jQuery(document).ready(function($) {
// Modal elements
const $modal = $('#mxchat-kb-content-selector-modal');
const $openButton = $('#mxchat-open-content-selector');
const $closeButtons = $('.mxchat-kb-modal-close');
const $contentList = $('.mxchat-kb-content-list');
const $loading = $('.mxchat-kb-loading');
const $pagination = $('.mxchat-kb-pagination');
const $processButton = $('#mxchat-kb-process-selected');
const $selectAll = $('#mxchat-kb-select-all');
const $selectionCount = $('.mxchat-kb-selection-count');
const $acfPdfExtractCheckbox = $('#mxchat-kb-acf-pdf-extract');
// Restore last-used ACF→PDF extract preference from the server-localized default.
if (typeof mxchatSelector !== 'undefined' && mxchatSelector.acfPdfExtractDefault) {
$acfPdfExtractCheckbox.prop('checked', true);
}
// Filter elements
const $searchInput = $('#mxchat-kb-content-search');1
const $typeFilter = $('#mxchat-kb-content-type-filter');
const $statusFilter = $('#mxchat-kb-content-status-filter');
const $processedFilter = $('#mxchat-kb-processed-filter');
// Current state - using let for variables that change
let currentPage = 1;
let totalPages = 1;
let selectedItems = new Set();
let allItems = [];
// Open modal when WordPress import button is clicked
$openButton.on('click', function() {
$modal.show();
// Reset to first page when opening the modal
currentPage = 1;
loadContent();
});
// Close modal
$closeButtons.on('click', function() {
$modal.hide();
});
// Handle import option box clicks (for non-WordPress options)
$('.mxchat-import-box').on('click', function() {
const $box = $(this);
const option = $box.data('option');
// Skip if this is the WordPress option (it has its own handler)
if (option === 'wordpress') {
return;
}
// Update active state
$('.mxchat-import-box').removeClass('active');
$box.addClass('active');
// Hide all input areas
$('#mxchat-url-input-area, #mxchat-content-input-area, #mxchat-pdf-upload-area').hide();
// Hide sitemap-specific sections (but NOT for sitemap option - let detection logic handle it)
if (option !== 'sitemap') {
$('#mxchat-detected-sitemaps, #mxchat-no-sitemaps, #mxchat-sitemaps-loading').hide();
}
// Handle different import options
switch (option) {
case 'pdf-url':
case 'sitemap':
case 'url':
// Show URL input area with appropriate placeholder
$('#mxchat-url-input-area').show();
$('#sitemap_url').attr('placeholder', $box.data('placeholder'));
$('#import_type').val(option === 'pdf-url' ? 'pdf' : option);
// UPDATED: Add or update bot_id hidden field for URL forms
updateBotIdInForm('#mxchat-url-form');
// Update the description text based on the import type
let descriptionText = '';
if (option === 'pdf-url') {
descriptionText = 'Import a PDF document by entering its URL above. PDFs are processed via cron job. If processing does not start, you can manually process batch 5 pages at a time.';
} else if (option === 'sitemap') {
descriptionText = 'Enter a content-specific sub-sitemap URL, not the sitemap index. Sitemaps are processed via cron job. If processing does not start, you can manually process batch 5 pages at a time.';
// Re-show sitemap sections if they were previously loaded
const $sitemapsList = $('#mxchat-sitemaps-list');
if ($sitemapsList.children().length > 0) {
// Sitemaps were already loaded, just show the container
$('#mxchat-detected-sitemaps').show();
} else if ($('#mxchat-no-sitemaps').data('was-shown')) {
// No sitemaps message was shown before
$('#mxchat-no-sitemaps').show();
}
// Note: If neither condition is true, initSitemapDetection will show loading state
} else if (option === 'url') {
descriptionText = 'Import content from any webpage by entering its URL.';
}
$('#url-description-text').text(descriptionText);
break;
case 'content':
// Show content input area
$('#mxchat-content-input-area').show();
// UPDATED: Add or update bot_id hidden field for content forms
updateBotIdInForm('#mxchat-content-form');
break;
case 'pdf-upload':
// Show PDF file upload area
$('#mxchat-pdf-upload-area').show();
// Add or update bot_id hidden field for PDF upload form
updateBotIdInForm('#mxchat-pdf-upload-form');
break;
}
});
// Helper function to add/update bot_id hidden field in forms
function updateBotIdInForm(formSelector) {
const $form = $(formSelector);
if ($form.length === 0) return;
// Get current bot_id from the bot selector dropdown
const currentBotId = $('#mxchat-bot-selector').val();
// Only add bot_id field if multi-bot is active and bot is not 'default'
if (currentBotId && currentBotId !== 'default') {
// Remove existing bot_id field if it exists
$form.find('input[name="bot_id"]').remove();
// Add new bot_id field
$form.append('');
console.log('Updated bot_id in form ' + formSelector + ' to: ' + currentBotId);
} else {
// Remove bot_id field if bot is default
$form.find('input[name="bot_id"]').remove();
}
}
// Load content via AJAX
function loadContent() {
$loading.show();
$contentList.find('.mxchat-kb-content-item').remove();
const data = {
action: 'mxchat_get_content_list',
nonce: mxchatSelector.nonce,
page: currentPage,
per_page: 100,
search: $searchInput.val(),
post_type: $typeFilter.val(),
post_status: $statusFilter.val(),
processed_filter: $processedFilter.val()
};
//console.log('Loading content for page', currentPage, 'with filters:', data);
$.ajax({
url: mxchatSelector.ajaxurl,
data: data,
method: 'GET',
dataType: 'json',
success: function(response) {
$loading.hide();
if (response.success && response.data.items && response.data.items.length > 0) {
// Store the items directly
let items = response.data.items;
if (items.length > 0) {
renderContentItems(items);
renderPagination(parseInt(response.data.current_page), parseInt(response.data.total_pages));
// Update state
allItems = items;
totalPages = parseInt(response.data.total_pages);
currentPage = parseInt(response.data.current_page);
// Update select all checkbox based on current selection
updateSelectAllState();
} else {
displayNoResults($processedFilter.val());
}
} else {
displayNoResults($processedFilter.val());
}
},
error: function(xhr, status, error) {
$loading.hide();
console.error('AJAX Error:', status, error);
$contentList.html('
Error loading content. Please try again.
');
// Clear pagination on error
$pagination.empty();
}
});
}
// Helper function to display appropriate "no results" message
function displayNoResults(processedStatus) {
let message = 'No content found matching your criteria.';
if (processedStatus === 'processed') {
message = 'No content found in knowledge base.';
} else if (processedStatus === 'unprocessed') {
message = 'All content is already in knowledge base.';
}
$contentList.html('
' + message + '
');
// Clear pagination when no results
$pagination.empty();
}
// Render content items
function renderContentItems(items) {
let html = '';
items.forEach(function(item) {
const isSelected = selectedItems.has(item.id);
const isProcessed = item.already_processed;
const chunkCount = item.chunk_count || 0;
// Updated badge text - include chunk count if > 1
let badgeText = 'Not In Knowledge Base';
if (isProcessed) {
badgeText = chunkCount > 1 ? `In Knowledge Base (${chunkCount} chunks)` : 'In Knowledge Base';
}
const badgeClass = isProcessed ? 'mxchat-kb-processed-badge' : 'mxchat-kb-unprocessed-badge';
html += `
';
// Show results in modal
$modal.find('.mxchat-kb-modal-content').prepend($(resultHTML));
// Clear selection
selectedItems.clear();
updateSelection();
// Enable button
$button.prop('disabled', false)
.text('Process Selected Content')
.removeClass('update-mode mixed-mode');
$('.mxchat-kb-selected-count').text('(0)');
// Only reload if there were successful operations
if (processed > 0 || updated > 0) {
// Refresh the knowledge base table with properly grouped entries
if (typeof window.refreshKnowledgeBaseTable === 'function') {
window.refreshKnowledgeBaseTable();
}
// Reload content list to update "already processed" status
setTimeout(function() {
loadContent();
}, 1000);
}
}
// Start processing the first post
processNext(0);
});
// Initialize - Set WordPress as the active option by default
$('.mxchat-import-box[data-option="wordpress"]').addClass('active');
});
// Navigation functionality for Knowledge Base page
jQuery(document).ready(function($) {
// Hook into the new navigation system using .mxch-nav-link
$(document).on('click', '.mxch-nav-link[data-target], .mxch-mobile-nav-link[data-target]', function() {
var target = $(this).data('target');
// Initialize Pinecone functionality when Pinecone section is activated
if (target === 'pinecone') {
setTimeout(function() {
if (typeof initPineconeFeatures === 'function') {
initPineconeFeatures();
}
}, 100);
}
// Initialize OpenAI Vector Store functionality when Vector Store section is activated
if (target === 'openai-vectorstore') {
setTimeout(function() {
if (typeof initVectorStoreFeatures === 'function') {
initVectorStoreFeatures();
}
}, 100);
}
// Check if Pinecone was changed and we're going to import section
if (target === 'import' && sessionStorage.getItem('mxchat_pinecone_changed') === 'true') {
sessionStorage.removeItem('mxchat_pinecone_changed');
// Show refresh notice
var $knowledgeCard = $('#import .mxch-card').eq(1);
if ($knowledgeCard.length > 0 && $knowledgeCard.find('.notice-warning').length === 0) {
var refreshNotice = $('
' +
'
' +
'' +
'Database settings have changed. ' +
'Click here to refresh to see the updated knowledge base.' +
'
');
$knowledgeCard.prepend(refreshNotice);
}
}
});
// Also check on page load if we're already on one of these sections
setTimeout(function() {
if ($('#pinecone').is(':visible') || $('#pinecone.active').length > 0) {
if (typeof initPineconeFeatures === 'function') {
initPineconeFeatures();
}
}
if ($('#openai-vectorstore').is(':visible') || $('#openai-vectorstore.active').length > 0) {
if (typeof initVectorStoreFeatures === 'function') {
initVectorStoreFeatures();
}
}
}, 200);
});
// Pinecone and Vector Store functionality - global functions
var initPineconeFeatures, initVectorStoreFeatures;
(function($) {
// Helper function to update sidebar badge when integration is toggled
function updateSidebarBadge(section, isActive) {
// Find the nav item for this section (both desktop and mobile)
var $desktopNavItem = $('.mxch-nav-item[data-section="' + section + '"] .mxch-nav-link');
var $mobileNavItem = $('.mxch-mobile-nav-link[data-target="' + section + '"]');
// Remove existing badge if any
$desktopNavItem.find('.mxch-active-badge').remove();
$mobileNavItem.find('.mxch-active-badge').remove();
// Add badge if active
if (isActive) {
var badgeHtml = 'Active';
$desktopNavItem.append(badgeHtml);
$mobileNavItem.append(badgeHtml);
}
}
// Pinecone functionality
initPineconeFeatures = function() {
// Check for either old or new section ID
if ($('#pinecone').length === 0 && $('#mxchat-kb-tab-pinecone').length === 0) {
return;
}
initPineconeToggle();
initPineconeConnectionTest();
checkPineconeCompatibility();
};
function initPineconeToggle() {
// Remove any existing handlers to prevent duplicates
var $toggleInput = $('input[name="mxchat_pinecone_addon_options[mxchat_use_pinecone]"]');
$toggleInput.off('change.pineconeToggle');
// Ensure the success notice exists in the settings div (add if not present)
// Check for both the JS-added class and any existing PHP-rendered success notice
var settingsDiv = $('.mxchat-pinecone-settings');
if (settingsDiv.length > 0 && settingsDiv.find('.mxch-notice-success').length === 0) {
var successNotice = $('
' +
'' +
'Pinecone is enabled. All new knowledge base content will be stored in Pinecone.' +
'
');
settingsDiv.prepend(successNotice);
}
// Add the toggle handler for UI only (auto-save will handle the actual saving)
$toggleInput.on('change.pineconeToggle', function() {
var $checkbox = $(this);
var isChecked = $checkbox.is(':checked');
var settingsDiv = $('.mxchat-pinecone-settings');
var enabledNotice = settingsDiv.find('.mxchat-pinecone-enabled-notice, .mxch-notice-success');
// Update the UI immediately
if (isChecked) {
settingsDiv.slideDown(300);
enabledNotice.slideDown(300);
} else {
enabledNotice.slideUp(300);
settingsDiv.slideUp(300);
}
// Update sidebar badge for Pinecone
updateSidebarBadge('pinecone', isChecked);
});
// Set initial state based on current checkbox value
var currentToggle = $('input[name="mxchat_pinecone_addon_options[mxchat_use_pinecone]"]');
if (currentToggle.length > 0) {
var settingsDiv = $('.mxchat-pinecone-settings');
var enabledNotice = settingsDiv.find('.mxchat-pinecone-enabled-notice, .mxch-notice-success');
if (currentToggle.is(':checked')) {
settingsDiv.show();
enabledNotice.show();
} else {
settingsDiv.hide();
enabledNotice.hide();
}
}
}
function initPineconeConnectionTest() {
$('#test-pinecone-connection').off('click.pinecone');
$('#test-pinecone-connection').on('click.pinecone', function() {
var button = $(this);
var resultDiv = $('#connection-test-result');
var apiKey = $('#mxchat_pinecone_api_key').val();
var host = $('#mxchat_pinecone_host').val();
var index = $('#mxchat_pinecone_index').val();
if (!apiKey || !host || !index) {
resultDiv.html('
Connection test failed. Please check your settings.
').show();
},
complete: function() {
button.prop('disabled', false).text('Test Connection');
}
});
});
}
function checkPineconeCompatibility() {
if ($('.mxchat-pinecone-compatibility-notice').length > 0) {
return;
}
var hasOldAddon = $('body').hasClass('mxchat-pinecone-addon-active') ||
$('.pcm-card').length > 0;
if (hasOldAddon) {
var compatibilityNotice = $(`
Pinecone Integration Notice: We've detected you have the Pinecone add-on installed.
Pinecone functionality is now built into the core plugin. You can safely deactivate the separate
Pinecone add-on after confirming your settings are migrated below.
`);
$('#mxchat-kb-tab-pinecone .mxchat-card').prepend(compatibilityNotice);
migratePineconeSettings();
}
}
function migratePineconeSettings() {
if (typeof ajaxurl !== 'undefined') {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'mxchat_migrate_pinecone_settings',
_ajax_nonce: (typeof mxchatAdmin !== 'undefined') ? mxchatAdmin.setting_nonce : ''
},
success: function(response) {
if (response.success && response.data.migrated) {
location.reload();
}
},
error: function() {
//console.log('Pinecone settings migration not available');
}
});
}
}
// ============================================
// OpenAI Vector Store functionality
// ============================================
initVectorStoreFeatures = function() {
if ($('#openai-vectorstore').length === 0) {
return;
}
initVectorStoreToggle();
};
function initVectorStoreToggle() {
// Remove any existing handlers to prevent duplicates
var $toggleInput = $('input[name="mxchat_openai_vectorstore_options[mxchat_use_openai_vectorstore]"]');
$toggleInput.off('change.vectorstoreToggle');
// Ensure the success notice exists in the settings div (add if not present)
// Check for both the JS-added class and any existing PHP-rendered success notice
var settingsDiv = $('.mxchat-vectorstore-settings');
if (settingsDiv.length > 0 && settingsDiv.find('.mxch-notice-success').length === 0) {
var successNotice = $('
' +
'' +
'OpenAI Vector Store is enabled. Queries will search your Vector Store for relevant content.' +
'
');
settingsDiv.prepend(successNotice);
}
// Add the toggle handler for UI only (form submit will handle the actual saving)
$toggleInput.on('change.vectorstoreToggle', function() {
var $checkbox = $(this);
var isChecked = $checkbox.is(':checked');
var settingsDiv = $('.mxchat-vectorstore-settings');
var enabledNotice = settingsDiv.find('.mxchat-vectorstore-enabled-notice, .mxch-notice-success');
// Update the UI immediately
if (isChecked) {
settingsDiv.slideDown(300);
enabledNotice.slideDown(300);
} else {
enabledNotice.slideUp(300);
settingsDiv.slideUp(300);
}
// Update sidebar badge for OpenAI Vector Store
updateSidebarBadge('openai-vectorstore', isChecked);
});
// Set initial state based on current checkbox value
var currentToggle = $('input[name="mxchat_openai_vectorstore_options[mxchat_use_openai_vectorstore]"]');
if (currentToggle.length > 0) {
var settingsDiv = $('.mxchat-vectorstore-settings');
var enabledNotice = settingsDiv.find('.mxchat-vectorstore-enabled-notice, .mxch-notice-success');
if (currentToggle.is(':checked')) {
settingsDiv.show();
enabledNotice.show();
} else {
settingsDiv.hide();
enabledNotice.hide();
}
}
}
})(jQuery);