PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.1.7
MxChat – AI Chatbot & Content Generation for WordPress v3.1.7
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_transcripts.js +25 -595 3.2.153.1.7 View file →
@@ -178,11 +178,9 @@
178 178 $('.mxch-chat-checkbox').prop('checked', isChecked);
179 179
180 180 if (isChecked) {
181 181 $('.mxch-chat-item').each(function() {
182 - // Use .attr() — jQuery's .data() coerces "null"/"true"/numeric strings to JS types,
183 - // which causes fetch/delete of those sessions to silently fail.
184 - selectedSessions.add($(this).attr('data-session-id'));
182 + selectedSessions.add($(this).data('session-id'));
185 183 $(this).addClass('selected');
186 184 });
187 185 $('#mxch-chat-list').addClass('selection-mode');
188 186 } else {
@@ -216,104 +214,29 @@
216 214 $('#mxch-select-all').prop('checked', totalItems > 0 && checkedItems === totalItems);
217 215 $('#mxch-select-all').prop('indeterminate', checkedItems > 0 && checkedItems < totalItems);
218 216 }
219 217
220 - // Sort button — opens a small menu with 4 sort modes (plan-a5b006 adds rating sorts).
221 - $('#mxch-sort-btn').on('click', function(e) {
222 - e.stopPropagation();
223 - const $btn = $(this);
224 - let $menu = $('#mxch-sort-menu');
225 - if (!$menu.length) {
226 - $menu = $(
227 - '<div id="mxch-sort-menu" class="mxch-sort-menu" role="menu">' +
228 - ' <button type="button" class="mxch-sort-option" data-sort="desc" role="menuitem">Newest first</button>' +
229 - ' <button type="button" class="mxch-sort-option" data-sort="asc" role="menuitem">Oldest first</button>' +
230 - ' <button type="button" class="mxch-sort-option" data-sort="rating_positive" role="menuitem"><span class="mxch-sort-option-icon mxch-rating-thumb-up"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 10v12"/><path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H7"/><path d="M3 10h4"/></svg></span>Positive ratings first</button>' +
231 - ' <button type="button" class="mxch-sort-option" data-sort="rating_negative" role="menuitem"><span class="mxch-sort-option-icon mxch-rating-thumb-down"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 14V2"/><path d="M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H17"/><path d="M21 14h-4"/></svg></span>Negative ratings first</button>' +
232 - '</div>'
233 - );
234 - $('body').append($menu);
235 - $menu.on('click', '.mxch-sort-option', function() {
236 - currentSortOrder = $(this).data('sort');
237 - $menu.find('.mxch-sort-option').removeClass('active');
238 - $(this).addClass('active');
239 - $menu.hide();
240 - loadChatList(1, $('#mxch-search-transcripts').val());
241 - });
242 - $(document).on('click.mxchSortMenu', function(ev) {
243 - if (!$(ev.target).closest('#mxch-sort-menu, #mxch-sort-btn').length) {
244 - $menu.hide();
245 - }
246 - });
247 - }
248 - $menu.find('.mxch-sort-option').removeClass('active');
249 - $menu.find('[data-sort="' + currentSortOrder + '"]').addClass('active');
250 - const offset = $btn.offset();
251 - const btnHeight = $btn.outerHeight();
252 - $menu.css({
253 - position: 'absolute',
254 - top: (offset.top + btnHeight + 4) + 'px',
255 - left: offset.left + 'px'
256 - }).toggle();
218 + // Sort button
219 + $('#mxch-sort-btn').on('click', function() {
220 + currentSortOrder = currentSortOrder === 'desc' ? 'asc' : 'desc';
221 + $(this).find('svg').css('transform', currentSortOrder === 'asc' ? 'rotate(180deg)' : 'rotate(0deg)');
222 + loadChatList(currentPage, $('#mxch-search-transcripts').val());
257 223 });
258 224
259 - // Render a rating badge for a session row. Uses inline SVG so the glyph
260 - // renders the same across OSes (emoji fonts vary). Tooltip surfaces the
261 - // optional feedback text.
262 - function renderRatingBadge(session) {
263 - const value = (session && typeof session.rating_value === 'number') ? session.rating_value : null;
264 - const feedback = (session && session.rating_feedback) ? session.rating_feedback : '';
265 - if (value === 1) {
266 - const title = feedback ? ('Visitor: ' + feedback) : 'Visitor rated this chat positively';
267 - return '<span class="mxch-chat-rating mxch-chat-rating-up" title="' + escapeHtml(title) + '" aria-label="' + escapeHtml(title) + '"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 10v12"/><path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H7"/><path d="M3 10h4"/></svg></span>';
268 - }
269 - if (value === -1) {
270 - const title = feedback ? ('Visitor: ' + feedback) : 'Visitor rated this chat negatively';
271 - return '<span class="mxch-chat-rating mxch-chat-rating-down" title="' + escapeHtml(title) + '" aria-label="' + escapeHtml(title) + '"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 14V2"/><path d="M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H17"/><path d="M21 14h-4"/></svg></span>';
272 - }
273 - return '<span class="mxch-chat-rating mxch-chat-rating-empty" title="No rating yet" aria-label="No rating yet">—</span>';
274 - }
275 -
276 - // Delete selected button — opens the shared confirm modal with the "also delete lead" checkbox.
225 + // Delete selected button
277 226 $('#mxch-delete-selected').on('click', function() {
278 227 const count = selectedSessions.size;
279 228 if (count === 0) return;
280 - openTranscriptConfirm(Array.from(selectedSessions), count);
281 - });
282 229
283 - // Transcript delete confirm (shared by bulk + individual) ---------------------------
284 - let transcriptConfirmSessionIds = [];
230 + if (!confirm('Are you sure you want to delete ' + count + ' conversation(s)? This action cannot be undone.')) {
231 + return;
232 + }
285 233
286 - function openTranscriptConfirm(sessionIds, count) {
287 - transcriptConfirmSessionIds = sessionIds.slice();
288 - const n = count || sessionIds.length;
289 - $('#mxch-transcript-confirm-title').text(n === 1 ? 'Delete conversation?' : 'Delete ' + n + ' conversations?');
290 - $('#mxch-transcript-confirm-body').text(
291 - n === 1
292 - ? 'This removes the conversation and its messages.'
293 - : 'This removes ' + n + ' conversations and their messages.'
294 - );
295 - $('#mxch-transcript-also-delete-lead').prop('checked', false);
296 - $('#mxch-transcript-confirm').fadeIn(120);
297 - }
298 -
299 - function closeTranscriptConfirm() {
300 - $('#mxch-transcript-confirm').fadeOut(120);
301 - transcriptConfirmSessionIds = [];
302 - }
303 -
304 - $(document).on('click', '[data-mxch-transcript-close]', closeTranscriptConfirm);
305 -
306 - $('#mxch-transcript-confirm-go').on('click', function() {
307 - const ids = transcriptConfirmSessionIds.slice();
308 - if (!ids.length) { closeTranscriptConfirm(); return; }
309 - const alsoDeleteLead = $('#mxch-transcript-also-delete-lead').is(':checked');
310 - closeTranscriptConfirm();
311 - deleteMultipleSessions(ids, alsoDeleteLead);
234 + deleteMultipleSessions(Array.from(selectedSessions));
312 235 });
313 236
314 237 // Delete multiple sessions
315 - function deleteMultipleSessions(sessionIds, alsoDeleteLead) {
238 + function deleteMultipleSessions(sessionIds) {
316 239 $.ajax({
317 240 url: ajaxurl,
318 241 type: 'POST',
319 242 data: {
@@ -318,9 +241,8 @@
318 241 type: 'POST',
319 242 data: {
320 243 action: 'mxchat_delete_chat_history',
321 244 delete_session_ids: sessionIds,
322 - also_delete_lead: alsoDeleteLead ? '1' : '0',
323 245 security: $('#mxchat_delete_chat_nonce').val()
324 246 },
325 247 success: function(response) {
326 248 try {
@@ -341,13 +263,8 @@
341 263 }
342 264
343 265 // Reload list
344 266 loadChatList(currentPage, $('#mxch-search-transcripts').val());
345 -
346 - // The Leads tab shares this data (Chat deleted pill, nav badge,
347 - // stats) — invalidate it so switching tabs re-fetches instead of
348 - // showing stale "active lead" rows.
349 - invalidateLeadsData();
350 267 } else if (jsonResponse.error) {
351 268 alert('Error: ' + jsonResponse.error);
352 269 }
353 270 } catch (e) {
@@ -415,9 +332,8 @@
415 332 <div class="mxch-chat-name">${escapeHtml(session.display_name)}</div>
416 333 <div class="mxch-chat-preview">${escapeHtml(session.preview)}</div>
417 334 </div>
418 335 <div class="mxch-chat-meta">
419 - ${renderRatingBadge(session)}
420 336 <span class="mxch-chat-time">${escapeHtml(session.time_display)}</span>
421 337 <span class="mxch-chat-count">${session.message_count}</span>
422 338 </div>
423 339 </div>
@@ -429,9 +345,9 @@
429 345 // Attach checkbox handlers
430 346 $('.mxch-chat-checkbox').on('click', function(e) {
431 347 e.stopPropagation(); // Prevent triggering chat item click
432 348 const $item = $(this).closest('.mxch-chat-item');
433 - const sessionId = $item.attr('data-session-id');
349 + const sessionId = $item.data('session-id');
434 350
435 351 if ($(this).is(':checked')) {
436 352 selectedSessions.add(sessionId);
437 353 $item.addClass('selected');
@@ -447,9 +363,9 @@
447 363 $('.mxch-chat-item').on('click', function(e) {
448 364 // Don't trigger if clicking on checkbox
449 365 if ($(e.target).is('.mxch-chat-checkbox')) return;
450 366
451 - const sessionId = $(this).attr('data-session-id');
367 + const sessionId = $(this).data('session-id');
452 368 selectChat(sessionId);
453 369
454 370 // Update active state
455 371 $('.mxch-chat-item').removeClass('active');
@@ -570,18 +486,8 @@
570 486 } else {
571 487 $('#mxch-detail-email-row').hide();
572 488 }
573 489
574 - // Feedback row — .text() (not .html()) for XSS-safe display of user-submitted text.
575 - // rating_feedback is already sanitize_text_field()'d + mb_substr(200) on save.
576 - var feedback = (data && data.rating_feedback) ? String(data.rating_feedback).trim() : '';
577 - if (feedback) {
578 - $('#mxch-detail-feedback').text(feedback);
579 - $('#mxch-detail-feedback-row').show();
580 - } else {
581 - $('#mxch-detail-feedback-row').hide();
582 - }
583 -
584 490 // Clicked links
585 491 if (data.clicked_urls && data.clicked_urls.length > 0) {
586 492 let linksHtml = '';
587 493 data.clicked_urls.forEach(function(url) {
@@ -607,19 +513,13 @@
607 513 <div class="mxch-message-time">${escapeHtml(msg.timestamp)}</div>
608 514 </div>
609 515 `;
610 516 } else {
611 - // Live-agent replies (role 'agent') get their own label and never
612 - // carry a Sources link; bot/assistant rows render exactly as before.
613 - const isAgent = !!msg.is_agent;
614 - const ragLink = (!isAgent && msg.has_rag) ? `<a href="#" class="mxch-rag-link" data-message-id="${msg.id}">Sources</a>` : '';
615 - const senderLabel = isAgent
616 - ? '<span class="mxch-agent-label">Live Agent</span>'
617 - : '<span class="mxch-bot-label">AI Assistant</span>';
517 + const ragLink = msg.has_rag ? `<a href="#" class="mxch-rag-link" data-message-id="${msg.id}">Sources</a>` : '';
618 518 messagesHtml += `
619 - <div class="mxch-message mxch-message-bot${isAgent ? ' mxch-message-agent' : ''}" data-message-id="${msg.id}">
519 + <div class="mxch-message mxch-message-bot" data-message-id="${msg.id}">
620 520 <div class="mxch-message-header">
621 - ${senderLabel}
521 + <span class="mxch-bot-label">AI Assistant</span>
622 522 ${ragLink}
623 523 </div>
624 524 <div class="mxch-message-row">
625 525 <div class="mxch-message-bubble">
@@ -661,16 +561,21 @@
661 561 $btn.addClass('active');
662 562 }
663 563 });
664 564
665 - // Delete current chat — opens the shared confirm modal.
565 + // Delete current chat
666 566 $('#mxch-delete-current').on('click', function() {
667 567 if (!currentSessionId) return;
668 - openTranscriptConfirm([currentSessionId], 1);
568 +
569 + if (!confirm('Are you sure you want to delete this conversation? This action cannot be undone.')) {
570 + return;
571 + }
572 +
573 + deleteSession(currentSessionId);
669 574 });
670 575
671 576 // Delete session function
672 - function deleteSession(sessionId, alsoDeleteLead) {
577 + function deleteSession(sessionId) {
673 578 $.ajax({
674 579 url: ajaxurl,
675 580 type: 'POST',
676 581 data: {
@@ -675,9 +580,8 @@
675 580 type: 'POST',
676 581 data: {
677 582 action: 'mxchat_delete_chat_history',
678 583 delete_session_ids: [sessionId],
679 - also_delete_lead: alsoDeleteLead ? '1' : '0',
680 584 security: $('#mxchat_delete_chat_nonce').val()
681 585 },
682 586 success: function(response) {
683 587 try {
@@ -1370,480 +1274,6 @@
1370 1274 clearTimeout(resizeTimeout);
1371 1275 resizeTimeout = setTimeout(function() {
1372 1276 initActivityChart();
1373 1277 }, 250);
1374 - });
1375 -
1376 - // ==========================================================================
1377 - // Leads Tab
1378 - // ==========================================================================
1379 -
1380 - const leadsState = {
1381 - loaded: false,
1382 - page: 1,
1383 - perPage: 25,
1384 - totalPages: 1,
1385 - totalCount: 0,
1386 - selected: new Set(),
1387 - filters: {
1388 - search: '',
1389 - dateRange: 'all',
1390 - status: 'all',
1391 - pageUrl: '',
1392 - pageTitle: ''
1393 - },
1394 - pendingDelete: [],
1395 - leadsRows: [] // last-rendered rows for quick lookup
1396 - };
1397 -
1398 - function $leads() { return $('#leads'); }
1399 -
1400 - // Called after a transcript delete from the All Chats side. Marks the Leads tab
1401 - // data stale so the next tab visit re-fetches, and refreshes immediately if the
1402 - // Leads tab happens to already be visible.
1403 - function invalidateLeadsData() {
1404 - leadsState.loaded = false;
1405 - if ($('#leads').hasClass('active')) {
1406 - loadLeads(1);
1407 - }
1408 - }
1409 -
1410 - function escapeHtmlLeads(s) {
1411 - if (s === null || typeof s === 'undefined') return '';
1412 - return String(s)
1413 - .replace(/&/g, '&amp;')
1414 - .replace(/</g, '&lt;')
1415 - .replace(/>/g, '&gt;')
1416 - .replace(/"/g, '&quot;')
1417 - .replace(/'/g, '&#039;');
1418 - }
1419 -
1420 - function leadsFiltersActive() {
1421 - const f = leadsState.filters;
1422 - return f.search !== '' || f.dateRange !== 'all' || f.status !== 'all' || f.pageUrl !== '';
1423 - }
1424 -
1425 - function updateClearFiltersButton() {
1426 - if (leadsFiltersActive()) {
1427 - $('#mxch-leads-clear-filters').show();
1428 - } else {
1429 - $('#mxch-leads-clear-filters').hide();
1430 - }
1431 - }
1432 -
1433 - function setPageFilterChip(url, title) {
1434 - leadsState.filters.pageUrl = url || '';
1435 - leadsState.filters.pageTitle = title || url || '';
1436 - const $chip = $('#mxch-leads-active-page-filter');
1437 - if (url) {
1438 - $chip.find('.mxch-leads-page-chip-label').text('Page: ' + (title || url));
1439 - $chip.show();
1440 - } else {
1441 - $chip.hide();
1442 - }
1443 - updateClearFiltersButton();
1444 - }
1445 -
1446 - function loadLeads(page) {
1447 - if (typeof page === 'number') leadsState.page = page;
1448 -
1449 - const $tbody = $('#mxch-leads-tbody');
1450 - $tbody.html('<tr><td colspan="6" class="mxch-leads-loading"><span class="spinner is-active"></span></td></tr>');
1451 -
1452 - $.ajax({
1453 - url: ajaxurl,
1454 - type: 'POST',
1455 - data: {
1456 - action: 'mxchat_fetch_leads',
1457 - page: leadsState.page,
1458 - per_page: leadsState.perPage,
1459 - search: leadsState.filters.search,
1460 - date_range: leadsState.filters.dateRange,
1461 - status: leadsState.filters.status,
1462 - page_url: leadsState.filters.pageUrl
1463 - },
1464 - success: function(response) {
1465 - leadsState.loaded = true;
1466 - if (!response || !response.success) {
1467 - $tbody.html('<tr><td colspan="7" class="mxch-leads-empty">Error loading leads</td></tr>');
1468 - return;
1469 - }
1470 - leadsState.totalPages = response.total_pages || 1;
1471 - leadsState.totalCount = response.total_count || 0;
1472 - leadsState.leadsRows = response.leads || [];
1473 -
1474 - renderLeadsStats(response.stats || {});
1475 - renderLeadsTopPages(response.top_pages || []);
1476 - renderLeadsTable(response.leads || []);
1477 - renderLeadsCount(response.showing_start, response.showing_end, response.total_count);
1478 - renderLeadsPagination(response.page, response.total_pages);
1479 -
1480 - // Nav badge
1481 - if (response.stats && typeof response.stats.total_leads === 'number') {
1482 - const $badge = $('#mxch-leads-nav-badge');
1483 - if (response.stats.total_leads > 0) {
1484 - $badge.text(response.stats.total_leads).show();
1485 - } else {
1486 - $badge.hide();
1487 - }
1488 - }
1489 - },
1490 - error: function() {
1491 - $tbody.html('<tr><td colspan="7" class="mxch-leads-empty">Error loading leads</td></tr>');
1492 - }
1493 - });
1494 - }
1495 -
1496 - function renderLeadsStats(stats) {
1497 - $('#mxch-leads-stat-total').text(stats.total_leads || 0);
1498 - $('#mxch-leads-stat-new').text(stats.new_this_week || 0);
1499 - $('#mxch-leads-stat-avg').text(stats.avg_convos || 0);
1500 - const pct = stats.orphan_pct || 0;
1501 - $('#mxch-leads-stat-orphan').text(pct + '%');
1502 - const orphanCount = stats.orphan_count || 0;
1503 - $('#mxch-leads-stat-orphan-sub').text(orphanCount + (orphanCount === 1 ? ' lead captured but never chatted' : ' leads captured but never chatted'));
1504 - }
1505 -
1506 - function renderLeadsTopPages(pages) {
1507 - const $wrap = $('#mxch-leads-toppages-list');
1508 - if (!pages || pages.length === 0) {
1509 - $wrap.html('<div class="mxch-leads-empty-mini">No page data yet.</div>');
1510 - return;
1511 - }
1512 - let html = '';
1513 - pages.forEach(function(p) {
1514 - const isActive = leadsState.filters.pageUrl === p.url ? ' is-active' : '';
1515 - html += `
1516 - <button type="button" class="mxch-leads-toppage-row${isActive}" data-url="${escapeHtmlLeads(p.url)}" data-title="${escapeHtmlLeads(p.title)}">
1517 - <span class="mxch-leads-toppage-title">${escapeHtmlLeads(p.title || p.url)}</span>
1518 - <span class="mxch-leads-toppage-count">${p.lead_count}</span>
1519 - </button>
1520 - `;
1521 - });
1522 - $wrap.html(html);
1523 - }
1524 -
1525 - function renderLeadsTable(rows) {
1526 - const $tbody = $('#mxch-leads-tbody');
1527 - if (!rows || rows.length === 0) {
1528 - $tbody.html(`
1529 - <tr><td colspan="6" class="mxch-leads-empty">
1530 - <div class="mxch-leads-empty-wrap">
1531 - <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
1532 - <p>No leads match the current filters.</p>
1533 - </div>
1534 - </td></tr>
1535 - `);
1536 - return;
1537 - }
1538 -
1539 - let html = '';
1540 - rows.forEach(function(r) {
1541 - const emailKey = (r.email || '').toLowerCase();
1542 - const isChecked = leadsState.selected.has(emailKey) ? ' checked' : '';
1543 - // Status: 'active' (has conversations), 'chat_deleted' (admin removed the chat), 'orphan' (no chat ever).
1544 - const status = r.status || (r.is_orphan ? 'orphan' : 'active');
1545 - const isOrphan = (status === 'orphan');
1546 - const isChatDeleted = (status === 'chat_deleted');
1547 - const nameLine = r.name
1548 - ? `<span class="mxch-leads-lead-name">${escapeHtmlLeads(r.name)}</span>`
1549 - : '';
1550 - const leadCell = `
1551 - <div class="mxch-leads-lead-cell">
1552 - <span class="mxch-leads-lead-email" title="${escapeHtmlLeads(r.email)}">${escapeHtmlLeads(r.email)}</span>
1553 - ${nameLine}
1554 - </div>`;
1555 - let countCell;
1556 - if (isOrphan) {
1557 - countCell = `<span class="mxch-leads-pill mxch-leads-pill-orphan">Orphan</span>`;
1558 - } else if (isChatDeleted) {
1559 - countCell = `<span class="mxch-leads-pill mxch-leads-pill-deleted" title="Chat was deleted by an admin">Chat deleted</span>`;
1560 - } else {
1561 - countCell = `<span class="mxch-leads-pill">${r.conversation_count}</span>`;
1562 - }
1563 - const lastCell = escapeHtmlLeads(r.last_seen_display || (isOrphan ? 'No conversation yet' : ''));
1564 - const pageCell = r.top_page_url
1565 - ? `<a href="${escapeHtmlLeads(r.top_page_url)}" target="_blank" rel="noopener" class="mxch-leads-page-link" title="${escapeHtmlLeads(r.top_page_url)}">${escapeHtmlLeads(r.top_page_title || r.top_page_url)}</a>`
1566 - : '<span class="mxch-leads-muted">—</span>';
1567 - // View Convo only for active leads (orphans and chat_deleted have no viewable session).
1568 - const viewBtn = (status === 'active' && r.latest_session_id)
1569 - ? `<button type="button" class="mxch-btn mxch-btn-ghost mxch-btn-sm mxch-leads-view" data-session-id="${escapeHtmlLeads(r.latest_session_id)}" title="View latest conversation">
1570 - <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
1571 - <span>View convo</span>
1572 - </button>`
1573 - : '';
1574 - const deleteBtn = `<button type="button" class="mxch-btn mxch-btn-ghost mxch-btn-sm mxch-btn-danger-ghost mxch-leads-delete-row" data-email="${escapeHtmlLeads(r.email)}" title="Delete lead">
1575 - <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
1576 - </button>`;
1577 -
1578 - const rowStateClass = isOrphan ? ' is-orphan' : (isChatDeleted ? ' is-chat-deleted' : '');
1579 - html += `
1580 - <tr class="mxch-leads-row${rowStateClass}" data-email="${escapeHtmlLeads(r.email)}">
1581 - <td class="mxch-leads-col-check"><input type="checkbox" class="mxch-leads-rowcheck"${isChecked}></td>
1582 - <td class="mxch-leads-col-lead">${leadCell}</td>
1583 - <td class="mxch-leads-col-count">${countCell}</td>
1584 - <td class="mxch-leads-col-last">${lastCell}</td>
1585 - <td class="mxch-leads-col-page">${pageCell}</td>
1586 - <td class="mxch-leads-col-actions">${viewBtn}${deleteBtn}</td>
1587 - </tr>
1588 - `;
1589 - });
1590 -
1591 - $tbody.html(html);
1592 - updateLeadsSelectionUI();
1593 - }
1594 -
1595 - function renderLeadsCount(start, end, total) {
1596 - if (!total) {
1597 - $('#mxch-leads-count').text('0 leads');
1598 - } else {
1599 - $('#mxch-leads-count').text(start + '-' + end + ' / ' + total + ' leads');
1600 - }
1601 - }
1602 -
1603 - function renderLeadsPagination(currentPage, totalPages) {
1604 - const $c = $('#mxch-leads-pagination');
1605 - if (!totalPages || totalPages <= 1) { $c.html(''); return; }
1606 - let html = '<div class="mxch-pagination-btns">';
1607 - if (currentPage > 1) {
1608 - html += `<button class="mxch-page-btn" data-page="${currentPage - 1}">&laquo;</button>`;
1609 - }
1610 - html += `<span class="mxch-page-info">${currentPage} / ${totalPages}</span>`;
1611 - if (currentPage < totalPages) {
1612 - html += `<button class="mxch-page-btn" data-page="${currentPage + 1}">&raquo;</button>`;
1613 - }
1614 - html += '</div>';
1615 - $c.html(html);
1616 - }
1617 -
1618 - function updateLeadsSelectionUI() {
1619 - const count = leadsState.selected.size;
1620 - const $countEl = $('#mxch-leads-selected-count');
1621 - const $del = $('#mxch-leads-delete-selected');
1622 - if (count > 0) {
1623 - $countEl.text(count + ' selected').addClass('has-selection');
1624 - $del.prop('disabled', false);
1625 - } else {
1626 - $countEl.text('0').removeClass('has-selection');
1627 - $del.prop('disabled', true);
1628 - }
1629 - // Selected-scope export menu items
1630 - $('#mxch-leads-export-menu button[data-scope="selected"]').prop('disabled', count === 0);
1631 -
1632 - // Select-all checkbox state
1633 - const $checks = $('.mxch-leads-rowcheck');
1634 - const checked = $checks.filter(':checked').length;
1635 - const total = $checks.length;
1636 - $('#mxch-leads-select-all').prop('checked', total > 0 && checked === total);
1637 - $('#mxch-leads-select-all').prop('indeterminate', checked > 0 && checked < total);
1638 - }
1639 -
1640 - // Trigger leads load when switching to the tab (works alongside the main nav handler above).
1641 - $('.mxch-nav-link[data-target="leads"], .mxch-mobile-nav-link[data-target="leads"]').on('click', function() {
1642 - if (!leadsState.loaded) {
1643 - loadLeads(1);
1644 - }
1645 - });
1646 -
1647 - // Filter: search (debounced)
1648 - let leadsSearchTimer;
1649 - $('#mxch-leads-search').on('input', function() {
1650 - clearTimeout(leadsSearchTimer);
1651 - const val = $(this).val();
1652 - leadsSearchTimer = setTimeout(function() {
1653 - leadsState.filters.search = (val || '').trim();
1654 - updateClearFiltersButton();
1655 - loadLeads(1);
1656 - }, 300);
1657 - });
1658 -
1659 - // Filter: date range
1660 - $('#mxch-leads-date-range').on('change', function() {
1661 - leadsState.filters.dateRange = $(this).val();
1662 - updateClearFiltersButton();
1663 - loadLeads(1);
1664 - });
1665 -
1666 - // Filter: status
1667 - $('#mxch-leads-status').on('change', function() {
1668 - leadsState.filters.status = $(this).val();
1669 - updateClearFiltersButton();
1670 - loadLeads(1);
1671 - });
1672 -
1673 - // Clear filters
1674 - $('#mxch-leads-clear-filters').on('click', function() {
1675 - leadsState.filters = { search: '', dateRange: 'all', status: 'all', pageUrl: '', pageTitle: '' };
1676 - $('#mxch-leads-search').val('');
1677 - $('#mxch-leads-date-range').val('all');
1678 - $('#mxch-leads-status').val('all');
1679 - setPageFilterChip('', '');
1680 - loadLeads(1);
1681 - });
1682 -
1683 - // Remove page chip
1684 - $leads().on('click', '.mxch-leads-page-chip-remove', function() {
1685 - setPageFilterChip('', '');
1686 - loadLeads(1);
1687 - });
1688 -
1689 - // Top Pages click -> set filter
1690 - $leads().on('click', '.mxch-leads-toppage-row', function() {
1691 - const url = $(this).data('url') || '';
1692 - const title = $(this).data('title') || '';
1693 - setPageFilterChip(url, title);
1694 - loadLeads(1);
1695 - });
1696 -
1697 - // Pagination click
1698 - $leads().on('click', '#mxch-leads-pagination .mxch-page-btn', function() {
1699 - const p = parseInt($(this).data('page'), 10);
1700 - if (p > 0) loadLeads(p);
1701 - });
1702 -
1703 - // Select-all
1704 - $('#mxch-leads-select-all').on('change', function() {
1705 - const on = $(this).is(':checked');
1706 - $('.mxch-leads-rowcheck').prop('checked', on);
1707 - $('.mxch-leads-row').each(function() {
1708 - const email = ($(this).data('email') || '').toString().toLowerCase();
1709 - if (on) {
1710 - leadsState.selected.add(email);
1711 - } else {
1712 - leadsState.selected.delete(email);
1713 - }
1714 - });
1715 - updateLeadsSelectionUI();
1716 - });
1717 -
1718 - // Row checkbox
1719 - $leads().on('change', '.mxch-leads-rowcheck', function() {
1720 - const email = ($(this).closest('.mxch-leads-row').data('email') || '').toString().toLowerCase();
1721 - if ($(this).is(':checked')) {
1722 - leadsState.selected.add(email);
1723 - } else {
1724 - leadsState.selected.delete(email);
1725 - }
1726 - updateLeadsSelectionUI();
1727 - });
1728 -
1729 - // View convo -> jump to All Chats tab and open the session
1730 - $leads().on('click', '.mxch-leads-view', function() {
1731 - const sid = $(this).attr('data-session-id');
1732 - if (!sid) return;
1733 - $('.mxch-nav-link[data-target="all-chats"]').trigger('click');
1734 - // selectChat is defined earlier in this closure
1735 - if (typeof selectChat === 'function') {
1736 - setTimeout(function() { selectChat(sid); }, 30);
1737 - }
1738 - });
1739 -
1740 - // Row delete -> confirm for one
1741 - $leads().on('click', '.mxch-leads-delete-row', function() {
1742 - const email = $(this).data('email');
1743 - if (!email) return;
1744 - openLeadsConfirm([String(email)]);
1745 - });
1746 -
1747 - // Bulk delete -> confirm for N
1748 - $('#mxch-leads-delete-selected').on('click', function() {
1749 - if (leadsState.selected.size === 0) return;
1750 - openLeadsConfirm(Array.from(leadsState.selected));
1751 - });
1752 -
1753 - function openLeadsConfirm(emails) {
1754 - leadsState.pendingDelete = emails;
1755 - const count = emails.length;
1756 - const msg = count === 1
1757 - ? 'Delete lead "' + emails[0] + '" and all of their conversations?'
1758 - : 'Delete ' + count + ' leads and all of their conversations?';
1759 - $('#mxch-leads-confirm-body').text(msg);
1760 - $('#mxch-leads-confirm').fadeIn(120);
1761 - }
1762 -
1763 - function closeLeadsConfirm() {
1764 - $('#mxch-leads-confirm').fadeOut(120);
1765 - leadsState.pendingDelete = [];
1766 - }
1767 -
1768 - $leads().on('click', '[data-mxch-leads-close]', closeLeadsConfirm);
1769 -
1770 - $('#mxch-leads-confirm-go').on('click', function() {
1771 - const emails = leadsState.pendingDelete.slice();
1772 - if (!emails.length) { closeLeadsConfirm(); return; }
1773 -
1774 - const $btn = $(this).prop('disabled', true).text('Deleting...');
1775 -
1776 - $.ajax({
1777 - url: ajaxurl,
1778 - type: 'POST',
1779 - data: {
1780 - action: 'mxchat_delete_leads',
1781 - security: $('#mxchat_leads_delete_nonce').val(),
1782 - emails: emails
1783 - },
1784 - success: function(response) {
1785 - $btn.prop('disabled', false).text('Delete permanently');
1786 - closeLeadsConfirm();
1787 - if (response && response.success) {
1788 - emails.forEach(function(e) { leadsState.selected.delete(e.toLowerCase()); });
1789 - loadLeads(leadsState.page);
1790 - } else {
1791 - alert((response && response.data && response.data.message) || 'Failed to delete leads.');
1792 - }
1793 - },
1794 - error: function() {
1795 - $btn.prop('disabled', false).text('Delete permanently');
1796 - alert('Network error while deleting.');
1797 - }
1798 - });
1799 - });
1800 -
1801 - // Export dropdown
1802 - $('#mxch-leads-export-btn').on('click', function(e) {
1803 - e.stopPropagation();
1804 - $('#mxch-leads-export-menu').toggleClass('is-open');
1805 - });
1806 -
1807 - $(document).on('click', function() {
1808 - $('#mxch-leads-export-menu').removeClass('is-open');
1809 - });
1810 -
1811 - $('#mxch-leads-export-menu').on('click', function(e) { e.stopPropagation(); });
1812 -
1813 - $('#mxch-leads-export-menu button').on('click', function() {
1814 - if ($(this).prop('disabled')) return;
1815 - const scope = $(this).data('scope') || 'all';
1816 - const fields = $(this).data('fields') || 'email_and_name';
1817 - submitLeadsExport(scope, fields);
1818 - $('#mxch-leads-export-menu').removeClass('is-open');
1819 - });
1820 -
1821 - function submitLeadsExport(scope, fields) {
1822 - const $form = $('<form>', { method: 'POST', action: ajaxurl, style: 'display:none;' });
1823 - $form.append($('<input>', { type: 'hidden', name: 'action', value: 'mxchat_export_leads' }));
1824 - $form.append($('<input>', { type: 'hidden', name: 'security', value: $('#mxchat_leads_export_nonce').val() }));
1825 - $form.append($('<input>', { type: 'hidden', name: 'scope', value: scope }));
1826 - $form.append($('<input>', { type: 'hidden', name: 'fields', value: fields }));
1827 - if (scope === 'selected') {
1828 - Array.from(leadsState.selected).forEach(function(e) {
1829 - $form.append($('<input>', { type: 'hidden', name: 'emails[]', value: e }));
1830 - });
1831 - }
1832 - $form.appendTo('body').submit().remove();
1833 - }
1834 -
1835 - // Preload leads metadata on page load (for the nav badge count only) without rendering.
1836 - // We keep this light — the full fetch only runs when the tab is clicked.
1837 - $.ajax({
1838 - url: ajaxurl,
1839 - type: 'POST',
1840 - data: { action: 'mxchat_fetch_leads', page: 1, per_page: 1 },
1841 - success: function(response) {
1842 - if (response && response.success && response.stats) {
1843 - const total = response.stats.total_leads || 0;
1844 - const $badge = $('#mxch-leads-nav-badge');
1845 - if (total > 0) $badge.text(total).show();
1846 - }
1847 - }
1848 1278 });
1849 1279 });