PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 2.5.4
MxChat – AI Chatbot & Content Generation for WordPress v2.5.4
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 | js/mxchat-admin.js +2451 -238 2.0.52.5.4 View file →
@@ -10,9 +10,9 @@
10 10 timeout = setTimeout(later, wait);
11 11 };
12 12 }
13 13
14 -// Helper function to open edit modal
14 +// Helper function to open edit modal for intents/actions
15 15 function mxchatOpenEditModal(intentId, phrases) {
16 16 const modal = document.getElementById('mxchat-edit-modal');
17 17 if (!modal) return;
18 18
@@ -59,12 +59,145 @@
59 59
60 60 // Focus the textarea
61 61 phrasesField.focus();
62 62 }
63 +// Live Agent Notice Dismissal Function
64 +function dismissLiveAgentNotice() {
65 + if (typeof jQuery !== 'undefined' && typeof mxchatLiveAgent !== 'undefined') {
66 + jQuery.post(mxchatLiveAgent.ajaxurl, {
67 + action: 'dismiss_live_agent_notice',
68 + nonce: mxchatLiveAgent.nonce
69 + }, function(response) {
70 + if (response.success) {
71 + jQuery('#mxchat-disabled-notice').fadeOut(300);
72 + }
73 + }).fail(function() {
74 + // Fallback: just hide the notice if AJAX fails
75 + jQuery('#mxchat-disabled-notice').fadeOut(300);
76 + });
77 + } else {
78 + // Fallback for cases where jQuery or localized data isn't available
79 + var notice = document.getElementById('mxchat-disabled-notice');
80 + if (notice) {
81 + notice.style.display = 'none';
82 + }
83 + }
84 +}
63 85
86 +// Updated mxchatOpenActionModal function to integrate with the new selector
87 +function mxchatOpenActionModal(isEdit = false, actionId = '', label = '', phrases = '', threshold = 85, callbackFunction = '') {
88 + const modal = document.getElementById('mxchat-action-modal');
89 + if (!modal) return;
90 +
91 + // Get form fields
92 + const actionIdField = document.getElementById('edit_action_id');
93 + const labelField = document.getElementById('intent_label');
94 + const phrasesField = document.getElementById('action_phrases');
95 + const formActionType = document.getElementById('form_action_type');
96 + const callbackGroup = document.getElementById('callback_selection_group');
97 + const callbackSelect = document.getElementById('callback_function');
98 + const saveButton = document.getElementById('mxchat-save-action-btn');
99 + const nonceContainer = document.getElementById('action-nonce-container');
100 + const thresholdSlider = document.getElementById('similarity_threshold');
101 + const thresholdDisplay = document.querySelector('.mxchat-threshold-value-display');
102 +
103 + // Set up modal for edit or create
104 + if (isEdit) {
105 + saveButton.textContent = 'Update Action';
106 + formActionType.value = 'mxchat_edit_intent';
107 + actionIdField.value = actionId;
108 + labelField.value = label;
109 + phrasesField.value = phrases;
110 + callbackGroup.style.display = 'none'; // Hide callback selection when editing
111 + thresholdSlider.value = threshold; // Set the current threshold value
112 + thresholdDisplay.textContent = threshold + '%'; // Update display
113 +
114 + // Remove the required attribute when editing
115 + callbackSelect.removeAttribute('required');
116 +
117 + // Update the nonce field for editing
118 + nonceContainer.innerHTML = ''; // Clear existing nonce
119 + if (typeof mxchatAdmin !== 'undefined' && mxchatAdmin.edit_intent_nonce) {
120 + nonceContainer.innerHTML = `<input type="hidden" name="_wpnonce" value="${mxchatAdmin.edit_intent_nonce}">`;
121 + }
122 + } else {
123 + saveButton.textContent = 'Save Action';
124 + formActionType.value = 'mxchat_add_intent';
125 + actionIdField.value = '';
126 + labelField.value = '';
127 + phrasesField.value = '';
128 + callbackGroup.style.display = 'block'; // Show callback selection when creating
129 + thresholdSlider.value = 85; // Default value for new actions
130 + thresholdDisplay.textContent = '85%'; // Default display
131 +
132 + // Ensure the required attribute is present when adding
133 + callbackSelect.setAttribute('required', 'required');
134 +
135 + // Update the nonce field for adding
136 + nonceContainer.innerHTML = ''; // Clear existing nonce
137 + if (typeof mxchatAdmin !== 'undefined' && mxchatAdmin.add_intent_nonce) {
138 + nonceContainer.innerHTML = `<input type="hidden" name="_wpnonce" value="${mxchatAdmin.add_intent_nonce}">`;
139 + }
140 + }
141 +
142 + // Show modal with animation
143 + modal.style.display = 'flex';
144 + requestAnimationFrame(() => {
145 + modal.classList.add('active');
146 + });
147 +
148 + // Set up close handlers
149 + const closeModal = () => {
150 + modal.classList.remove('active');
151 + setTimeout(() => {
152 + modal.style.display = 'none';
153 + }, 300); // Match the CSS transition time
154 + };
155 +
156 + // Close button handler
157 + const closeBtn = modal.querySelector('.mxchat-modal-close');
158 + if (closeBtn) {
159 + closeBtn.onclick = closeModal;
160 + }
161 +
162 + // Cancel button handler
163 + const cancelBtn = modal.querySelector('.mxchat-modal-cancel');
164 + if (cancelBtn) {
165 + cancelBtn.onclick = closeModal;
166 + }
167 +
168 + // Click outside modal to close
169 + modal.onclick = (e) => {
170 + if (e.target === modal) {
171 + closeModal();
172 + }
173 + };
174 +
175 + // Escape key to close modal
176 + document.addEventListener('keydown', function(e) {
177 + if (e.key === 'Escape' && modal.classList.contains('active')) {
178 + closeModal();
179 + }
180 + }, { once: true });
181 +
182 + // Focus the first field
183 + labelField.focus();
184 +
185 + // Dispatch an event for the action type selector to catch
186 + const event = new CustomEvent('mxchatModalOpened', {
187 + detail: {
188 + isEdit: isEdit,
189 + callbackFunction: callbackFunction || (isEdit ? callbackSelect.value : '')
190 + }
191 + });
192 + document.dispatchEvent(event);
193 +
194 + return closeModal; // Return close function for external use
195 +}
196 +
64 197 // Initialize event listeners
65 198 document.addEventListener('DOMContentLoaded', () => {
66 - // Set up edit button handlers
199 + // Set up edit button handlers for intents
67 200 document.querySelectorAll('.mxchat-edit-button').forEach(button => {
68 201 button.onclick = () => {
69 202 const intentId = button.dataset.intentId;
70 203 const phrases = button.dataset.phrases;
@@ -70,8 +203,159 @@
70 203 const phrases = button.dataset.phrases;
71 204 mxchatOpenEditModal(intentId, phrases);
72 205 };
73 206 });
207 +
208 + document.querySelectorAll('.mxchat-action-card .mxchat-edit-button').forEach(button => {
209 + button.onclick = () => {
210 + const actionId = button.dataset.actionId;
211 + const phrases = button.dataset.phrases;
212 + const label = button.dataset.label;
213 + const threshold = button.dataset.threshold || 85;
214 + const callbackFunction = button.dataset.callbackFunction;
215 + const enabledBots = button.dataset.enabledBots; // ADD THIS LINE
216 +
217 + mxchatOpenActionModal(true, actionId, label, phrases, threshold, callbackFunction, enabledBots);
218 + };
219 + });
220 +
221 + // Set up add new action buttons (new functionality)
222 + const addActionBtn = document.getElementById('mxchat-add-action-btn');
223 + if (addActionBtn) {
224 + addActionBtn.onclick = () => mxchatOpenActionModal();
225 + }
226 +
227 + const createFirstAction = document.getElementById('mxchat-create-first-action');
228 + if (createFirstAction) {
229 + createFirstAction.onclick = () => mxchatOpenActionModal();
230 + }
231 +
232 + // Setup category-specific new action buttons (new functionality)
233 + document.querySelectorAll('.mxchat-new-action-button').forEach(button => {
234 + button.onclick = () => {
235 + const category = button.closest('.mxchat-new-action-card').dataset.category;
236 + const closeModal = mxchatOpenActionModal();
237 +
238 + // Pre-select the appropriate callback based on category
239 + if (category) {
240 + const callbackSelect = document.getElementById('callback_function');
241 + if (callbackSelect) {
242 + setTimeout(() => {
243 + // Map categories to default callbacks
244 + const categoryToCallback = {
245 + 'data_collection': 'mxchat_handle_form_collection',
246 + 'integrations': 'mxchat_handle_slack_message',
247 + 'custom_actions': 'mxchat_handle_custom_action',
248 + 'recommendations': 'mxchat_handle_product_recommendations'
249 + // Add more mappings as needed
250 + };
251 +
252 + if (categoryToCallback[category]) {
253 + callbackSelect.value = categoryToCallback[category];
254 + }
255 + }, 100);
256 + }
257 + }
258 + };
259 + });
260 +
261 + // Handle action toggle switches (new functionality)
262 + document.querySelectorAll('.mxchat-action-toggle').forEach(toggle => {
263 + toggle.onchange = function() {
264 + const actionId = this.dataset.actionId;
265 + const isEnabled = this.checked;
266 +
267 + // Show loading indicator
268 + const loadingEl = document.getElementById('mxchat-action-loading');
269 + if (loadingEl) loadingEl.style.display = 'flex';
270 +
271 + // Send AJAX request to update status
272 + fetch(ajaxurl, {
273 + method: 'POST',
274 + headers: {
275 + 'Content-Type': 'application/x-www-form-urlencoded',
276 + },
277 + body: new URLSearchParams({
278 + action: 'mxchat_toggle_action',
279 + intent_id: actionId,
280 + enabled: isEnabled ? 1 : 0,
281 + nonce: mxchatAdmin.toggle_action_nonce // Use the correct nonce
282 + })
283 + })
284 + .then(response => response.json())
285 + .then(data => {
286 + if (!data.success) {
287 + alert('Failed to update action status: ' + (data.data?.message || 'Unknown error'));
288 + this.checked = !isEnabled; // Revert the toggle
289 + }
290 + })
291 + .catch(error => {
292 + //console.error('Error:', error);
293 + alert('Server error. Please try again.');
294 + this.checked = !isEnabled; // Revert the toggle
295 + })
296 + .finally(() => {
297 + if (loadingEl) loadingEl.style.display = 'none';
298 + });
299 + };
300 + });
301 +
302 + // Handle threshold sliders in action cards (new functionality)
303 + document.querySelectorAll('.mxchat-threshold-slider').forEach(slider => {
304 + slider.oninput = function() {
305 + const actionId = this.id.replace('intent_threshold_', '');
306 + document.getElementById('threshold_output_' + actionId).textContent = this.value + '%';
307 + };
308 + });
309 +
310 + // Handle threshold save buttons in action cards (new functionality)
311 + document.querySelectorAll('.mxchat-threshold-save').forEach(button => {
312 + button.onclick = function(e) {
313 + e.preventDefault();
314 + const form = this.closest('form');
315 + const intentId = form.querySelector('input[name="intent_id"]').value;
316 + const threshold = form.querySelector('input[name="intent_threshold"]').value;
317 + const nonce = form.querySelector('input[name="_wpnonce"]').value;
318 +
319 + // Show loading indicator
320 + const loadingEl = document.getElementById('mxchat-action-loading');
321 + if (loadingEl) loadingEl.style.display = 'flex';
322 +
323 + // Send AJAX request
324 + fetch(ajaxurl, {
325 + method: 'POST',
326 + headers: {
327 + 'Content-Type': 'application/x-www-form-urlencoded',
328 + },
329 + body: new URLSearchParams({
330 + action: 'mxchat_update_intent_threshold',
331 + intent_id: intentId,
332 + intent_threshold: threshold,
333 + _wpnonce: nonce
334 + })
335 + })
336 + .then(response => response.json())
337 + .then(data => {
338 + if (data.success) {
339 + // Visual feedback of success
340 + const card = this.closest('.mxchat-action-card');
341 + card.style.background = 'rgba(120, 115, 245, 0.1)';
342 + setTimeout(() => {
343 + card.style.background = 'white';
344 + }, 300);
345 + } else {
346 + alert('Failed to update threshold: ' + (data.data?.message || 'Unknown error'));
347 + }
348 + })
349 + .catch(error => {
350 + //console.error('Error:', error);
351 + alert('Server error. Please try again.');
352 + })
353 + .finally(() => {
354 + if (loadingEl) loadingEl.style.display = 'none';
355 + });
356 + };
357 + });
74 358 });
75 359
76 360 jQuery(document).ready(function($) {
77 361 // Ensure we have a debounce function (use lodash if available, otherwise use our implementation)
@@ -77,11 +361,29 @@
77 361 // Ensure we have a debounce function (use lodash if available, otherwise use our implementation)
78 362 const useDebounce = (window._ && window._.debounce) ? window._.debounce : debounce;
79 363
80 364 // --- AJAX Auto-Save ---
81 - const $autosaveSections = $('.mxchat-autosave-section');
365 + let $autosaveSections = $('.mxchat-autosave-section');
366 +
367 + // *** ADD THIS: Extend auto-save sections to include Pinecone settings ***
368 + const $pineconeAutosaveSection = $('#mxchat-kb-tab-pinecone');
369 + if ($pineconeAutosaveSection.length) {
370 + $autosaveSections = $autosaveSections.add($pineconeAutosaveSection);
371 + //console.log('Added Pinecone section to auto-save monitoring');
372 + }
373 +
374 + // Track whether fields have been modified by user
375 + const userModifiedFields = new Set();
82 376
83 377 if ($autosaveSections.length) {
378 + // Track user interactions with input fields to determine if changes are user-initiated
379 + $autosaveSections.find('input, textarea, select').on('focus keydown paste', function() {
380 + const fieldName = $(this).attr('name');
381 + if (fieldName) {
382 + userModifiedFields.add(fieldName);
383 + }
384 + });
385 +
84 386 // Handle real-time range slider value updates
85 387 $autosaveSections.find('input[type="range"]').on('input', function() {
86 388 const value = $(this).val();
87 389 $('#threshold_value').text(value);
@@ -87,86 +389,213 @@
87 389 $('#threshold_value').text(value);
88 390 });
89 391
90 392 // Handle all input changes (including range slider)
91 - $autosaveSections.find('input, textarea, select').on('change', function() {
92 - const $field = $(this);
93 - const name = $field.attr('name');
94 - let value;
393 + $autosaveSections.find('input, textarea, select').not('#model, #openrouter_selected_model').on('change', function() {
394 + const $field = $(this);
395 + const name = $field.attr('name');
396 +
397 + // Skip saving for API key fields that haven't been interacted with and are empty
398 + const isApiKeyField = name && (
399 + name === 'loops_api_key' ||
400 + name === 'api_key' ||
401 + name === 'xai_api_key' ||
402 + name === 'claude_api_key' ||
403 + name === 'voyage_api_key' ||
404 + name === 'gemini_api_key' ||
405 + name === 'deepseek_api_key' ||
406 + name.indexOf('_api_key') !== -1
407 + );
408 +
409 + // Skip processing if:
410 + // 1. It's an API key field
411 + // 2. The user hasn't interacted with it
412 + // 3. The field is empty
413 + if (isApiKeyField && !userModifiedFields.has(name) && (!$field.val() || $field.val().trim() === '')) {
414 + //console.log('Skipping auto-save for untouched API key field:', name);
415 + return;
416 + }
417 +
418 + let value;
419 +
420 + // Handle different input types
421 + if ($field.attr('type') === 'checkbox') {
422 + // *** UPDATED: Handle Pinecone checkboxes differently ***
423 + if (name && name.indexOf('mxchat_pinecone_addon_options') !== -1) {
424 + value = $field.is(':checked') ? '1' : '0';
425 + } else {
426 + value = $field.is(':checked') ? 'on' : 'off';
427 + }
428 + } else {
429 + value = $field.val();
430 + }
431 +
432 + // Create feedback container
433 + const feedbackContainer = $('<div class="feedback-container"></div>');
434 + const spinner = $('<div class="saving-spinner"></div>');
435 + const successIcon = $('<div class="success-icon">✔</div>');
436 +
437 + // Position feedback container based on input type
438 + if ($field.closest('.toggle-switch').length) {
439 + $field.closest('td').append(feedbackContainer);
440 + } else if ($field.closest('.mxchat-toggle-switch').length) {
441 + $field.closest('.mxchat-toggle-container').append(feedbackContainer);
442 + } else if ($field.closest('.slider-container').length) {
443 + $field.closest('.slider-container').after(feedbackContainer);
444 + } else {
445 + $field.after(feedbackContainer);
446 + }
447 + feedbackContainer.append(spinner);
448 +
449 + // Determine which AJAX action and nonce to use:
450 + var ajaxAction, nonce;
451 + // *** UPDATED: Add Pinecone fields to prompts action ***
452 + if (name.indexOf('mxchat_prompts_options') !== -1 ||
453 + name === 'mxchat_auto_sync_posts' ||
454 + name === 'mxchat_auto_sync_pages' ||
455 + name.indexOf('mxchat_auto_sync_') === 0 ||
456 + name.indexOf('mxchat_pinecone_addon_options') !== -1) { // *** ADD THIS LINE ***
457 + ajaxAction = 'mxchat_save_prompts_setting';
458 + nonce = mxchatPromptsAdmin.prompts_setting_nonce;
459 + } else {
460 + // Otherwise, use the existing AJAX action.
461 + ajaxAction = 'mxchat_save_setting';
462 + nonce = mxchatAdmin.setting_nonce;
463 + }
464 +
465 + // *** ADD THIS: Debug logging for Pinecone fields ***
466 + if (name && name.indexOf('mxchat_pinecone_addon_options') !== -1) {
467 + //console.log('Saving Pinecone field:', name, '=', value);
468 + }
469 +
470 + // AJAX save request
471 + $.ajax({
472 + url: (ajaxAction === 'mxchat_save_prompts_setting') ? mxchatPromptsAdmin.ajax_url : mxchatAdmin.ajax_url,
473 + type: 'POST',
474 + data: {
475 + action: ajaxAction,
476 + name: name,
477 + value: value,
478 + _ajax_nonce: nonce
479 + },
480 + success: function(response) {
481 + if (response.success) {
482 + spinner.fadeOut(200, function() {
483 + feedbackContainer.append(successIcon);
484 + successIcon.fadeIn(200).delay(1000).fadeOut(200, function() {
485 + feedbackContainer.remove();
486 + });
487 + });
95 488
96 - // Handle different input types
97 - if ($field.attr('type') === 'checkbox') {
98 - value = $field.is(':checked') ? 'on' : 'off';
99 - } else {
100 - value = $field.val();
101 - }
489 + // *** ADD THIS: Refresh API key status after saving an API key ***
490 + const isApiKeyField = name && (
491 + name === 'api_key' ||
492 + name === 'xai_api_key' ||
493 + name === 'claude_api_key' ||
494 + name === 'voyage_api_key' ||
495 + name === 'gemini_api_key' ||
496 + name === 'deepseek_api_key' ||
497 + name === 'openrouter_api_key' ||
498 + name.indexOf('_api_key') !== -1
499 + );
102 500
103 - // Create feedback container
104 - const feedbackContainer = $('<div class="feedback-container"></div>');
105 - const spinner = $('<div class="saving-spinner"></div>');
106 - const successIcon = $('<div class="success-icon">✔</div>');
501 + if (isApiKeyField && typeof window.mxchatRefreshAPIKeyStatus === 'function') {
502 + window.mxchatRefreshAPIKeyStatus();
503 + }
107 504
108 - // Position feedback container based on input type
109 - if ($field.closest('.toggle-switch').length) {
110 - $field.closest('td').append(feedbackContainer);
111 - } else if ($field.closest('.mxchat-toggle-switch').length) {
112 - $field.closest('.mxchat-toggle-container').append(feedbackContainer);
113 - } else if ($field.closest('.slider-container').length) {
114 - $field.closest('.slider-container').after(feedbackContainer);
505 + // *** ADD THIS: Update Pinecone checkbox state after successful save ***
506 + if (name && name.indexOf('mxchat_pinecone_addon_options[mxchat_use_pinecone]') !== -1) {
507 + //console.log('Pinecone toggle saved successfully, value:', value);
508 +
509 + // The checkbox state is already updated by the user interaction
510 + // But let's make sure the UI state matches the saved value
511 + var $checkbox = $('input[name="mxchat_pinecone_addon_options[mxchat_use_pinecone]"]');
512 + var settingsDiv = $('.mxchat-pinecone-settings');
513 +
514 + // Double-check the UI state matches what was saved
515 + if (value === '1' && !$checkbox.is(':checked')) {
516 + $checkbox.prop('checked', true);
517 + settingsDiv.slideDown(300);
518 + } else if (value === '0' && $checkbox.is(':checked')) {
519 + $checkbox.prop('checked', false);
520 + settingsDiv.slideUp(300);
521 + }
522 +
523 + //console.log('Pinecone UI state synchronized');
524 +
525 + // Check if Knowledge Import tab is currently active
526 + if ($('.mxchat-kb-tab-button[data-tab="import"]').hasClass('active')) {
527 + // Show a notice that we need to refresh
528 + var $knowledgeCard = $('#mxchat-kb-tab-import .mxchat-card').eq(1);
529 + if ($knowledgeCard.length > 0) {
530 + // Add a refresh notice at the top of the knowledge base card
531 + var refreshNotice = $('<div class="notice notice-warning" style="margin: 15px 0; padding: 10px 15px;">' +
532 + '<p style="margin: 0;">' +
533 + '<span class="dashicons dashicons-info" style="color: #f0ad4e; margin-right: 5px;"></span>' +
534 + 'Database settings have changed. ' +
535 + '<a href="#" onclick="location.reload(); return false;" style="font-weight: bold;">Click here to refresh</a> to see the updated knowledge base.' +
536 + '</p></div>');
537 +
538 + $knowledgeCard.prepend(refreshNotice);
539 + }
540 + } else {
541 + // If not on import tab, set a flag to refresh when they go there
542 + sessionStorage.setItem('mxchat_pinecone_changed', 'true');
543 + }
544 + }
545 +
546 + // *** ADD THIS: Debug logging for successful saves ***
547 + if (name && name.indexOf('mxchat_pinecone_addon_options') !== -1) {
548 + //console.log('Pinecone field saved successfully:', name, '=', value);
549 + }
550 +
551 + // Check if the response contains a "no changes" message and log it
552 + if (response.data && response.data.message === 'No changes detected') {
553 + //console.log('No changes detected for field:', name);
554 + }
115 555 } else {
116 - $field.after(feedbackContainer);
117 - }
118 - feedbackContainer.append(spinner);
119 -
120 - // Determine which AJAX action and nonce to use:
121 - var ajaxAction, nonce;
122 - // Use the new AJAX action for submenu fields:
123 - if ( name.indexOf('mxchat_prompts_options') !== -1 ||
124 - name === 'mxchat_auto_sync_posts' ||
125 - name === 'mxchat_auto_sync_pages' ) {
126 - ajaxAction = 'mxchat_save_prompts_setting';
127 - nonce = mxchatPromptsAdmin.prompts_setting_nonce;
128 - } else {
129 - // Otherwise, use the existing AJAX action.
130 - ajaxAction = 'mxchat_save_setting';
131 - nonce = mxchatAdmin.setting_nonce;
132 - }
133 -
134 - // AJAX save request
135 - $.ajax({
136 - url: (ajaxAction === 'mxchat_save_prompts_setting') ? mxchatPromptsAdmin.ajax_url : mxchatAdmin.ajax_url,
137 - type: 'POST',
138 - data: {
139 - action: ajaxAction,
140 - name: name,
141 - value: value,
142 - _ajax_nonce: nonce
143 - },
144 - success: function(response) {
145 - if (response.success) {
146 - spinner.fadeOut(200, function() {
147 - feedbackContainer.append(successIcon);
148 - successIcon.fadeIn(200).delay(1000).fadeOut(200, function() {
149 - feedbackContainer.remove();
150 - });
556 + // Only show alert for actual errors, not for "no changes"
557 + let errorMessage = response.data?.message || 'Unknown error';
558 +
559 + // Don't display an alert for "no changes" message
560 + if (errorMessage !== 'No changes detected' && errorMessage !== 'Update failed or no changes') {
561 + alert('Error saving: ' + errorMessage);
562 + } else {
563 + // Still provide visual feedback that no changes were needed
564 + spinner.fadeOut(200, function() {
565 + feedbackContainer.append(successIcon);
566 + successIcon.fadeIn(200).delay(1000).fadeOut(200, function() {
567 + feedbackContainer.remove();
151 568 });
152 - } else {
153 - alert('Error saving: ' + (response.data?.message || 'Unknown error'));
154 - if ($field.attr('type') === 'checkbox') {
155 - $field.prop('checked', !$field.is(':checked'));
156 - }
157 - feedbackContainer.remove();
158 - }
159 - },
160 - error: function() {
161 - alert('An error occurred while saving.');
569 + });
570 + //console.log('No changes detected for field:', name);
571 + return;
572 + }
573 +
574 + // Only revert checkbox state if it was an actual error
575 + if (errorMessage !== 'No changes detected' && errorMessage !== 'Update failed or no changes') {
162 576 if ($field.attr('type') === 'checkbox') {
163 577 $field.prop('checked', !$field.is(':checked'));
164 578 }
165 - feedbackContainer.remove();
166 579 }
167 - });
168 - });
580 +
581 + // Always clean up the feedback container
582 + feedbackContainer.remove();
583 + }
584 + },
585 + error: function(xhr, textStatus, error) {
586 + //console.error('AJAX Error:', textStatus, error);
587 + alert('An error occurred while saving. Please try again.');
588 +
589 + // Revert checkbox state on error
590 + if ($field.attr('type') === 'checkbox') {
591 + $field.prop('checked', !$field.is(':checked'));
592 + }
593 +
594 + feedbackContainer.remove();
595 + }
596 + });
597 + });
169 598
170 599 // Initialize color pickers with debouncing
171 600 $autosaveSections.find('.my-color-field').each(function() {
172 601 const $colorField = $(this);
@@ -174,9 +603,9 @@
174 603 $(this).wpColorPicker({
175 604 change: useDebounce(function(event, ui) {
176 605 // Safety check - ensure we have a valid field and value
177 606 if (!$colorField || !$colorField.val()) {
178 - console.warn('Color picker not ready');
607 + //console.warn('Color picker not ready');
179 608 return;
180 609 }
181 610
182 611 const name = $colorField.attr('name');
@@ -182,9 +611,9 @@
182 611 const name = $colorField.attr('name');
183 612 const value = $colorField.val();
184 613
185 614 if (!name || !value) {
186 - console.warn('Missing required color picker values');
615 + //console.warn('Missing required color picker values');
187 616 return;
188 617 }
189 618
190 619 // Create feedback container
@@ -195,20 +624,22 @@
195 624 // Position feedback container
196 625 $colorField.closest('.wp-picker-container').after(feedbackContainer);
197 626 feedbackContainer.append(spinner);
198 627
199 - // Determine AJAX action and nonce for color fields:
628 + // Determine which AJAX action and nonce to use:
200 629 var ajaxAction, nonce;
201 - if ( name.indexOf('mxchat_prompts_options') !== -1 ||
202 - name === 'mxchat_auto_sync_posts' ||
203 - name === 'mxchat_auto_sync_pages' ) {
630 + // Use the new AJAX action for submenu fields:
631 + if (name.indexOf('mxchat_prompts_options') !== -1 ||
632 + name === 'mxchat_auto_sync_posts' ||
633 + name === 'mxchat_auto_sync_pages' ||
634 + name.indexOf('mxchat_auto_sync_') === 0) { // Modified to catch all auto-sync fields
204 635 ajaxAction = 'mxchat_save_prompts_setting';
205 636 nonce = mxchatPromptsAdmin.prompts_setting_nonce;
206 637 } else {
638 + // Otherwise, use the existing AJAX action.
207 639 ajaxAction = 'mxchat_save_setting';
208 640 nonce = mxchatAdmin.setting_nonce;
209 641 }
210 -
211 642 // AJAX save request
212 643 $.ajax({
213 644 url: (ajaxAction === 'mxchat_save_prompts_setting') ? mxchatPromptsAdmin.ajax_url : mxchatAdmin.ajax_url,
214 645 type: 'POST',
@@ -240,9 +671,9 @@
240 671 });
241 672 });
242 673
243 674 // Reinitialize color pickers when switching tabs
244 - $('.mxchat-nav-tab').on('click.mxchat', function() {
675 + $('.mxchat-tab-button').on('click.mxchat', function() {
245 676 setTimeout(function() {
246 677 $('.my-color-field:visible').wpColorPicker('close');
247 678 }, 100);
248 679 });
@@ -247,107 +678,972 @@
247 678 }, 100);
248 679 });
249 680 }
250 681
251 - // Initialize tabs system
252 - function initTabs() {
253 - // Remove any existing handlers first
254 - $('.mxchat-nav-tab').off('click.mxchat');
682 +// Initialize tabs system
683 +function initTabs() {
684 + // Remove any existing handlers first
685 + $('.mxchat-tab-button').off('click.mxchat');
686 +
687 + // Add new click handlers
688 + $('.mxchat-tab-button').on('click.mxchat', function(e) {
689 + e.preventDefault();
690 + e.stopPropagation();
255 691
256 - // Add new click handlers
257 - $('.mxchat-nav-tab').on('click.mxchat', function(e) {
258 - e.preventDefault();
259 - e.stopPropagation();
692 + var $this = $(this);
693 +
694 + // Get tab ID from data-tab attribute
695 + var tabId = $this.data('tab') || 'chatbot';
696 +
697 + // Safety check for empty tabId
698 + if (!tabId) {
699 + //console.warn('No tab identifier found');
700 + return;
701 + }
702 +
703 + // Update tab buttons
704 + $('.mxchat-tab-button').removeClass('active');
705 + $this.addClass('active');
706 +
707 + // Update content areas - with safety check
708 + $('.mxchat-tab-content').removeClass('active');
709 + var $targetTab = $('#' + tabId);
710 + if ($targetTab.length) {
711 + $targetTab.addClass('active');
712 + // Removed localStorage saving functionality
713 + } else {
714 + //console.warn('Tab content #' + tabId + ' not found');
715 + }
716 + });
717 +}
718 +
719 +// Initialize tabs and handle events
720 +initTabs();
721 +$(document).on('widget-added widget-updated postbox-toggled', initTabs);
722 +
723 +// Always activate the first tab (Chatbot)
724 +$('.mxchat-tab-button').first().trigger('click.mxchat');
725 +
726 +
727 +// Toggle visibility handlers
728 +function toggleVisibility(selector) {
729 + $(selector).on('click', function() {
730 + var inputField = $(this).prev('input');
731 + if (inputField.attr('type') === 'password') {
732 + inputField.attr('type', 'text');
733 + $(this).text('Hide');
734 + } else {
735 + inputField.attr('type', 'password');
736 + $(this).text('Show');
737 + }
738 + });
739 +}
740 +
741 +// Initialize all toggle visibility buttons
742 +[
743 + '#toggleApiKeyVisibility',
744 + '#toggleWooCommerceSecretVisibility',
745 + '#toggleVoyageAPIKeyVisibility',
746 + '#toggleLoopsApiKeyVisibility',
747 + '#toggleXaiApiKeyVisibility',
748 + '#toggleClaudeApiKeyVisibility',
749 + '#toggleBraveApiKeyVisibility',
750 + '#toggleWebhookUrlVisibility',
751 + '#toggleSecretKeyVisibility',
752 + '#toggleBotTokenVisibility',
753 + '#toggleDeepSeekApiKeyVisibility',
754 + '#toggleGeminiApiKeyVisibility',
755 + '#toggleOpenRouterApiKeyVisibility'
756 +].forEach(toggleVisibility);
757 +
758 +function setupMxChatModelSelector() {
759 + const $modelSelect = $('#model');
760 + const $modelSelectorButton = $('<button>', {
761 + type: 'button',
762 + id: 'mxchat_model_selector_btn',
763 + class: 'button-primary mxchat-model-selector-btn',
764 + text: 'Select AI Model'
765 + });
766 +
767 + // Replace the select dropdown with a button
768 + $modelSelect.hide().after($modelSelectorButton);
769 +
770 + // Update button text to show currently selected model
771 + function updateButtonText() {
772 + const selectedModel = $modelSelect.val();
773 +
774 + // Check if OpenRouter is selected
775 + if (selectedModel === 'openrouter') {
776 + const openrouterModelId = $('#openrouter_selected_model').val();
777 + const openrouterModelName = $('#openrouter_selected_model_name').val();
260 778
261 - var $this = $(this);
262 -
263 - // Get tab ID - try href first, fallback to data-tab, then to default
264 - var tabId = $this.attr('href');
265 - if (tabId) {
266 - tabId = tabId.replace('#', '');
779 + if (openrouterModelName && openrouterModelName.trim() !== '') {
780 + $modelSelectorButton.text('OpenRouter: ' + openrouterModelName);
781 + } else if (openrouterModelId && openrouterModelId.trim() !== '') {
782 + $modelSelectorButton.text('OpenRouter: ' + openrouterModelId);
267 783 } else {
268 - tabId = $this.data('tab') || 'chatbot';
784 + $modelSelectorButton.text('OpenRouter - Select Model');
269 785 }
270 -
271 - // Safety check for empty tabId
272 - if (!tabId) {
273 - console.warn('No tab identifier found');
274 - return;
786 + } else {
787 + const selectedModelText = $modelSelect.find('option:selected').text();
788 + $modelSelectorButton.text(selectedModelText);
789 + }
790 + }
791 +
792 + // Initialize button text
793 + updateButtonText();
794 +
795 + // Create and append modal HTML
796 + const modelSelectorModal = `
797 + <div id="mxchat_model_selector_modal" class="mxchat-model-selector-modal">
798 + <div class="mxchat-model-selector-modal-content">
799 + <div class="mxchat-model-selector-modal-header">
800 + <h3>Select AI Model</h3>
801 + <span class="mxchat-model-selector-modal-close">&times;</span>
802 + </div>
803 + <div class="mxchat-model-selector-modal-body">
804 + <div class="mxchat-model-selector-search-container">
805 + <input type="text" id="mxchat_model_search_input" class="mxchat-model-search-input" placeholder="Search models...">
806 + </div>
807 + <div class="mxchat-model-selector-categories">
808 + <button class="mxchat-model-category-btn active" data-category="all">All</button>
809 + <button class="mxchat-model-category-btn" data-category="openrouter">OpenRouter</button>
810 + <button class="mxchat-model-category-btn" data-category="gemini">Google Gemini</button>
811 + <button class="mxchat-model-category-btn" data-category="openai">OpenAI</button>
812 + <button class="mxchat-model-category-btn" data-category="claude">Claude</button>
813 + <button class="mxchat-model-category-btn" data-category="xai">X.AI</button>
814 + <button class="mxchat-model-category-btn" data-category="deepseek">DeepSeek</button>
815 + </div>
816 + <div class="mxchat-model-selector-grid" id="mxchat_models_grid"></div>
817 + </div>
818 + <div class="mxchat-model-selector-modal-footer">
819 + <button id="mxchat_cancel_model_selection" class="button mxchat-model-cancel-btn">Cancel</button>
820 + </div>
821 + </div>
822 + </div>
823 + `;
824 +
825 + $('body').append(modelSelectorModal);
826 +
827 + // MOVE THIS OUTSIDE - Make it a property of the window object so it's accessible globally
828 + window.populateModelsGrid = function(filter = '', category = 'all') {
829 + const $grid = $('#mxchat_models_grid');
830 + $grid.empty();
831 +
832 + const models = {
833 + openrouter: [
834 + { value: 'openrouter', label: 'OpenRouter', description: 'Access 100+ models from multiple providers (add API key to browse)' }
835 + ],
836 + gemini: [
837 + { value: 'gemini-2.0-flash', label: 'Gemini 2.0 Flash', description: 'Next-Gen features, speed & multimodal generation' },
838 + { value: 'gemini-2.0-flash-lite', label: 'Gemini 2.0 Flash-Lite', description: 'Cost-efficient with low latency' },
839 + { value: 'gemini-1.5-pro', label: 'Gemini 1.5 Pro', description: 'Complex reasoning tasks requiring more intelligence' },
840 + { value: 'gemini-1.5-flash', label: 'Gemini 1.5 Flash', description: 'Fast and versatile performance' },
841 + ],
842 + openai: [
843 + { value: 'gpt-5', label: 'GPT-5', description: 'Flagship for coding, reasoning, and agentic tasks across domains' },
844 + { value: 'gpt-5-mini', label: 'GPT-5 Mini', description: 'Faster, more cost-efficient for well-defined tasks and precise prompts' },
845 + { value: 'gpt-5-nano', label: 'GPT-5 Nano', description: 'Fastest and cheapest; ideal for summarization and classification' },
846 + { value: 'gpt-4.1-2025-04-14', label: 'GPT-4.1', description: 'Flagship model for complex tasks' },
847 + { value: 'gpt-4o', label: 'GPT-4o', description: 'Recommended for most use cases' },
848 + { value: 'gpt-4o-mini', label: 'GPT-4o Mini', description: 'Fast and lightweight' },
849 + { value: 'gpt-4-turbo', label: 'GPT-4 Turbo', description: 'High-performance model' },
850 + { value: 'gpt-4', label: 'GPT-4', description: 'High intelligence model' },
851 + { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo', description: 'Affordable and fast' },
852 + ],
853 + claude: [
854 + { value: 'claude-sonnet-4-5-20250929', label: 'Claude Sonnet 4.5', description: 'Best for complex agents and coding' },
855 + { value: 'claude-opus-4-1-20250805', label: 'Claude Opus 4.1', description: 'Exceptional for specialized complex tasks' },
856 + { value: 'claude-haiku-4-5-20251001', label: 'Claude Haiku 4.5', description: 'Fastest and most intelligent Haiku' },
857 + { value: 'claude-opus-4-20250514', label: 'Claude 4 Opus', description: 'Most capable Claude model' },
858 + { value: 'claude-sonnet-4-20250514', label: 'Claude 4 Sonnet', description: 'High performance' },
859 + { value: 'claude-3-7-sonnet-20250219', label: 'Claude 3.7 Sonnet', description: 'High intelligence' },
860 + { value: 'claude-3-opus-20240229', label: 'Claude 3 Opus', description: 'Highly complex tasks' },
861 + { value: 'claude-3-sonnet-20240229', label: 'Claude 3 Sonnet', description: 'Balanced performance' },
862 + { value: 'claude-3-haiku-20240307', label: 'Claude 3 Haiku', description: 'Fastest Claude model' },
863 + ],
864 + xai: [
865 + { value: 'grok-4-0709', label: 'Grok 4', description: 'Latest flagship model - unparalleled performance in natural language, math and reasoning' },
866 + { value: 'grok-3-beta', label: 'Grok-3', description: 'Powerful model with 131K context' },
867 + { value: 'grok-3-fast-beta', label: 'Grok-3 Fast', description: 'High performance with faster responses' },
868 + { value: 'grok-3-mini-beta', label: 'Grok-3 Mini', description: 'Affordable model with good performance' },
869 + { value: 'grok-3-mini-fast-beta', label: 'Grok-3 Mini Fast', description: 'Quick and cost-effective' },
870 + { value: 'grok-2', label: 'Grok 2', description: 'Latest X.AI model' },
871 + ],
872 + deepseek: [
873 + { value: 'deepseek-chat', label: 'DeepSeek-V3', description: 'Advanced AI assistant' },
874 + ],
875 + };
876 +
877 + let allModels = [];
878 + Object.keys(models).forEach(key => {
879 + if (category === 'all' || category === key) {
880 + allModels = allModels.concat(models[key]);
275 881 }
882 + });
883 +
884 + // Filter by search term if present
885 + if (filter) {
886 + const lowerFilter = filter.toLowerCase();
887 + allModels = allModels.filter(model =>
888 + model.label.toLowerCase().includes(lowerFilter) ||
889 + model.description.toLowerCase().includes(lowerFilter)
890 + );
891 + }
892 +
893 + // Create model cards
894 + allModels.forEach(model => {
895 + const isSelected = $modelSelect.val() === model.value;
896 + const $modelCard = $(`
897 + <div class="mxchat-model-selector-card ${isSelected ? 'mxchat-model-selected' : ''}" data-value="${model.value}">
898 + <div class="mxchat-model-selector-icon">${getModelIcon(model.value)}</div>
899 + <div class="mxchat-model-selector-info">
900 + <h4 class="mxchat-model-selector-title">${model.label}</h4>
901 + <p class="mxchat-model-selector-description">${model.description}</p>
902 + </div>
903 + ${isSelected ? '<div class="mxchat-model-selector-checkmark">✓</div>' : ''}
904 + </div>
905 + `);
906 + $grid.append($modelCard);
907 + });
908 + };
909 +
910 + // Helper function to get icon for each model
911 + function getModelIcon(modelValue) {
912 + if (modelValue === 'openrouter') return '<span class="dashicons dashicons-networking" style="font-size: 24px; color: #6750A4;"></span>';
913 + if (modelValue.startsWith('gemini-')) return '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 48 48" class="mxchat-model-icon-gemini"><defs><path id="a" d="M44.5 20H24v8.5h11.8C34.7 33.9 30.1 37 24 37c-7.2 0-13-5.8-13-13s5.8-13 13-13c3.1 0 5.9 1.1 8.1 2.9l6.4-6.4C34.6 4.1 29.6 2 24 2 11.8 2 2 11.8 2 24s9.8 22 22 22c11 0 21-8 21-22 0-1.3-.2-2.7-.5-4z"></path></defs><clipPath id="b"><use xlink:href="#a" overflow="visible"></use></clipPath><path clip-path="url(#b)" fill="#FBBC05" d="M0 37V11l17 13z"></path><path clip-path="url(#b)" fill="#EA4335" d="M0 11l17 13 7-6.1L48 14V0H0z"></path><path clip-path="url(#b)" fill="#34A853" d="M0 37l30-23 7.9 1L48 0v48H0z"></path><path clip-path="url(#b)" fill="#4285F4" d="M48 48L17 24l-4-3 35-10z"></path></svg>';
914 + if (modelValue.startsWith('gpt-')) return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320" class="mxchat-model-icon-openai"><path fill="currentColor" d="M297 131a80.6 80.6 0 0 0-93.7-104.2 80.6 80.6 0 0 0-137 29A80.6 80.6 0 0 0 23 189a80.6 80.6 0 0 0 93.7 104.2 80.6 80.6 0 0 0 137-29A80.7 80.7 0 0 0 297.1 131zM176.9 299c-14 .1-27.6-4.8-38.4-13.8l1.9-1 63.7-36.9c3.3-1.8 5.3-5.3 5.2-9v-89.9l27 15.6c.3.1.4.4.5.7v74.4a60 60 0 0 1-60 60zM47.9 244a59.7 59.7 0 0 1-7.1-40.1l1.9 1.1 63.7 36.8c3.2 1.9 7.2 1.9 10.5 0l77.8-45V228c0 .3-.2.6-.4.8L129.9 266a60 60 0 0 1-82-22zM31.2 105c7-12.2 18-21.5 31.2-26.3v75.8c0 3.7 2 7.2 5.2 9l77.8 45-27 15.5a1 1 0 0 1-.9 0L53.1 187a60 60 0 0 1-22-82zm221.2 51.5-77.8-45 27-15.5a1 1 0 0 1 .9 0l64.4 37.1a60 60 0 0 1-9.3 108.2v-75.8c0-3.7-2-7.2-5.2-9zm26.8-40.4-1.9-1.1-63.7-36.8a10.4 10.4 0 0 0-10.5 0L125.4 123V92c0-.3 0-.6.3-.8L190.1 54a60 60 0 0 1 89.1 62.1zm-168.5 55.4-27-15.5a1 1 0 0 1-.4-.7V80.9a60 60 0 0 1 98.3-46.1l-1.9 1L116 72.8a10.3 10.3 0 0 0-5.2 9v89.8zm14.6-31.5 34.7-20 34.6 20v40L160 200l-34.7-20z"></path></svg>';
915 + if (modelValue.startsWith('claude-')) return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 176" fill="none" class="mxchat-model-icon-claude"><path fill="currentColor" d="m147.487 0l70.081 175.78H256L185.919 0zM66.183 106.221l23.98-61.774l23.98 61.774zM70.07 0L0 175.78h39.18l14.33-36.914h73.308l14.328 36.914h39.179L110.255 0z"></path></svg>';
916 + if (modelValue.startsWith('grok-')) return '<svg fill="currentColor" fill-rule="evenodd" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="mxchat-model-icon-xai"><path d="M6.469 8.776L16.512 23h-4.464L2.005 8.776H6.47zm-.004 7.9l2.233 3.164L6.467 23H2l4.465-6.324zM22 2.582V23h-3.659V7.764L22 2.582zM22 1l-9.952 14.095-2.233-3.163L17.533 1H22z"></path></svg>';
917 + if (modelValue.startsWith('deepseek-')) return '<svg height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg" class="mxchat-model-icon-deepseek"><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="currentColor"></path></svg>';
918 + return '<span class="dashicons dashicons-admin-generic mxchat-model-icon-generic"></span>';
919 + }
920 +
921 + // Event handlers
922 + $modelSelectorButton.on('click', function() {
923 + $('#mxchat_model_selector_modal').show();
924 + window.populateModelsGrid('', 'all');
925 + });
926 +
927 + $('.mxchat-model-selector-modal-close, #mxchat_cancel_model_selection').on('click', function() {
928 + $('#mxchat_model_selector_modal').hide();
929 + });
930 +
931 + $('.mxchat-model-category-btn').on('click', function() {
932 + $('.mxchat-model-category-btn').removeClass('active');
933 + $(this).addClass('active');
934 + const category = $(this).data('category');
935 + const searchTerm = $('#mxchat_model_search_input').val();
936 + window.populateModelsGrid(searchTerm, category);
937 + });
938 +
939 + $('#mxchat_model_search_input').on('input', function() {
940 + const searchTerm = $(this).val();
941 + const activeCategory = $('.mxchat-model-category-btn.active').data('category');
942 + window.populateModelsGrid(searchTerm, activeCategory);
943 + });
944 +
945 +$(document).on('click', '.mxchat-model-selector-card', function() {
946 + const modelValue = $(this).data('value');
947 + const $modelSelect = $('#model');
948 + const $clickedCard = $(this);
949 +
950 + // Check if OpenRouter was selected
951 + if (modelValue === 'openrouter') {
952 + // Load OpenRouter models instead of closing
953 + loadOpenRouterModels();
954 + } else {
955 + // Remove selection from all other cards
956 + $('.mxchat-model-selector-card').removeClass('mxchat-model-selected').find('.mxchat-model-selector-checkmark').remove();
957 +
958 + // Add selection to clicked card immediately for instant feedback
959 + $clickedCard.addClass('mxchat-model-selected');
960 + if ($clickedCard.find('.mxchat-model-selector-checkmark').length === 0) {
961 + $clickedCard.append('<div class="mxchat-model-selector-checkmark">✓</div>');
962 + }
963 +
964 + // Brief delay to show the selection, then start saving
965 + setTimeout(function() {
966 + // Normal model selection
967 + $modelSelect.val(modelValue).trigger('change');
968 +
969 + // Show loading state on the card
970 + $clickedCard.css('pointer-events', 'none');
971 + const originalContent = $clickedCard.find('.mxchat-model-selector-title').html();
972 + $clickedCard.find('.mxchat-model-selector-title').html(
973 + '<span class="spinner is-active" style="float: none; margin: 0 5px 0 0;"></span> Saving...'
974 + );
975 +
976 + // Manually save the model via AJAX
977 + jQuery.ajax({
978 + url: mxchatAdmin.ajax_url,
979 + type: 'POST',
980 + data: {
981 + action: 'mxchat_save_setting',
982 + name: 'model',
983 + value: modelValue,
984 + _ajax_nonce: mxchatAdmin.setting_nonce
985 + },
986 + success: function(response) {
987 + if (response.success) {
988 + // Show success state
989 + $clickedCard.find('.mxchat-model-selector-title').html(
990 + '<span class="dashicons dashicons-yes" style="color: #46b450; margin-top: 3px;"></span> Saved!'
991 + );
992 +
993 + // Update button text after successful save
994 + const selectedModelText = $modelSelect.find('option:selected').text();
995 + $('#mxchat_model_selector_btn').text(selectedModelText);
996 +
997 + // Close modal after a short delay to show the success message
998 + setTimeout(function() {
999 + $('#mxchat_model_selector_modal').hide();
1000 + // Restore original content and remove selection for next time
1001 + $clickedCard.find('.mxchat-model-selector-title').html(originalContent);
1002 + $clickedCard.removeClass('mxchat-model-selected').find('.mxchat-model-selector-checkmark').remove();
1003 + $clickedCard.css('pointer-events', 'auto');
1004 + }, 600);
1005 + } else {
1006 + // Show error state
1007 + $clickedCard.find('.mxchat-model-selector-title').html(
1008 + '<span class="dashicons dashicons-no" style="color: #dc3232;"></span> Error!'
1009 + );
1010 +
1011 + setTimeout(function() {
1012 + $clickedCard.find('.mxchat-model-selector-title').html(originalContent);
1013 + $clickedCard.removeClass('mxchat-model-selected').find('.mxchat-model-selector-checkmark').remove();
1014 + $clickedCard.css('pointer-events', 'auto');
1015 + }, 1500);
1016 + }
1017 + },
1018 + error: function() {
1019 + // Show error state
1020 + $clickedCard.find('.mxchat-model-selector-title').html(
1021 + '<span class="dashicons dashicons-no" style="color: #dc3232;"></span> Error!'
1022 + );
1023 +
1024 + setTimeout(function() {
1025 + $clickedCard.find('.mxchat-model-selector-title').html(originalContent);
1026 + $clickedCard.removeClass('mxchat-model-selected').find('.mxchat-model-selector-checkmark').remove();
1027 + $clickedCard.css('pointer-events', 'auto');
1028 + }, 1500);
1029 + }
1030 + });
1031 + }, 300); // 300ms delay to show the selection before starting to save
1032 + }
1033 +});
1034 +
1035 + // Close modal when clicking outside
1036 + $(window).on('click', function(event) {
1037 + if ($(event.target).is('#mxchat_model_selector_modal')) {
1038 + $('#mxchat_model_selector_modal').hide();
1039 + }
1040 + });
1041 +}
1042 +
1043 +function loadOpenRouterModels() {
1044 + const apiKey = $('#openrouter_api_key').val(); // This line already re-checks the field
1045 + const $modal = $('#mxchat_model_selector_modal');
1046 + const $modalBody = $modal.find('.mxchat-model-selector-modal-body');
1047 +
1048 + if (!apiKey || apiKey.trim() === '') {
1049 + // Show error message in modal
1050 + $modalBody.html(`
1051 + <div style="text-align: center; padding: 40px;">
1052 + <span class="dashicons dashicons-warning" style="font-size: 48px; color: #d63638; margin-bottom: 20px;"></span>
1053 + <h3>OpenRouter API Key Required</h3>
1054 + <p>Please enter your OpenRouter API key in the settings before selecting a model. If you're seeing this message and recently entered API key, try refreshing.</p>
1055 + <button class="button button-primary" id="mxchat_back_to_models">Back to Models</button>
1056 + </div>
1057 + `);
1058 +
1059 + $('#mxchat_back_to_models').on('click', function(e) {
1060 + e.preventDefault();
1061 + // CHANGE THIS: Instead of reloading, restore the original modal content
1062 + $modalBody.html(`
1063 + <div class="mxchat-model-selector-search-container">
1064 + <input type="text" id="mxchat_model_search_input" class="mxchat-model-search-input" placeholder="Search models...">
1065 + </div>
1066 + <div class="mxchat-model-selector-categories">
1067 + <button class="mxchat-model-category-btn active" data-category="all">All</button>
1068 + <button class="mxchat-model-category-btn" data-category="openrouter">OpenRouter</button>
1069 + <button class="mxchat-model-category-btn" data-category="gemini">Google Gemini</button>
1070 + <button class="mxchat-model-category-btn" data-category="openai">OpenAI</button>
1071 + <button class="mxchat-model-category-btn" data-category="claude">Claude</button>
1072 + <button class="mxchat-model-category-btn" data-category="xai">X.AI</button>
1073 + <button class="mxchat-model-category-btn" data-category="deepseek">DeepSeek</button>
1074 + </div>
1075 + <div class="mxchat-model-selector-grid" id="mxchat_models_grid"></div>
1076 + `);
276 1077
277 - // Update tabs
278 - $('.mxchat-nav-tab').removeClass('mxchat-nav-tab-active');
279 - $this.addClass('mxchat-nav-tab-active');
1078 + // Re-populate the grid
1079 + populateModelsGrid('', 'all');
280 1080
281 - // Update content areas - with safety check
282 - $('.mxchat-tab-content').removeClass('active').hide();
283 - var $targetTab = $('#' + tabId);
284 - if ($targetTab.length) {
285 - $targetTab.addClass('active').show();
1081 + // Re-bind event handlers
1082 + rebindModalEventHandlers();
1083 + });
1084 + return;
1085 + }
1086 +
1087 + // Show loading state
1088 + $modalBody.html(`
1089 + <div style="text-align: center; padding: 60px 20px;">
1090 + <div class="spinner is-active" style="float: none; margin: 0 auto 20px;"></div>
1091 + <h3>Loading OpenRouter Models...</h3>
1092 + <p>Fetching available models from OpenRouter</p>
1093 + </div>
1094 + `);
1095 +
1096 + // Fetch models from OpenRouter
1097 + jQuery.ajax({
1098 + url: mxchatAdmin.ajax_url,
1099 + type: 'POST',
1100 + data: {
1101 + action: 'mxchat_fetch_openrouter_models',
1102 + api_key: apiKey,
1103 + nonce: mxchatAdmin.fetch_openrouter_models_nonce
1104 + },
1105 + success: function(response) {
1106 + if (response.success && response.data.models) {
1107 + displayOpenRouterModels(response.data.models);
1108 + } else {
1109 + $modalBody.html(`
1110 + <div style="text-align: center; padding: 40px;">
1111 + <span class="dashicons dashicons-warning" style="font-size: 48px; color: #d63638; margin-bottom: 20px;"></span>
1112 + <h3>Error Loading Models</h3>
1113 + <p>${response.data.message || 'Failed to load models from OpenRouter'}</p>
1114 + <button class="button button-primary" id="mxchat_back_to_models">Back to Models</button>
1115 + </div>
1116 + `);
286 1117
287 - // Store active tab
288 - try {
289 - localStorage.setItem('mxchat_active_tab', tabId);
290 - } catch (e) {
291 - console.warn('LocalStorage not available:', e);
292 - }
293 - } else {
294 - console.warn('Tab content #' + tabId + ' not found');
1118 + $('#mxchat_back_to_models').on('click', function(e) {
1119 + e.preventDefault();
1120 + // CHANGE THIS: Restore original content instead of reloading
1121 + restoreOriginalModalContent();
1122 + });
295 1123 }
1124 + },
1125 + error: function() {
1126 + $modalBody.html(`
1127 + <div style="text-align: center; padding: 40px;">
1128 + <span class="dashicons dashicons-warning" style="font-size: 48px; color: #d63638; margin-bottom: 20px;"></span>
1129 + <h3>Connection Error</h3>
1130 + <p>Failed to connect to OpenRouter. Please check your API key and try again.</p>
1131 + <button class="button button-primary" id="mxchat_back_to_models">Back to Models</button>
1132 + </div>
1133 + `);
1134 +
1135 + $('#mxchat_back_to_models').on('click', function(e) {
1136 + e.preventDefault();
1137 + // CHANGE THIS: Restore original content instead of reloading
1138 + restoreOriginalModalContent();
1139 + });
1140 + }
1141 + });
1142 +}
1143 +function restoreOriginalModalContent() {
1144 + const $modalBody = $('#mxchat_model_selector_modal').find('.mxchat-model-selector-modal-body');
1145 +
1146 + $modalBody.html(`
1147 + <div class="mxchat-model-selector-search-container">
1148 + <input type="text" id="mxchat_model_search_input" class="mxchat-model-search-input" placeholder="Search models...">
1149 + </div>
1150 + <div class="mxchat-model-selector-categories">
1151 + <button class="mxchat-model-category-btn active" data-category="all">All</button>
1152 + <button class="mxchat-model-category-btn" data-category="openrouter">OpenRouter</button>
1153 + <button class="mxchat-model-category-btn" data-category="gemini">Google Gemini</button>
1154 + <button class="mxchat-model-category-btn" data-category="openai">OpenAI</button>
1155 + <button class="mxchat-model-category-btn" data-category="claude">Claude</button>
1156 + <button class="mxchat-model-category-btn" data-category="xai">X.AI</button>
1157 + <button class="mxchat-model-category-btn" data-category="deepseek">DeepSeek</button>
1158 + </div>
1159 + <div class="mxchat-model-selector-grid" id="mxchat_models_grid"></div>
1160 + `);
1161 +
1162 + // Re-populate the grid
1163 + window.populateModelsGrid('', 'all');
1164 +
1165 + // Re-bind event handlers
1166 + rebindModalEventHandlers();
1167 +}
1168 +function rebindModalEventHandlers() {
1169 + const $modal = $('#mxchat_model_selector_modal');
1170 +
1171 + // Re-bind category button clicks
1172 + $('.mxchat-model-category-btn').off('click').on('click', function() {
1173 + $('.mxchat-model-category-btn').removeClass('active');
1174 + $(this).addClass('active');
1175 + const category = $(this).data('category');
1176 + const searchTerm = $('#mxchat_model_search_input').val();
1177 + window.populateModelsGrid(searchTerm, category);
1178 + });
1179 +
1180 + // Re-bind search input
1181 + $('#mxchat_model_search_input').off('input').on('input', function() {
1182 + const searchTerm = $(this).val();
1183 + const activeCategory = $('.mxchat-model-category-btn.active').data('category');
1184 + populateModelsGrid(searchTerm, activeCategory);
1185 + });
1186 +}
1187 +
1188 +function restoreDefaultModalFooter() {
1189 + const $modalFooter = $('#mxchat_model_selector_modal').find('.mxchat-model-selector-modal-footer');
1190 +
1191 + // Restore default footer buttons
1192 + $modalFooter.html(`
1193 + <button id="mxchat_cancel_model_selection" class="button mxchat-model-cancel-btn">Cancel</button>
1194 + `);
1195 +
1196 + // Re-bind cancel button
1197 + $('#mxchat_cancel_model_selection').on('click', function() {
1198 + $('#mxchat_model_selector_modal').hide();
1199 + });
1200 +}
1201 +
1202 +function displayOpenRouterModels(models) {
1203 + const $modal = $('#mxchat_model_selector_modal');
1204 + const $modalBody = $modal.find('.mxchat-model-selector-modal-body');
1205 + const $modalFooter = $modal.find('.mxchat-model-selector-modal-footer');
1206 + const currentSelected = $('#openrouter_selected_model').val();
1207 +
1208 + // Variable to store the currently selected model (in the UI, not yet saved)
1209 + let pendingSelection = {
1210 + modelId: currentSelected || null,
1211 + modelName: $('#openrouter_selected_model_name').val() || null
1212 + };
1213 +
1214 + // Build new modal content with search and models
1215 + const newContent = `
1216 + <div class="mxchat-model-selector-search-container">
1217 + <input type="text" id="mxchat_openrouter_search" class="mxchat-model-search-input" placeholder="Search OpenRouter models...">
1218 + <p style="margin: 10px 0; color: #666; font-size: 13px;">
1219 + <strong>${models.length} models available</strong> ·
1220 + <a href="#" id="mxchat_back_to_provider_select" style="color: #2271b1;">← Back to providers</a>
1221 + </p>
1222 + </div>
1223 + <div class="mxchat-model-selector-grid" id="mxchat_openrouter_models_grid"></div>
1224 + `;
1225 +
1226 + // Update footer with Save button for OpenRouter
1227 + const footerContent = `
1228 + <button id="mxchat_back_to_models_footer" class="button mxchat-model-cancel-btn">Back to Providers</button>
1229 + <button id="mxchat_save_openrouter_model" class="button button-primary" disabled>
1230 + <span class="dashicons dashicons-saved" style="margin-top: 3px;"></span> Save Selected Model
1231 + </button>
1232 + `;
1233 +
1234 + $modalBody.html(newContent);
1235 + $modalFooter.html(footerContent);
1236 +
1237 + // Function to render models
1238 + function renderOpenRouterModels(filterText = '') {
1239 + const $grid = $('#mxchat_openrouter_models_grid');
1240 + $grid.empty();
1241 +
1242 + let filteredModels = models;
1243 + if (filterText) {
1244 + const lowerFilter = filterText.toLowerCase();
1245 + filteredModels = models.filter(m =>
1246 + m.id.toLowerCase().includes(lowerFilter) ||
1247 + m.name.toLowerCase().includes(lowerFilter) ||
1248 + (m.description && m.description.toLowerCase().includes(lowerFilter))
1249 + );
1250 + }
1251 +
1252 + filteredModels.forEach(model => {
1253 + const isSelected = pendingSelection.modelId === model.id;
1254 + const contextLength = model.context_length ? `${(model.context_length / 1000).toFixed(0)}K` : '';
1255 + const promptPrice = model.pricing.prompt ? `$${(model.pricing.prompt * 1000000).toFixed(2)}/1M` : '';
1256 +
1257 + const $card = jQuery(`
1258 + <div class="mxchat-openrouter-card ${isSelected ? 'mxchat-model-selected' : ''}" data-model-id="${model.id}" data-model-name="${model.name}">
1259 + <div class="mxchat-model-selector-icon">
1260 + ${getOpenRouterIcon(model.id)}
1261 + </div>
1262 + <div class="mxchat-model-selector-info">
1263 + <h4 class="mxchat-model-selector-title">${model.name}</h4>
1264 + <div style="font-size: 12px; color: #666; margin-top: 5px;">
1265 + ${contextLength ? '<span style="margin-right: 12px;">📄 ' + contextLength + '</span>' : ''}
1266 + ${promptPrice ? '<span>💰 ' + promptPrice + '</span>' : ''}
1267 + </div>
1268 + </div>
1269 + ${isSelected ? '<div class="mxchat-model-selector-checkmark">✓</div>' : ''}
1270 + </div>
1271 + `);
1272 +
1273 + $grid.append($card);
296 1274 });
297 1275 }
298 1276
299 - // Initialize tabs and handle events
300 - initTabs();
301 - $(document).on('widget-added widget-updated postbox-toggled', initTabs);
1277 + // Helper to get icon
1278 + function getOpenRouterIcon(modelId) {
1279 + if (modelId.includes('gpt') || modelId.includes('openai')) {
1280 + return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320" class="mxchat-model-icon-openai"><path fill="currentColor" d="M297 131a80.6 80.6 0 0 0-93.7-104.2 80.6 80.6 0 0 0-137 29A80.6 80.6 0 0 0 23 189a80.6 80.6 0 0 0 93.7 104.2 80.6 80.6 0 0 0 137-29A80.7 80.7 0 0 0 297.1 131zM176.9 299c-14 .1-27.6-4.8-38.4-13.8l1.9-1 63.7-36.9c3.3-1.8 5.3-5.3 5.2-9v-89.9l27 15.6c.3.1.4.4.5.7v74.4a60 60 0 0 1-60 60zM47.9 244a59.7 59.7 0 0 1-7.1-40.1l1.9 1.1 63.7 36.8c3.2 1.9 7.2 1.9 10.5 0l77.8-45V228c0 .3-.2.6-.4.8L129.9 266a60 60 0 0 1-82-22zM31.2 105c7-12.2 18-21.5 31.2-26.3v75.8c0 3.7 2 7.2 5.2 9l77.8 45-27 15.5a1 1 0 0 1-.9 0L53.1 187a60 60 0 0 1-22-82zm221.2 51.5-77.8-45 27-15.5a1 1 0 0 1 .9 0l64.4 37.1a60 60 0 0 1-9.3 108.2v-75.8c0-3.7-2-7.2-5.2-9zm26.8-40.4-1.9-1.1-63.7-36.8a10.4 10.4 0 0 0-10.5 0L125.4 123V92c0-.3 0-.6.3-.8L190.1 54a60 60 0 0 1 89.1 62.1zm-168.5 55.4-27-15.5a1 1 0 0 1-.4-.7V80.9a60 60 0 0 1 98.3-46.1l-1.9 1L116 72.8a10.3 10.3 0 0 0-5.2 9v89.8zm14.6-31.5 34.7-20 34.6 20v40L160 200l-34.7-20z"></path></svg>';
1281 + } else if (modelId.includes('claude') || modelId.includes('anthropic')) {
1282 + return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 176" fill="none" class="mxchat-model-icon-claude"><path fill="currentColor" d="m147.487 0l70.081 175.78H256L185.919 0zM66.183 106.221l23.98-61.774l23.98 61.774zM70.07 0L0 175.78h39.18l14.33-36.914h73.308l14.328 36.914h39.179L110.255 0z"></path></svg>';
1283 + } else if (modelId.includes('gemini') || modelId.includes('google')) {
1284 + return '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 48 48" class="mxchat-model-icon-gemini"><defs><path id="a" d="M44.5 20H24v8.5h11.8C34.7 33.9 30.1 37 24 37c-7.2 0-13-5.8-13-13s5.8-13 13-13c3.1 0 5.9 1.1 8.1 2.9l6.4-6.4C34.6 4.1 29.6 2 24 2 11.8 2 2 11.8 2 24s9.8 22 22 22c11 0 21-8 21-22 0-1.3-.2-2.7-.5-4z"></path></defs><clipPath id="b"><use xlink:href="#a" overflow="visible"></use></clipPath><path clip-path="url(#b)" fill="#FBBC05" d="M0 37V11l17 13z"></path><clip-path="url(#b)" fill="#EA4335" d="M0 11l17 13 7-6.1L48 14V0H0z"></path><path clip-path="url(#b)" fill="#34A853" d="M0 37l30-23 7.9 1L48 0v48H0z"></path><path clip-path="url(#b)" fill="#4285F4" d="M48 48L17 24l-4-3 35-10z"></path></svg>';
1285 + }
1286 + return '<span class="dashicons dashicons-cloud" style="font-size: 24px; color: #6750A4;"></span>';
1287 + }
302 1288
303 - // Activate initial tab
304 - try {
305 - var savedTab = localStorage.getItem('mxchat_active_tab');
306 - if (savedTab && $('#' + savedTab).length > 0) {
307 - $('.mxchat-nav-tab[href="#' + savedTab + '"]').trigger('click.mxchat');
308 - } else {
309 - $('.mxchat-nav-tab').first().trigger('click.mxchat');
1289 + // Initial render
1290 + renderOpenRouterModels();
1291 +
1292 + // Search handler
1293 + $('#mxchat_openrouter_search').on('input', function() {
1294 + renderOpenRouterModels($(this).val());
1295 + });
1296 +
1297 + $('#mxchat_back_to_provider_select').on('click', function(e) {
1298 + e.preventDefault();
1299 + // Restore footer to default state
1300 + restoreDefaultModalFooter();
1301 + // Instead of location.reload(), restore original content
1302 + restoreOriginalModalContent();
1303 + });
1304 +
1305 + // Back to providers footer button
1306 + $('#mxchat_back_to_models_footer').on('click', function(e) {
1307 + e.preventDefault();
1308 + // Restore footer to default state
1309 + restoreDefaultModalFooter();
1310 + // Restore original content
1311 + restoreOriginalModalContent();
1312 + });
1313 +
1314 + // Model selection - just highlight, don't save yet
1315 + $(document).on('click', '.mxchat-openrouter-card', function(e) {
1316 + e.stopPropagation(); // Prevent triggering the regular model card handler
1317 +
1318 + const modelId = $(this).data('model-id');
1319 + const modelName = $(this).data('model-name');
1320 +
1321 + // Remove selection from all cards
1322 + $('.mxchat-openrouter-card').removeClass('mxchat-model-selected').find('.mxchat-model-selector-checkmark').remove();
1323 +
1324 + // Add selection to clicked card
1325 + $(this).addClass('mxchat-model-selected');
1326 + if ($(this).find('.mxchat-model-selector-checkmark').length === 0) {
1327 + $(this).append('<div class="mxchat-model-selector-checkmark">✓</div>');
310 1328 }
311 - } catch (e) {
312 - $('.mxchat-nav-tab').first().trigger('click.mxchat');
1329 +
1330 + // Update pending selection
1331 + pendingSelection.modelId = modelId;
1332 + pendingSelection.modelName = modelName;
1333 +
1334 + // Enable the save button
1335 + $('#mxchat_save_openrouter_model').prop('disabled', false);
1336 + });
1337 +
1338 + // Save button handler
1339 + $('#mxchat_save_openrouter_model').on('click', function() {
1340 + const $saveButton = $(this);
1341 +
1342 + if (!pendingSelection.modelId) {
1343 + return;
1344 + }
1345 +
1346 + // Disable button and show loading state
1347 + $saveButton.prop('disabled', true).html('<span class="spinner is-active" style="float: none; margin: 0 5px 0 0;"></span> Saving...');
1348 +
1349 + // First, save that we're using OpenRouter
1350 + jQuery.ajax({
1351 + url: mxchatAdmin.ajax_url,
1352 + type: 'POST',
1353 + data: {
1354 + action: 'mxchat_save_setting',
1355 + name: 'model',
1356 + value: 'openrouter',
1357 + _ajax_nonce: mxchatAdmin.setting_nonce
1358 + },
1359 + success: function() {
1360 + // After model is set, save the model ID
1361 + jQuery.ajax({
1362 + url: mxchatAdmin.ajax_url,
1363 + type: 'POST',
1364 + data: {
1365 + action: 'mxchat_save_setting',
1366 + name: 'openrouter_selected_model',
1367 + value: pendingSelection.modelId,
1368 + _ajax_nonce: mxchatAdmin.setting_nonce
1369 + },
1370 + success: function() {
1371 + // Update DOM immediately
1372 + $('#openrouter_selected_model').val(pendingSelection.modelId);
1373 +
1374 + // After model ID is saved, save the display name
1375 + jQuery.ajax({
1376 + url: mxchatAdmin.ajax_url,
1377 + type: 'POST',
1378 + data: {
1379 + action: 'mxchat_save_setting',
1380 + name: 'openrouter_selected_model_name',
1381 + value: pendingSelection.modelName,
1382 + _ajax_nonce: mxchatAdmin.setting_nonce
1383 + },
1384 + success: function() {
1385 + // Update DOM immediately
1386 + $('#openrouter_selected_model_name').val(pendingSelection.modelName);
1387 +
1388 + // Update button text
1389 + $('#mxchat_model_selector_btn').text('OpenRouter: ' + pendingSelection.modelName);
1390 +
1391 + // Update the "Currently using" message
1392 + const $currentSelection = $('#openrouter-current-selection');
1393 + if ($currentSelection.length) {
1394 + $currentSelection.html(
1395 + '<span class="dashicons dashicons-yes" style="font-size: 16px; vertical-align: middle;"></span> ' +
1396 + 'Currently using: <strong>' + pendingSelection.modelName + '</strong>'
1397 + ).show();
1398 + }
1399 +
1400 + // Show success state briefly
1401 + $saveButton.html('<span class="dashicons dashicons-yes" style="color: #46b450; margin-top: 3px;"></span> Saved!');
1402 +
1403 + // Close modal after short delay
1404 + setTimeout(function() {
1405 + // Restore footer to default state
1406 + restoreDefaultModalFooter();
1407 + $modal.hide();
1408 + }, 800);
1409 + },
1410 + error: function() {
1411 + $saveButton.prop('disabled', false).html('<span class="dashicons dashicons-saved" style="margin-top: 3px;"></span> Save Selected Model');
1412 + alert('Failed to save model name. Please try again.');
1413 + }
1414 + });
1415 + },
1416 + error: function() {
1417 + $saveButton.prop('disabled', false).html('<span class="dashicons dashicons-saved" style="margin-top: 3px;"></span> Save Selected Model');
1418 + alert('Failed to save model ID. Please try again.');
1419 + }
1420 + });
1421 + },
1422 + error: function() {
1423 + $saveButton.prop('disabled', false).html('<span class="dashicons dashicons-saved" style="margin-top: 3px;"></span> Save Selected Model');
1424 + alert('Failed to save OpenRouter selection. Please try again.');
1425 + }
1426 + });
1427 + });
1428 +
1429 +}
1430 +
1431 +// Embedding model selector - completely separate from chat model selector
1432 +function setupMxChatEmbeddingModelSelector() {
1433 + const $embeddingModelSelect = $('#embedding_model');
1434 +
1435 + // Skip if the element doesn't exist on the page
1436 + if ($embeddingModelSelect.length === 0) {
1437 + return;
313 1438 }
314 1439
315 - // Attach edit modal event handler
316 - $(document).on('click', '.mxchat-edit-button', function() {
317 - const intentId = $(this).data('intent-id');
318 - const phrases = $(this).data('phrases');
319 - mxchatOpenEditModal(intentId, phrases);
1440 + const $embeddingModelSelectorButton = $('<button>', {
1441 + type: 'button',
1442 + id: 'mxchat_embedding_model_selector_btn',
1443 + class: 'button-primary mxchat-embedding-model-selector-btn', // Changed class name to be more specific
1444 + text: 'Select Embedding Model'
320 1445 });
321 1446
322 - // Toggle visibility handlers
323 - function toggleVisibility(selector) {
324 - $(selector).on('click', function() {
325 - var inputField = $(this).prev('input');
326 - if (inputField.attr('type') === 'password') {
327 - inputField.attr('type', 'text');
328 - $(this).text('Hide');
1447 + // Replace the select dropdown with a button
1448 + $embeddingModelSelect.hide().after($embeddingModelSelectorButton);
1449 +
1450 + // Update button text to show currently selected model
1451 + function updateButtonText() {
1452 + const selectedModel = $embeddingModelSelect.val();
1453 + const selectedModelText = $embeddingModelSelect.find('option:selected').text();
1454 + $embeddingModelSelectorButton.text(selectedModelText);
1455 + }
1456 +
1457 + // Initialize button text
1458 + updateButtonText();
1459 +
1460 + // Create a unique ID for the modal to avoid conflicts
1461 + const embeddingModalId = 'mxchat_embedding_model_selector_modal';
1462 +
1463 + // Create and append modal HTML with unique IDs
1464 + const embeddingModelSelectorModal = `
1465 + <div id="${embeddingModalId}" class="mxchat-embedding-model-selector-modal">
1466 + <div class="mxchat-embedding-model-selector-modal-content">
1467 + <div class="mxchat-embedding-model-selector-modal-header">
1468 + <h3>Select Embedding Model</h3>
1469 + <span class="mxchat-embedding-model-selector-modal-close">&times;</span>
1470 + </div>
1471 + <div class="mxchat-embedding-model-selector-modal-body">
1472 + <div class="mxchat-embedding-model-selector-search-container">
1473 + <input type="text" id="mxchat_embedding_model_search_input" class="mxchat-embedding-model-search-input" placeholder="Search models...">
1474 + </div>
1475 + <div class="mxchat-embedding-model-selector-categories">
1476 + <button class="mxchat-embedding-model-category-btn active" data-category="all">All</button>
1477 + <button class="mxchat-embedding-model-category-btn" data-category="openai">OpenAI</button>
1478 + <button class="mxchat-embedding-model-category-btn" data-category="voyage">Voyage AI</button>
1479 + <button class="mxchat-embedding-model-category-btn" data-category="gemini">Google Gemini</button>
1480 + </div>
1481 + <div class="mxchat-embedding-model-selector-grid" id="mxchat_embedding_models_grid"></div>
1482 + </div>
1483 + <div class="mxchat-embedding-model-selector-modal-footer">
1484 + <button id="mxchat_cancel_embedding_model_selection" class="button mxchat-embedding-model-cancel-btn">Cancel</button>
1485 + </div>
1486 + </div>
1487 + </div>
1488 + `;
1489 +
1490 + // Use jQuery's append to ensure it doesn't clash with existing modals
1491 + $('body').append(embeddingModelSelectorModal);
1492 +
1493 + // Populate models grid
1494 + function populateEmbeddingModelsGrid(filter = '', category = 'all') {
1495 + const $grid = $('#mxchat_embedding_models_grid');
1496 + $grid.empty();
1497 +
1498 + // Define embedding models with descriptions and context lengths
1499 + const models = {
1500 + openai: [
1501 + {
1502 + value: 'text-embedding-3-small',
1503 + label: 'TE3 Small',
1504 + description: 'Fast and cost-effective embeddings (1536 dimensions, 8K context)'
1505 + },
1506 + {
1507 + value: 'text-embedding-ada-002',
1508 + label: 'Ada 2',
1509 + description: 'Balanced performance embeddings (1536 dimensions, 8K context)'
1510 + },
1511 + {
1512 + value: 'text-embedding-3-large',
1513 + label: 'TE3 Large',
1514 + description: 'High-performance embeddings (3072 dimensions, 8K context)'
1515 + }
1516 + ],
1517 + voyage: [
1518 + {
1519 + value: 'voyage-3-large',
1520 + label: 'Voyage-3 Large',
1521 + description: 'Advanced semantic search embeddings (2048 dimensions, 32K context)'
1522 + }
1523 + ],
1524 + gemini: [
1525 + {
1526 + value: 'gemini-embedding-exp-03-07',
1527 + label: 'Gemini Embedding',
1528 + description: 'Experimental SOTA embeddings (1536 dimensions, 8K context)'
1529 + }
1530 + ]
1531 + };
1532 +
1533 + let allModels = [];
1534 + Object.keys(models).forEach(key => {
1535 + if (category === 'all' || category === key) {
1536 + allModels = allModels.concat(models[key]);
1537 + }
1538 + });
1539 +
1540 + // Filter by search term if present
1541 + if (filter) {
1542 + const lowerFilter = filter.toLowerCase();
1543 + allModels = allModels.filter(model =>
1544 + model.label.toLowerCase().includes(lowerFilter) ||
1545 + model.description.toLowerCase().includes(lowerFilter)
1546 + );
1547 + }
1548 +
1549 + // Create model cards
1550 + allModels.forEach(model => {
1551 + const isSelected = $embeddingModelSelect.val() === model.value;
1552 + let providerClass = 'mxchat-embedding-model-provider-openai';
1553 +
1554 + if (model.value.startsWith('voyage-')) {
1555 + providerClass = 'mxchat-embedding-model-provider-voyage';
1556 + } else if (model.value.startsWith('gemini-embedding-')) {
1557 + providerClass = 'mxchat-embedding-model-provider-gemini';
1558 + }
1559 +
1560 + let iconHTML = '';
1561 + if (model.value.startsWith('voyage-')) {
1562 + iconHTML = '<span class="dashicons dashicons-chart-line mxchat-embedding-model-icon-voyage"></span>';
1563 + } else if (model.value.startsWith('gemini-embedding-')) {
1564 + iconHTML = '<span class="dashicons dashicons-google mxchat-embedding-model-icon-gemini"></span>';
329 1565 } else {
330 - inputField.attr('type', 'password');
331 - $(this).text('Show');
1566 + iconHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320" class="mxchat-embedding-model-icon-openai"><path fill="currentColor" d="M297 131a80.6 80.6 0 0 0-93.7-104.2 80.6 80.6 0 0 0-137 29A80.6 80.6 0 0 0 23 189a80.6 80.6 0 0 0 93.7 104.2 80.6 80.6 0 0 0 137-29A80.7 80.7 0 0 0 297.1 131zM176.9 299c-14 .1-27.6-4.8-38.4-13.8l1.9-1 63.7-36.9c3.3-1.8 5.3-5.3 5.2-9v-89.9l27 15.6c.3.1.4.4.5.7v74.4a60 60 0 0 1-60 60zM47.9 244a59.7 59.7 0 0 1-7.1-40.1l1.9 1.1 63.7 36.8c3.2 1.9 7.2 1.9 10.5 0l77.8-45V228c0 .3-.2.6-.4.8L129.9 266a60 60 0 0 1-82-22zM31.2 105c7-12.2 18-21.5 31.2-26.3v75.8c0 3.7 2 7.2 5.2 9l77.8 45-27 15.5a1 1 0 0 1-.9 0L53.1 187a60 60 0 0 1-22-82zm221.2 51.5-77.8-45 27-15.5a1 1 0 0 1 .9 0l64.4 37.1a60 60 0 0 1-9.3 108.2v-75.8c0-3.7-2-7.2-5.2-9zm26.8-40.4-1.9-1.1-63.7-36.8a10.4 10.4 0 0 0-10.5 0L125.4 123V92c0-.3 0-.6.3-.8L190.1 54a60 60 0 0 1 89.1 62.1zm-168.5 55.4-27-15.5a1 1 0 0 1-.4-.7V80.9a60 60 0 0 1 98.3-46.1l-1.9 1L116 72.8a10.3 10.3 0 0 0-5.2 9v89.8zm14.6-31.5 34.7-20 34.6 20v40L160 200l-34.7-20z"></path></svg>';
332 1567 }
1568 +
1569 + const $modelCard = $(`
1570 + <div class="mxchat-embedding-model-selector-card ${isSelected ? 'mxchat-embedding-model-selected' : ''} ${providerClass}" data-value="${model.value}">
1571 + <div class="mxchat-embedding-model-selector-icon">
1572 + ${iconHTML}
1573 + </div>
1574 + <div class="mxchat-embedding-model-selector-info">
1575 + <h4 class="mxchat-embedding-model-selector-title">${model.label}</h4>
1576 + <p class="mxchat-embedding-model-selector-description">${model.description}</p>
1577 + </div>
1578 + ${isSelected ? '<div class="mxchat-embedding-model-selector-checkmark">✓</div>' : ''}
1579 + </div>
1580 + `);
1581 +
1582 + $grid.append($modelCard);
333 1583 });
334 1584 }
335 1585
336 - // Initialize all toggle visibility buttons
337 - [
338 - '#toggleApiKeyVisibility',
339 - '#toggleWooCommerceSecretVisibility',
340 - '#toggleLoopsApiKeyVisibility',
341 - '#toggleXaiApiKeyVisibility',
342 - '#toggleClaudeApiKeyVisibility',
343 - '#toggleBraveApiKeyVisibility',
344 - '#toggleWebhookUrlVisibility',
345 - '#toggleSecretKeyVisibility',
346 - '#toggleBotTokenVisibility',
347 - '#toggleDeepSeekApiKeyVisibility'
348 - ].forEach(toggleVisibility);
1586 + // Event handlers - use namespaced events to avoid conflicts
1587 + $embeddingModelSelectorButton.on('click.embeddingModelSelector', function(e) {
1588 + e.stopPropagation(); // Prevent event bubbling
1589 + $('#' + embeddingModalId).show();
1590 + populateEmbeddingModelsGrid('', 'all');
1591 + });
349 1592
1593 + $('.mxchat-embedding-model-selector-modal-close, #mxchat_cancel_embedding_model_selection').on('click.embeddingModelSelector', function(e) {
1594 + e.stopPropagation(); // Prevent event bubbling
1595 + $('#' + embeddingModalId).hide();
1596 + });
1597 +
1598 + $('.mxchat-embedding-model-selector-categories .mxchat-embedding-model-category-btn').on('click.embeddingModelSelector', function(e) {
1599 + e.stopPropagation(); // Prevent event bubbling
1600 + $('.mxchat-embedding-model-selector-categories .mxchat-embedding-model-category-btn').removeClass('active');
1601 + $(this).addClass('active');
1602 + const category = $(this).data('category');
1603 + const searchTerm = $('#mxchat_embedding_model_search_input').val();
1604 + populateEmbeddingModelsGrid(searchTerm, category);
1605 + });
1606 +
1607 + $('#mxchat_embedding_model_search_input').on('input.embeddingModelSelector', function() {
1608 + const searchTerm = $(this).val();
1609 + const activeCategory = $('.mxchat-embedding-model-selector-categories .mxchat-embedding-model-category-btn.active').data('category');
1610 + populateEmbeddingModelsGrid(searchTerm, activeCategory);
1611 + });
1612 +
1613 + // Use a direct selector to avoid conflicts with other card elements
1614 + $(document).on('click.embeddingModelSelector', '.mxchat-embedding-model-selector-grid .mxchat-embedding-model-selector-card', function(e) {
1615 + e.stopPropagation(); // Prevent event bubbling
1616 + const modelValue = $(this).data('value');
1617 +
1618 + // Important: Only update this specific select element
1619 + $embeddingModelSelect.val(modelValue);
1620 +
1621 + // Manually trigger change only on this element
1622 + const changeEvent = new Event('change', { bubbles: true });
1623 + $embeddingModelSelect[0].dispatchEvent(changeEvent);
1624 +
1625 + // Update button text
1626 + updateButtonText();
1627 +
1628 + // Hide modal
1629 + $('#' + embeddingModalId).hide();
1630 + });
1631 +
1632 + // Close modal when clicking outside - use namespaced events
1633 + $(window).on('click.embeddingModelSelector', function(event) {
1634 + if ($(event.target).is('#' + embeddingModalId)) {
1635 + $('#' + embeddingModalId).hide();
1636 + }
1637 + });
1638 +}
1639 +
1640 +// Call this function after the DOM is fully loaded
1641 +$(document).ready(function() {
1642 + setupMxChatModelSelector();
1643 + setupMxChatEmbeddingModelSelector();
1644 +});
1645 +
350 1646 // Add Intent Form Submission
351 1647 $('#mxchat-add-intent-form').on('submit', function(event) {
352 1648 $('#mxchat-intent-loading').show();
353 1649 $('#mxchat-intent-loading-text').show();
@@ -363,97 +1659,60 @@
363 1659 row.find('.save-button').show();
364 1660 });
365 1661
366 1662 // Save button handler
367 - $('.save-button').on('click', function() {
368 - var button = $(this);
369 - var row = button.closest('tr');
370 - var id = button.data('id');
371 - var newContent = row.find('.content-edit').val();
372 - var newUrl = row.find('.url-edit').val();
373 -
374 - button.prop('disabled', true);
375 - button.text('Saving...');
376 -
377 - $.ajax({
378 - url: mxchatAdmin.ajax_url,
379 - type: 'POST',
380 - data: {
381 - action: 'mxchat_save_inline_prompt',
382 - id: id,
383 - article_content: newContent,
384 - article_url: newUrl,
385 - _ajax_nonce: mxchatAdmin.inline_edit_nonce
386 - },
387 - success: function(response) {
388 - button.prop('disabled', false);
389 - button.text('Save');
390 -
391 - if (response.success) {
392 - row.find('.content-view').html(newContent.replace(/\n/g, "<br>"));
393 - if (newUrl) {
394 - row.find('.url-view').html('<a href="' + newUrl + '" target="_blank">' + newUrl + '</a>');
395 - } else {
396 - row.find('.url-view').html('N/A');
397 - }
398 -
399 - row.find('.content-edit, .url-edit').hide();
400 - row.find('.content-view, .url-view').show();
401 - row.find('.save-button').hide();
402 - row.find('.edit-button').show();
1663 +// Save button handler
1664 +$('.save-button').on('click', function() {
1665 + var button = $(this);
1666 + var row = button.closest('tr');
1667 + var id = button.data('id');
1668 + var nonce = button.data('nonce'); // Get nonce from button data attribute
1669 + var newContent = row.find('.content-edit').val();
1670 + var newUrl = row.find('.url-edit').val();
1671 +
1672 + //console.log('Nonce from button:', nonce); // Debug
1673 +
1674 + button.prop('disabled', true);
1675 + button.text('Saving...');
1676 +
1677 + $.ajax({
1678 + url: mxchatAdmin.ajax_url,
1679 + type: 'POST',
1680 + data: {
1681 + action: 'mxchat_save_inline_prompt',
1682 + id: id,
1683 + article_content: newContent,
1684 + article_url: newUrl,
1685 + _ajax_nonce: nonce // Use nonce from button
1686 + },
1687 + success: function(response) {
1688 + button.prop('disabled', false);
1689 + button.text('Save');
1690 +
1691 + if (response.success) {
1692 + row.find('.content-view').html(newContent.replace(/\n/g, "<br>"));
1693 + if (newUrl) {
1694 + row.find('.url-view').html('<a href="' + newUrl + '" target="_blank">' + newUrl + '</a>');
403 1695 } else {
404 - alert('Error saving content: ' + (response.data?.message || 'Unknown error'));
1696 + row.find('.url-view').html('N/A');
405 1697 }
406 - },
407 - error: function() {
408 - button.prop('disabled', false);
409 - button.text('Save');
410 - alert('An error occurred while saving.');
411 - }
412 - });
413 - });
414 -
415 - // Activation handling
416 - const form = $('#mxchat-activation-form');
417 - const spinner = $('#mxchat-activation-spinner');
418 - const submitButton = $('#activate_license_button');
419 - const licenseStatus = $('#mxchat-license-status');
420 -
421 - if (form.length && licenseStatus.length && submitButton.length) {
422 - function handleActivationResponse(response) {
423 - spinner.hide();
424 - if (response.success) {
425 - licenseStatus.text('Active');
426 - licenseStatus.removeClass('inactive').addClass('active');
427 - form.hide();
1698 +
1699 + row.find('.content-edit, .url-edit').hide();
1700 + row.find('.content-view, .url-view').show();
1701 + row.find('.save-button').hide();
1702 + row.find('.edit-button').show();
428 1703 } else {
429 - licenseStatus.text('Inactive');
430 - alert(response.data || 'Activation failed. Please check your input.');
431 - submitButton.prop('disabled', false);
1704 + alert('Error saving content: ' + (response.data?.message || 'Unknown error'));
432 1705 }
1706 + },
1707 + error: function() {
1708 + button.prop('disabled', false);
1709 + button.text('Save');
1710 + alert('An error occurred while saving.');
433 1711 }
1712 + });
1713 +});
434 1714
435 - form.on('submit', function(event) {
436 - event.preventDefault();
437 - spinner.show();
438 - submitButton.prop('disabled', true);
439 -
440 - var formData = {
441 - action: 'mxchat_activate_license',
442 - mxchat_pro_email: $('#mxchat_pro_email').val(),
443 - mxchat_activation_key: $('#mxchat_activation_key').val(),
444 - security: mxchatAdmin.license_nonce
445 - };
446 -
447 - $.post(mxchatAdmin.ajax_url, formData, function(response) {
448 - handleActivationResponse(response);
449 - }).fail(function() {
450 - alert('Server error. Please try again.');
451 - spinner.hide();
452 - submitButton.prop('disabled', false);
453 - });
454 - });
455 - }
456 1715
457 1716 // Questions handling
458 1717 $('.mxchat-add-question').on('click', function () {
459 1718 const container = $('#mxchat-additional-questions-container');
@@ -561,10 +1820,964 @@
561 1820
562 1821 // Bind events
563 1822 $textarea.on('focus input', adjustTextareaHeight) // Expand on focus and input
564 1823 .on('blur', resetTextareaHeight); // Reset on blur
1824 +});
1825 +
1826 +
1827 +
1828 +document.addEventListener('DOMContentLoaded', function() {
1829 + // Check if we're on the correct page before initializing
1830 + const modal = document.getElementById('mxchat-action-modal');
565 1831
1832 + // Only initialize if the modal exists on this page
1833 + if (modal) {
1834 + //console.log('MXChat Action Modal JS Loaded');
1835 +
1836 + // Initialize the action modal functionality
1837 + initStepBasedActionModal();
1838 + }
566 1839
1840 + // Function to initialize the step-based action modal
1841 + function initStepBasedActionModal() {
1842 + // We already checked for modal existence above, so no need to check again
1843 +
1844 + const actionStep1 = document.getElementById('mxchat-action-step-1');
1845 + const actionStep2 = document.getElementById('mxchat-action-step-2');
1846 + const backToStep1Btn = document.getElementById('mxchat-back-to-step-1');
1847 + const searchInput = document.getElementById('action-type-search');
1848 + const categoryButtons = modal.querySelectorAll('.mxchat-category-button');
1849 + const actionCards = modal.querySelectorAll('.mxchat-action-type-card');
1850 + const actionForm = document.getElementById('mxchat-action-form');
1851 + const callbackInput = document.getElementById('callback_function');
1852 + const actionIdField = document.getElementById('edit_action_id');
1853 + const labelField = document.getElementById('intent_label');
1854 + const phrasesField = document.getElementById('action_phrases');
1855 + const formActionType = document.getElementById('form_action_type');
1856 + const nonceContainer = document.getElementById('action-nonce-container');
1857 + const thresholdSlider = document.getElementById('similarity_threshold');
1858 + const thresholdDisplay = document.querySelector('.mxchat-threshold-value-display');
1859 +
1860 + // Rest of your initialization code remains the same...
1861 +
1862 + // Log the structure of one action card for debugging
1863 + if (actionCards.length > 0) {
1864 + //console.log('First action card data attributes:', actionCards[0].dataset);
1865 + //console.log('First action card HTML:', actionCards[0].outerHTML);
1866 + }
1867 +
1868 + // Add click event listeners to category buttons
1869 + categoryButtons.forEach(button => {
1870 + button.addEventListener('click', function() {
1871 + //console.log('Category button clicked:', this.dataset.category);
1872 +
1873 + // Remove active class from all buttons
1874 + categoryButtons.forEach(btn => btn.classList.remove('active'));
1875 +
1876 + // Add active class to clicked button
1877 + this.classList.add('active');
1878 +
1879 + // Get selected category
1880 + const category = this.dataset.category;
1881 +
1882 + // Filter action cards
1883 + filterActionCards(category, searchInput.value);
1884 + });
1885 + });
1886 +
1887 + // Add search functionality
1888 + if (searchInput) {
1889 + searchInput.addEventListener('input', function() {
1890 + // Get active category
1891 + const activeCategory = modal.querySelector('.mxchat-category-button.active')?.dataset.category || 'all';
1892 + //console.log('Search input changed, active category:', activeCategory);
1893 +
1894 + // Filter action cards
1895 + filterActionCards(activeCategory, this.value);
1896 + });
1897 + }
1898 +
1899 + // Add click event listeners to action cards
1900 + actionCards.forEach(card => {
1901 + card.addEventListener('click', function() {
1902 + // Get the action data
1903 + const isPro = this.dataset.pro === 'true';
1904 + const isInstalled = this.dataset.installed === 'true';
1905 + const addonName = this.dataset.addon || '';
1906 + const actionValue = this.dataset.value;
1907 + const actionLabel = this.dataset.label;
1908 + const actionIcon = this.querySelector('.dashicons').getAttribute('class').replace('dashicons dashicons-', '');
1909 + const actionDescription = this.querySelector('p').textContent;
1910 +
1911 + // Pro check using the proper detection method
1912 + const proIsActivated = typeof mxchatAdmin !== 'undefined' &&
1913 + (mxchatAdmin.is_activated === '1' ||
1914 + mxchatAdmin.is_activated === 'true' ||
1915 + mxchatAdmin.is_activated === true);
1916 +
1917 + // Handle different states
1918 + if (isPro && !proIsActivated) {
1919 + // Pro feature but no Pro license
1920 + showProFeatureNotice();
1921 + return;
1922 + }
1923 +
1924 + if (addonName && !isInstalled) {
1925 + // Add-on required but not installed
1926 + const addonDisplayName = this.querySelector('.mxchat-addon-info')?.textContent?.replace('Requires ', '') || addonName + ' Add-on';
1927 + showAddonRequiredNotice(addonDisplayName);
1928 + return;
1929 + }
1930 +
1931 + // If we get here, the action is available - proceed as normal
1932 + callbackInput.value = actionValue;
1933 +
1934 + // Update the selected action display in step 2
1935 + document.getElementById('selected-action-title').textContent = actionLabel;
1936 + document.getElementById('selected-action-description').textContent = actionDescription;
1937 + document.getElementById('selected-action-icon').innerHTML =
1938 + `<span class="dashicons dashicons-${actionIcon}"></span>`;
1939 +
1940 + // Set a default label based on the action type (user can change it)
1941 + if (!labelField.value) {
1942 + labelField.value = actionLabel;
1943 + }
1944 +
1945 + // Move to step 2
1946 + actionStep1.classList.remove('active');
1947 + actionStep2.classList.add('active');
1948 +
1949 + // Update modal title
1950 + });
1951 + });
1952 +
1953 + // Back button functionality
1954 + if (backToStep1Btn) {
1955 + backToStep1Btn.addEventListener('click', function() {
1956 + //console.log('Back button clicked');
1957 + actionStep2.classList.remove('active');
1958 + actionStep1.classList.add('active');
1959 + });
1960 + }
1961 +
1962 + // Function to filter action cards by category and search term
1963 + function filterActionCards(category, searchTerm) {
1964 + searchTerm = searchTerm.toLowerCase().trim();
1965 + //console.log(`Filtering cards by category: "${category}", search: "${searchTerm}"`);
1966 +
1967 + let visibleCount = 0;
1968 +
1969 + // Show all cards initially with animation
1970 + actionCards.forEach((card, index) => {
1971 + // Reset animation
1972 + card.style.animation = 'none';
1973 + // Trigger reflow
1974 + void card.offsetWidth;
1975 +
1976 + // Determine if card should be visible based on category and search term
1977 + const cardCategory = card.dataset.category || '';
1978 + const matchesCategory = category === 'all' || cardCategory === category;
1979 +
1980 + const cardTitle = card.querySelector('h4')?.textContent?.toLowerCase() || '';
1981 + const cardDesc = card.querySelector('p')?.textContent?.toLowerCase() || '';
1982 + const matchesSearch = searchTerm === '' ||
1983 + cardTitle.includes(searchTerm) ||
1984 + cardDesc.includes(searchTerm);
1985 +
1986 + // Show/hide card with animation
1987 + if (matchesCategory && matchesSearch) {
1988 + card.style.display = 'flex';
1989 + // Staggered animation for cards
1990 + card.style.animation = `fadeIn 0.2s ease forwards ${index * 0.03}s`;
1991 + visibleCount++;
1992 + } else {
1993 + card.style.display = 'none';
1994 + }
1995 + });
1996 +
1997 + //console.log(`Filter results: ${visibleCount} cards visible out of ${actionCards.length}`);
1998 + }
1999 +
2000 + // Function to show notice for Pro features
2001 + function showProFeatureNotice() {
2002 + //console.log('Showing Pro feature notice');
2003 + // Check if we already have a notification container
2004 + let noticeContainer = document.querySelector('.mxchat-pro-notice');
2005 +
2006 + if (!noticeContainer) {
2007 + // Create the notice container
2008 + noticeContainer = document.createElement('div');
2009 + noticeContainer.className = 'mxchat-pro-notice';
2010 +
2011 + // Create content
2012 + noticeContainer.innerHTML = `
2013 + <div class="mxchat-pro-notice-content">
2014 + <h3>MxChat Pro Feature</h3>
2015 + <p>This action is available in the Pro version only.</p>
2016 + <div class="mxchat-pro-notice-buttons">
2017 + <button class="mxchat-button-secondary mxchat-pro-notice-close">Close</button>
2018 + <a href="https://mxchat.ai/" class="mxchat-button-primary">Upgrade to Pro</a>
2019 + </div>
2020 + </div>
2021 + `;
2022 +
2023 + // Append to body
2024 + document.body.appendChild(noticeContainer);
2025 +
2026 + // Add close functionality
2027 + const closeButton = noticeContainer.querySelector('.mxchat-pro-notice-close');
2028 + closeButton.addEventListener('click', function() {
2029 + noticeContainer.classList.remove('active');
2030 + setTimeout(() => {
2031 + noticeContainer.remove();
2032 + }, 300);
2033 + });
2034 +
2035 + // Click outside to close
2036 + noticeContainer.addEventListener('click', function(e) {
2037 + if (e.target === noticeContainer) {
2038 + closeButton.click();
2039 + }
2040 + });
2041 +
2042 + // Show with animation
2043 + setTimeout(() => {
2044 + noticeContainer.classList.add('active');
2045 + }, 10);
2046 + } else {
2047 + // If it already exists, just make it visible again
2048 + noticeContainer.classList.add('active');
2049 + }
2050 + }
2051 +
2052 + // Function to show notice for add-on requirements
2053 + function showAddonRequiredNotice(addonName) {
2054 + //console.log(`Showing add-on notice for: ${addonName}`);
2055 + // Check if we already have a notification container
2056 + let noticeContainer = document.querySelector('.mxchat-addon-notice');
2057 +
2058 + if (!noticeContainer) {
2059 + // Create the notice container
2060 + noticeContainer = document.createElement('div');
2061 + noticeContainer.className = 'mxchat-addon-notice';
2062 +
2063 + // Create content
2064 + noticeContainer.innerHTML = `
2065 + <div class="mxchat-addon-notice-content">
2066 + <span class="mxchat-addon-notice-icon">🧩</span>
2067 + <h3>Add-on Required</h3>
2068 + <p>This action requires the <strong>${addonName}</strong> add-on to be installed.</p>
2069 + <div class="mxchat-addon-notice-buttons">
2070 + <button class="mxchat-button-secondary mxchat-addon-notice-close">Close</button>
2071 + <a href="admin.php?page=mxchat-addons" class="mxchat-button-primary">Get Add-ons</a>
2072 + </div>
2073 + </div>
2074 + `;
2075 +
2076 + // Append to body
2077 + document.body.appendChild(noticeContainer);
2078 +
2079 + // Add close functionality
2080 + const closeButton = noticeContainer.querySelector('.mxchat-addon-notice-close');
2081 + closeButton.addEventListener('click', function() {
2082 + noticeContainer.classList.remove('active');
2083 + setTimeout(() => {
2084 + noticeContainer.remove();
2085 + }, 300);
2086 + });
2087 +
2088 + // Click outside to close
2089 + noticeContainer.addEventListener('click', function(e) {
2090 + if (e.target === noticeContainer) {
2091 + closeButton.click();
2092 + }
2093 + });
2094 +
2095 + // Show with animation
2096 + setTimeout(() => {
2097 + noticeContainer.classList.add('active');
2098 + }, 10);
2099 + } else {
2100 + // If it already exists, update the content
2101 + const addonNameElement = noticeContainer.querySelector('p strong');
2102 + if (addonNameElement) {
2103 + addonNameElement.textContent = addonName;
2104 + }
2105 +
2106 + // Make it visible again
2107 + noticeContainer.classList.add('active');
2108 + }
2109 + }
2110 +
2111 + // Form submission handling
2112 + if (actionForm) {
2113 + actionForm.addEventListener('submit', function() {
2114 + //console.log('Form submitted');
2115 + document.getElementById('mxchat-action-loading').style.display = 'flex';
2116 + this.querySelector('button[type="submit"]').disabled = true;
2117 + });
2118 + }
2119 + }
2120 +
2121 + // Setup add action buttons (only if we're on the correct page)
2122 + if (modal) {
2123 + // Update the modal open function to support the step-based flow
2124 + window.mxchatOpenActionModal = function(isEdit = false, actionId = '', label = '', phrases = '', threshold = 85, callbackFunction = '', enabledBots = null) {
2125 + //console.log('Modal opening, edit mode:', isEdit);
2126 +
2127 + // Get form fields
2128 + const actionIdField = document.getElementById('edit_action_id');
2129 + const labelField = document.getElementById('intent_label');
2130 + const phrasesField = document.getElementById('action_phrases');
2131 + const formActionType = document.getElementById('form_action_type');
2132 + const callbackInput = document.getElementById('callback_function');
2133 + const saveButton = document.getElementById('mxchat-save-action-btn');
2134 + const nonceContainer = document.getElementById('action-nonce-container');
2135 + const thresholdSlider = document.getElementById('similarity_threshold');
2136 + const thresholdDisplay = document.querySelector('.mxchat-threshold-value-display');
2137 + const actionStep1 = document.getElementById('mxchat-action-step-1');
2138 + const actionStep2 = document.getElementById('mxchat-action-step-2');
2139 + const searchInput = document.getElementById('action-type-search');
2140 +
2141 + // Set up modal for edit or create
2142 + if (isEdit) {
2143 + saveButton.textContent = 'Update Action';
2144 + formActionType.value = 'mxchat_edit_intent';
2145 + actionIdField.value = actionId;
2146 + labelField.value = label;
2147 + phrasesField.value = phrases;
2148 + callbackInput.value = callbackFunction;
2149 + thresholdSlider.value = threshold; // Set the current threshold value
2150 + thresholdDisplay.textContent = threshold + '%'; // Update display
2151 +
2152 + // NEW: Handle bot selection checkboxes for editing
2153 + // First uncheck all bot checkboxes
2154 + document.querySelectorAll('input[name="enabled_bots[]"]').forEach(checkbox => {
2155 + checkbox.checked = false;
2156 + });
2157 +
2158 + // Then check the ones that should be enabled
2159 + if (enabledBots) {
2160 + let botsArray;
2161 + if (typeof enabledBots === 'string') {
2162 + try {
2163 + botsArray = JSON.parse(enabledBots);
2164 + } catch (e) {
2165 + console.warn('Failed to parse enabledBots:', enabledBots);
2166 + botsArray = ['default']; // fallback
2167 + }
2168 + } else if (Array.isArray(enabledBots)) {
2169 + botsArray = enabledBots;
2170 + } else {
2171 + botsArray = ['default']; // fallback
2172 + }
2173 +
2174 + botsArray.forEach(botId => {
2175 + const checkbox = document.querySelector(`input[name="enabled_bots[]"][value="${botId}"]`);
2176 + if (checkbox) {
2177 + checkbox.checked = true;
2178 + }
2179 + });
2180 + } else {
2181 + // Fallback to default if no bot data
2182 + const defaultCheckbox = document.querySelector('input[name="enabled_bots[]"][value="default"]');
2183 + if (defaultCheckbox) {
2184 + defaultCheckbox.checked = true;
2185 + }
2186 + }
2187 +
2188 + // Update the nonce field for editing
2189 + nonceContainer.innerHTML = ''; // Clear existing nonce
2190 + if (typeof mxchatAdmin !== 'undefined' && mxchatAdmin.edit_intent_nonce) {
2191 + nonceContainer.innerHTML = `<input type="hidden" name="_wpnonce" value="${mxchatAdmin.edit_intent_nonce}">`;
2192 + }
2193 +
2194 + // For editing, go directly to step 2 and update the selected action display
2195 + actionStep1.classList.remove('active');
2196 + actionStep2.classList.add('active');
2197 +
2198 + // Find the matching action card to get its details
2199 + const actionCards = document.querySelectorAll('.mxchat-action-type-card');
2200 + let foundCard = null;
2201 +
2202 + actionCards.forEach(card => {
2203 + if (card.dataset.value === callbackFunction) {
2204 + foundCard = card;
2205 + }
2206 + });
2207 +
2208 + if (foundCard) {
2209 + //console.log('Found matching action card for:', callbackFunction);
2210 + const actionLabel = foundCard.dataset.label || foundCard.querySelector('h4')?.textContent || '';
2211 + const actionIconElement = foundCard.querySelector('.dashicons');
2212 + const actionIcon = actionIconElement
2213 + ? actionIconElement.getAttribute('class').replace('dashicons dashicons-', '')
2214 + : 'admin-generic';
2215 + const actionDescription = foundCard.querySelector('p')?.textContent || '';
2216 +
2217 + document.getElementById('selected-action-title').textContent = actionLabel;
2218 + document.getElementById('selected-action-description').textContent = actionDescription;
2219 + document.getElementById('selected-action-icon').innerHTML =
2220 + `<span class="dashicons dashicons-${actionIcon}"></span>`;
2221 + } else {
2222 + //console.log('No matching action card found for:', callbackFunction);
2223 + // Fallback if we can't find the card
2224 + document.getElementById('selected-action-title').textContent = label;
2225 + document.getElementById('selected-action-description').textContent = 'Configure this action for your chatbot';
2226 + document.getElementById('selected-action-icon').innerHTML =
2227 + `<span class="dashicons dashicons-admin-generic"></span>`;
2228 + }
2229 + } else {
2230 + //console.log('Setting up create mode');
2231 + saveButton.textContent = 'Save Action';
2232 + formActionType.value = 'mxchat_add_intent';
2233 + actionIdField.value = '';
2234 + labelField.value = '';
2235 + phrasesField.value = '';
2236 + callbackInput.value = '';
2237 + thresholdSlider.value = 85; // Default value for new actions
2238 + thresholdDisplay.textContent = '85%'; // Default display
2239 +
2240 + // For new actions, ensure default is checked and others are unchecked
2241 + document.querySelectorAll('input[name="enabled_bots[]"]').forEach(checkbox => {
2242 + checkbox.checked = (checkbox.value === 'default');
2243 + });
2244 +
2245 + // Update the nonce field for adding
2246 + nonceContainer.innerHTML = ''; // Clear existing nonce
2247 + if (typeof mxchatAdmin !== 'undefined' && mxchatAdmin.add_intent_nonce) {
2248 + nonceContainer.innerHTML = `<input type="hidden" name="_wpnonce" value="${mxchatAdmin.add_intent_nonce}">`;
2249 + }
2250 +
2251 + // For creating new, start at step 1
2252 + actionStep1.classList.add('active');
2253 + actionStep2.classList.remove('active');
2254 + }
2255 +
2256 + // Show modal with animation
2257 + modal.style.display = 'flex';
2258 + requestAnimationFrame(() => {
2259 + modal.classList.add('active');
2260 + });
2261 +
2262 + // Set up close handlers
2263 + const closeModal = () => {
2264 + //console.log('Closing modal');
2265 + modal.classList.remove('active');
2266 + setTimeout(() => {
2267 + modal.style.display = 'none';
2268 + }, 300); // Match the CSS transition time
2269 + };
2270 +
2271 + // Close button handler
2272 + const closeBtn = modal.querySelector('.mxchat-modal-close');
2273 + if (closeBtn) {
2274 + closeBtn.onclick = closeModal;
2275 + }
2276 +
2277 + // Cancel button handler
2278 + const cancelBtns = modal.querySelectorAll('.mxchat-modal-cancel');
2279 + if (cancelBtns) {
2280 + cancelBtns.forEach(btn => {
2281 + btn.onclick = closeModal;
2282 + });
2283 + }
2284 +
2285 + // Click outside modal to close
2286 + modal.onclick = (e) => {
2287 + if (e.target === modal) {
2288 + closeModal();
2289 + }
2290 + };
2291 +
2292 + // Escape key to close modal
2293 + document.addEventListener('keydown', function(e) {
2294 + if (e.key === 'Escape' && modal.classList.contains('active')) {
2295 + closeModal();
2296 + }
2297 + }, { once: true });
2298 +
2299 + // Focus appropriate field based on current step
2300 + if (isEdit || actionStep2.classList.contains('active')) {
2301 + if (labelField) labelField.focus();
2302 + } else {
2303 + if (searchInput) searchInput.focus();
2304 + }
2305 +
2306 + return closeModal; // Return close function for external use
2307 + };
2308 + // Setup add action buttons
2309 + const addActionBtn = document.getElementById('mxchat-add-action-btn');
2310 + if (addActionBtn) {
2311 + //console.log('Add action button found');
2312 + addActionBtn.onclick = () => window.mxchatOpenActionModal();
2313 + }
2314 +
2315 + const createFirstAction = document.getElementById('mxchat-create-first-action');
2316 + if (createFirstAction) {
2317 + //console.log('Create first action button found');
2318 + createFirstAction.onclick = () => window.mxchatOpenActionModal();
2319 + }
2320 +
2321 + // Setup edit buttons
2322 + const editButtons = document.querySelectorAll('.mxchat-action-card .mxchat-edit-button');
2323 + //console.log('Edit buttons found:', editButtons.length);
2324 + editButtons.forEach(button => {
2325 + button.onclick = () => {
2326 + const actionId = button.dataset.actionId;
2327 + const phrases = button.dataset.phrases;
2328 + const label = button.dataset.label;
2329 + const threshold = button.dataset.threshold || 85;
2330 + const callbackFunction = button.dataset.callbackFunction;
2331 + const enabledBots = button.dataset.enabledBots; // ADD THIS LINE
2332 +
2333 + window.mxchatOpenActionModal(true, actionId, label, phrases, threshold, callbackFunction, enabledBots);
2334 + };
2335 + });
2336 + }
567 2337 });
568 2338
2339 +jQuery(document).ready(function($) {
2340 + // Toggle custom post types container
2341 + $('#mxchat-custom-post-types-toggle').on('click', function(e) {
2342 + e.preventDefault();
2343 +
2344 + $('#mxchat-custom-post-types-container').slideToggle(300);
2345 +
2346 + // Rotate the toggle icon
2347 + const $icon = $(this).find('.mxchat-accordion-icon');
2348 + if ($('#mxchat-custom-post-types-container').is(':visible')) {
2349 + $icon.css('transform', 'rotate(180deg)');
2350 + $(this).closest('.mxchat-settings-accordion').addClass('active');
2351 + } else {
2352 + $icon.css('transform', 'rotate(0deg)');
2353 + $(this).closest('.mxchat-settings-accordion').removeClass('active');
2354 + }
2355 + });
2356 +
2357 + // If there are any selections made, auto-expand the container
2358 + function autoExpandIfNeeded() {
2359 + // Check if any checkbox in the container is checked
2360 + const hasCheckedItems = $('#mxchat-custom-post-types-container input[type="checkbox"]:checked').length > 0;
2361 +
2362 + if (hasCheckedItems) {
2363 + $('#mxchat-custom-post-types-container').show();
2364 + $('#mxchat-custom-post-types-toggle .mxchat-accordion-icon').css('transform', 'rotate(180deg)');
2365 + $('.mxchat-settings-accordion').addClass('active');
2366 + }
2367 + }
2368 +
2369 + // Run on page load
2370 + autoExpandIfNeeded();
2371 +});
569 2372
2373 +document.addEventListener('DOMContentLoaded', function() {
2374 + var viewSampleBtn = document.getElementById('mxchatViewSampleBtn');
2375 + var modal = document.getElementById('mxchatSampleModal');
2376 + var modalClose = document.getElementById('mxchatModalClose');
2377 + var closeBtn = document.getElementById('mxchatCloseBtn');
2378 + var copyBtn = document.getElementById('mxchatCopyBtn');
2379 + var instructionsContent = document.querySelector('.mxchat-instructions-content');
2380 + var modalContent = document.querySelector('.mxchat-instructions-modal-content');
570 2381
2382 + if (!viewSampleBtn || !modal) {
2383 + return;
2384 + }
2385 +
2386 + // Open modal
2387 + viewSampleBtn.addEventListener('click', function(e) {
2388 + e.preventDefault();
2389 + e.stopPropagation();
2390 + modal.classList.add('mxchat-instructions-show');
2391 + });
2392 +
2393 + // Close modal function
2394 + function closeModal(e) {
2395 + if (e) {
2396 + e.preventDefault();
2397 + e.stopPropagation();
2398 + }
2399 + modal.classList.remove('mxchat-instructions-show');
2400 + }
2401 +
2402 + // Close modal events
2403 + if (modalClose) {
2404 + modalClose.addEventListener('click', function(e) {
2405 + closeModal(e);
2406 + });
2407 + }
2408 +
2409 + if (closeBtn) {
2410 + closeBtn.addEventListener('click', function(e) {
2411 + closeModal(e);
2412 + });
2413 + }
2414 +
2415 + // Close on backdrop click ONLY (not on hover)
2416 + modal.addEventListener('click', function(e) {
2417 + // Only close if clicking directly on the overlay, not on child elements
2418 + if (e.target === modal) {
2419 + closeModal(e);
2420 + }
2421 + });
2422 +
2423 + // Prevent modal content clicks from closing the modal
2424 + if (modalContent) {
2425 + modalContent.addEventListener('click', function(e) {
2426 + e.stopPropagation();
2427 + });
2428 + }
2429 +
2430 + // Close on escape key
2431 + document.addEventListener('keydown', function(e) {
2432 + if (e.key === 'Escape' && modal.classList.contains('mxchat-instructions-show')) {
2433 + closeModal();
2434 + }
2435 + });
2436 +
2437 + // Copy functionality
2438 + if (copyBtn && instructionsContent) {
2439 + copyBtn.addEventListener('click', function(e) {
2440 + e.preventDefault();
2441 + e.stopPropagation();
2442 +
2443 + var text = instructionsContent.textContent;
2444 +
2445 + if (navigator.clipboard) {
2446 + navigator.clipboard.writeText(text).then(function() {
2447 + showCopySuccess();
2448 + }).catch(function() {
2449 + fallbackCopy(text);
2450 + });
2451 + } else {
2452 + fallbackCopy(text);
2453 + }
2454 + });
2455 + }
2456 +
2457 + function fallbackCopy(text) {
2458 + var textArea = document.createElement('textarea');
2459 + textArea.value = text;
2460 + textArea.style.position = 'fixed';
2461 + textArea.style.left = '-999999px';
2462 + textArea.style.top = '-999999px';
2463 + document.body.appendChild(textArea);
2464 + textArea.select();
2465 + try {
2466 + document.execCommand('copy');
2467 + showCopySuccess();
2468 + } catch (err) {
2469 + console.error('Copy failed');
2470 + }
2471 + document.body.removeChild(textArea);
2472 + }
2473 +
2474 + function showCopySuccess() {
2475 + var originalText = copyBtn.innerHTML;
2476 + copyBtn.innerHTML = '<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"><polyline points="20,6 9,17 4,12"/></svg>Copied!';
2477 +
2478 + setTimeout(function() {
2479 + copyBtn.innerHTML = originalText;
2480 + }, 2000);
2481 + }
2482 +});
2483 +
2484 +jQuery(document).ready(function($) {
2485 + var emailDependentFields = [
2486 + '#email_blocker_header_content',
2487 + '#email_blocker_button_text',
2488 + '#enable_name_field',
2489 + '#name_field_placeholder'
2490 + ];
2491 +
2492 + // Add visual indicators
2493 + emailDependentFields.forEach(function(fieldId) {
2494 + var $row = $(fieldId).closest('tr');
2495 + $row.addClass('email-dependent-field');
2496 +
2497 + // Add an icon to show it's dependent
2498 + var $label = $row.find('th label, th');
2499 + $label.prepend('<span class="email-dependent-icon" style="color: #0073aa; margin-right: 5px;">↳</span>');
2500 + });
2501 +
2502 + // Hide initially with opacity for smoother transition
2503 + emailDependentFields.forEach(function(fieldId) {
2504 + $(fieldId).closest('tr').hide().css('opacity', '0');
2505 + });
2506 +
2507 + function toggleEmailFields() {
2508 + var emailEnabled = $('#enable_email_block').is(':checked');
2509 +
2510 + emailDependentFields.forEach(function(fieldId) {
2511 + var $row = $(fieldId).closest('tr');
2512 + if (emailEnabled) {
2513 + $row.slideDown(400).animate({opacity: 1}, 200);
2514 + } else {
2515 + $row.animate({opacity: 0}, 200).slideUp(400);
2516 + }
2517 + });
2518 + }
2519 +
2520 + toggleEmailFields();
2521 + $('#enable_email_block').on('change', toggleEmailFields);
2522 +});
2523 +
2524 +
2525 +
2526 +//Handle role restriction changes
2527 +jQuery(document).ready(function($) {
2528 + //Handle role restriction changes for both data sources
2529 + $(document).on('change', '.mxchat-role-select', function() {
2530 + const $select = $(this);
2531 + const entryId = $select.data('entry-id');
2532 + const dataSource = $select.data('data-source');
2533 + const roleRestriction = $select.val();
2534 + const nonce = $select.data('nonce');
2535 +
2536 + // Visual feedback
2537 + $select.prop('disabled', true).addClass('updating');
2538 +
2539 + $.ajax({
2540 + url: ajaxurl,
2541 + type: 'POST',
2542 + data: {
2543 + action: 'mxchat_update_role_restriction',
2544 + nonce: nonce,
2545 + entry_id: entryId,
2546 + data_source: dataSource, // NEW: Include data source
2547 + role_restriction: roleRestriction
2548 + },
2549 + success: function(response) {
2550 + if (response.success) {
2551 + // Show success feedback
2552 + $select.removeClass('updating').addClass('updated');
2553 + setTimeout(() => {
2554 + $select.removeClass('updated');
2555 + }, 2000);
2556 + } else {
2557 + alert('Failed to update role restriction: ' + response.data);
2558 + // Revert selection
2559 + $select.val($select.data('original-value'));
2560 + }
2561 + },
2562 + error: function() {
2563 + alert('Error updating role restriction');
2564 + // Revert selection
2565 + $select.val($select.data('original-value'));
2566 + },
2567 + complete: function() {
2568 + $select.prop('disabled', false);
2569 + }
2570 + });
2571 +
2572 + // Store original value for potential revert
2573 + $select.data('original-value', roleRestriction);
2574 + });
2575 +
2576 + // Store initial values
2577 + $('.mxchat-role-select').each(function() {
2578 + $(this).data('original-value', $(this).val());
2579 + });
2580 +});
2581 +
2582 +// Bot Selector Handler
2583 +jQuery(document).ready(function($) {
2584 + var saveTimer;
2585 +
2586 + // Function to update bot_id in forms
2587 + function updateBotIdInForm(formSelector) {
2588 + var botId = $('#mxchat-bot-selector').val();
2589 + var form = $(formSelector);
2590 +
2591 + if (form.length > 0) {
2592 + // Remove existing bot_id hidden input
2593 + form.find('input[name="bot_id"]').remove();
2594 +
2595 + // Add new bot_id hidden input if not default
2596 + if (botId && botId !== 'default') {
2597 + form.append('<input type="hidden" name="bot_id" value="' + botId + '">');
2598 + }
2599 + }
2600 + }
2601 +
2602 + $('#mxchat-bot-selector').on('change', function() {
2603 + var botId = $(this).val();
2604 +
2605 + // Clear any existing timer
2606 + clearTimeout(saveTimer);
2607 +
2608 + // Update all forms with new bot_id when bot selection changes
2609 + updateBotIdInForm('#mxchat-url-form');
2610 + updateBotIdInForm('#mxchat-content-form');
2611 +
2612 + // Save the selection via AJAX
2613 + $.ajax({
2614 + url: ajaxurl,
2615 + type: 'POST',
2616 + data: {
2617 + action: 'mxchat_save_selected_bot',
2618 + bot_id: botId,
2619 + nonce: mxchatAdmin.setting_nonce
2620 + },
2621 + success: function(response) {
2622 + if (response.success) {
2623 + // Show saved indicator
2624 + $('#mxchat-bot-save-status').fadeIn().delay(2000).fadeOut();
2625 +
2626 + // Reload the page after a short delay to refresh content
2627 + saveTimer = setTimeout(function() {
2628 + var currentUrl = new URL(window.location.href);
2629 + currentUrl.searchParams.set('bot_id', botId);
2630 + currentUrl.searchParams.set('page', 'mxchat-prompts');
2631 + window.location.href = currentUrl.toString();
2632 + }, 500);
2633 + }
2634 + },
2635 + error: function() {
2636 + console.error('Failed to save bot selection');
2637 + }
2638 + });
2639 + });
2640 +
2641 + // Initialize forms with current bot_id when the page loads
2642 + setTimeout(function() {
2643 + updateBotIdInForm('#mxchat-url-form');
2644 + updateBotIdInForm('#mxchat-content-form');
2645 + }, 100);
2646 +});
2647 +
2648 +// API Key Status Indicator for Chat Models
2649 +jQuery(document).ready(function($) {
2650 + function updateChatModelAPIStatus(apiKeyStatuses) {
2651 + var selectedModel = $('#model').val();
2652 +
2653 + // Hide all status messages
2654 + $('.mxchat-api-status').hide();
2655 +
2656 + // Return early if no model is selected
2657 + if (!selectedModel) {
2658 + return;
2659 + }
2660 +
2661 + // Map models to providers
2662 + var provider = null;
2663 +
2664 + if (selectedModel.startsWith('gpt-')) {
2665 + provider = 'openai';
2666 + } else if (selectedModel.startsWith('claude-')) {
2667 + provider = 'claude';
2668 + } else if (selectedModel.startsWith('grok-')) {
2669 + provider = 'xai';
2670 + } else if (selectedModel.startsWith('deepseek-')) {
2671 + provider = 'deepseek';
2672 + } else if (selectedModel.startsWith('gemini-')) {
2673 + provider = 'gemini';
2674 + } else if (selectedModel === 'openrouter') {
2675 + provider = 'openrouter';
2676 + }
2677 +
2678 + // If we have fresh API key data, update the messages
2679 + if (apiKeyStatuses && provider && apiKeyStatuses[provider] !== undefined) {
2680 + var $statusElement = $('.mxchat-api-status[data-provider="' + provider + '"]');
2681 + var hasKey = apiKeyStatuses[provider];
2682 +
2683 + if (hasKey) {
2684 + $statusElement.html('<span style="color: #00a32a;">✓ API key for ' + getProviderName(provider) + ' detected</span>');
2685 + } else {
2686 + $statusElement.html('<span style="color: #d63638;">⚠ No API key for ' + getProviderName(provider) + ' detected. Please enter API key in API Keys tab.</span>');
2687 + }
2688 + }
2689 +
2690 + // Show the appropriate status message
2691 + if (provider) {
2692 + $('.mxchat-api-status[data-provider="' + provider + '"]').show();
2693 + }
2694 + }
2695 +
2696 + function updateEmbeddingModelAPIStatus(apiKeyStatuses) {
2697 + var selectedModel = $('#embedding_model').val();
2698 +
2699 + // Hide all status messages
2700 + $('.mxchat-embedding-api-status').hide();
2701 +
2702 + // Return early if no model is selected
2703 + if (!selectedModel) {
2704 + return;
2705 + }
2706 +
2707 + // Map models to providers
2708 + var provider = null;
2709 +
2710 + if (selectedModel.startsWith('text-embedding-')) {
2711 + provider = 'openai';
2712 + } else if (selectedModel.startsWith('voyage-')) {
2713 + provider = 'voyage';
2714 + } else if (selectedModel.startsWith('gemini-embedding-')) {
2715 + provider = 'gemini';
2716 + }
2717 +
2718 + // If we have fresh API key data, update the messages
2719 + if (apiKeyStatuses && provider && apiKeyStatuses[provider] !== undefined) {
2720 + var $statusElement = $('.mxchat-embedding-api-status[data-provider="' + provider + '"]');
2721 + var hasKey = apiKeyStatuses[provider];
2722 +
2723 + if (hasKey) {
2724 + $statusElement.html('<span style="color: #00a32a;">✓ API key for ' + getProviderName(provider) + ' detected</span>');
2725 + } else {
2726 + $statusElement.html('<span style="color: #d63638;">⚠ No API key for ' + getProviderName(provider) + ' detected. Please enter API key in API Keys tab.</span>');
2727 + }
2728 + }
2729 +
2730 + // Show the appropriate status message
2731 + if (provider) {
2732 + $('.mxchat-embedding-api-status[data-provider="' + provider + '"]').show();
2733 + }
2734 + }
2735 +
2736 + function getProviderName(provider) {
2737 + var names = {
2738 + 'openai': 'OpenAI',
2739 + 'claude': 'Anthropic (Claude)',
2740 + 'xai': 'X.AI (Grok)',
2741 + 'deepseek': 'DeepSeek',
2742 + 'gemini': 'Google Gemini',
2743 + 'openrouter': 'OpenRouter',
2744 + 'voyage': 'Voyage AI'
2745 + };
2746 + return names[provider] || provider;
2747 + }
2748 +
2749 + function refreshAPIKeyStatus() {
2750 + $.ajax({
2751 + url: ajaxurl,
2752 + type: 'POST',
2753 + data: {
2754 + action: 'mxchat_check_api_keys',
2755 + nonce: mxchatAdmin.setting_nonce
2756 + },
2757 + success: function(response) {
2758 + if (response.success && response.data) {
2759 + updateChatModelAPIStatus(response.data);
2760 + updateEmbeddingModelAPIStatus(response.data);
2761 + }
2762 + }
2763 + });
2764 + }
2765 +
2766 + // Expose refresh function globally so auto-save can call it
2767 + window.mxchatRefreshAPIKeyStatus = refreshAPIKeyStatus;
2768 +
2769 + // Run on page load
2770 + updateChatModelAPIStatus();
2771 + updateEmbeddingModelAPIStatus();
2772 +
2773 + // Check if we just saved settings (WordPress redirects with ?settings-updated=true)
2774 + var urlParams = new URLSearchParams(window.location.search);
2775 + if (urlParams.get('settings-updated') === 'true') {
2776 + // Page was just reloaded after save, fetch fresh API key status
2777 + refreshAPIKeyStatus();
2778 + }
2779 +
2780 + // Run when model changes
2781 + $('#model').on('change', function() { updateChatModelAPIStatus(); });
2782 + $('#embedding_model').on('change', function() { updateEmbeddingModelAPIStatus(); });
2783 +});