PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.0
MxChat – AI Chatbot & Content Generation for WordPress v3.2.0
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | includes/class-mxchat-admin.php +34 -989 3.2.33.2.0 View file →
@@ -54,14 +54,8 @@
54 54 add_action('admin_post_mxchat_add_intent', array($this, 'mxchat_handle_add_intent'));
55 55 add_action('admin_post_mxchat_delete_intent', array($this, 'mxchat_handle_delete_intent'));
56 56 add_action('admin_post_mxchat_edit_intent', array($this, 'mxchat_handle_edit_intent'));
57 57 add_action('wp_ajax_mxchat_export_transcripts', array($this, 'export_chat_transcripts'));
58 -
59 - // Leads tab (inside Transcripts)
60 - add_action('wp_ajax_mxchat_fetch_leads', array($this, 'mxchat_fetch_leads'));
61 - add_action('wp_ajax_mxchat_delete_leads', array($this, 'mxchat_delete_leads'));
62 - add_action('wp_ajax_mxchat_export_leads', array($this, 'mxchat_export_leads'));
63 -
64 58 add_action('admin_init', array($this, 'mxchat_transcripts_page_init'));
65 59 add_action('wp_ajax_dismiss_live_agent_notice', array($this, 'dismiss_live_agent_notice'));
66 60 add_action('wp_ajax_dismiss_theme_migration_notice', array($this, 'dismiss_theme_migration_notice'));
67 61 add_action('mxchat_cleanup_old_transcripts', array($this, 'cleanup_old_transcripts'));
@@ -96,146 +90,10 @@
96 90
97 91 // Translation handlers
98 92 add_action('wp_ajax_mxchat_translate_messages', array($this, 'mxchat_translate_messages'));
99 93 add_action('wp_ajax_mxchat_get_transcript_translation', array($this, 'mxchat_get_transcript_translation'));
100 -
101 - // 3.2.3: Embedding model switch protection
102 - add_action('wp_ajax_mxchat_check_embedding_switch', array($this, 'mxchat_check_embedding_switch_ajax'));
103 - add_action('wp_ajax_mxchat_dismiss_embedding_mismatch', array($this, 'mxchat_dismiss_embedding_mismatch_ajax'));
104 - add_action('admin_notices', array($this, 'mxchat_embedding_mismatch_notice'));
105 94 }
106 95
107 - /**
108 - * 3.2.3: Preflight check before allowing the embedding model dropdown to
109 - * switch. Pure option comparison — no counts, no DB queries beyond the
110 - * cached options. The dialog is shown whenever the user has previously
111 - * embedded with a different model than the one they're switching to.
112 - */
113 - public function mxchat_check_embedding_switch_ajax() {
114 - check_ajax_referer('mxchat_admin_nonce', 'security');
115 - if (!current_user_can('manage_options')) {
116 - wp_send_json_error(__('Unauthorized', 'mxchat'));
117 - }
118 -
119 - $new_model = isset($_POST['new_model']) ? sanitize_text_field(wp_unslash($_POST['new_model'])) : '';
120 - $active_model = MxChat_Utils::get_active_embedding_model();
121 -
122 - $is_mismatch = !empty($active_model) && !empty($new_model) && $active_model !== $new_model;
123 -
124 - $active_dims = MxChat_Utils::embedding_model_dimensions($active_model);
125 - $new_dims = MxChat_Utils::embedding_model_dimensions($new_model);
126 -
127 - wp_send_json_success(array(
128 - 'is_mismatch' => $is_mismatch,
129 - 'active_model' => $active_model,
130 - 'active_label' => MxChat_Utils::embedding_model_label($active_model),
131 - 'new_model' => $new_model,
132 - 'new_label' => MxChat_Utils::embedding_model_label($new_model),
133 - 'dims_differ' => ($active_dims > 0 && $new_dims > 0 && $active_dims !== $new_dims),
134 - 'active_dims' => $active_dims,
135 - 'new_dims' => $new_dims,
136 - ));
137 - }
138 -
139 - /**
140 - * 3.2.3: Dismiss the persistent mismatch banner. Tied to the active+selected
141 - * pair so the banner reappears on the next switch event.
142 - */
143 - public function mxchat_dismiss_embedding_mismatch_ajax() {
144 - check_ajax_referer('mxchat_admin_nonce', 'security');
145 - if (!current_user_can('manage_options')) {
146 - wp_send_json_error(__('Unauthorized', 'mxchat'));
147 - }
148 -
149 - $options = get_option('mxchat_options', array());
150 - $selected = $options['embedding_model'] ?? '';
151 - $active = MxChat_Utils::get_active_embedding_model();
152 - update_option('mxchat_dismissed_embedding_mismatch', $active . '|' . $selected, false);
153 - wp_send_json_success();
154 - }
155 -
156 - /**
157 - * 3.2.3: Persistent admin banner shown whenever the active embedding model
158 - * (last used to actually embed something) differs from the currently
159 - * selected model. Pure option comparison — no DB queries on every page
160 - * load. The banner auto-clears once both match again, i.e. after a delete
161 - * + re-embed cycle.
162 - */
163 - public function mxchat_embedding_mismatch_notice() {
164 - if (!current_user_can('manage_options')) {
165 - return;
166 - }
167 -
168 - $options = get_option('mxchat_options', array());
169 - $selected = $options['embedding_model'] ?? '';
170 - $active = MxChat_Utils::get_active_embedding_model();
171 -
172 - if (empty($active) || empty($selected) || $active === $selected) {
173 - return;
174 - }
175 -
176 - $dismissed = get_option('mxchat_dismissed_embedding_mismatch', '');
177 - if ($dismissed === $active . '|' . $selected) {
178 - return;
179 - }
180 -
181 - $active_label = MxChat_Utils::embedding_model_label($active);
182 - $selected_label = MxChat_Utils::embedding_model_label($selected);
183 - $active_dims = MxChat_Utils::embedding_model_dimensions($active);
184 - $selected_dims = MxChat_Utils::embedding_model_dimensions($selected);
185 - $dims_differ = ($active_dims > 0 && $selected_dims > 0 && $active_dims !== $selected_dims);
186 -
187 - $kb_url = admin_url('admin.php?page=mxchat-prompts');
188 - $actions_url = admin_url('admin.php?page=mxchat-actions');
189 -
190 - ?>
191 - <div class="notice notice-error is-dismissible mxchat-embedding-mismatch-notice"
192 - data-active="<?php echo esc_attr($active); ?>"
193 - data-selected="<?php echo esc_attr($selected); ?>">
194 - <p><strong><?php esc_html_e('MxChat: Embedding model mismatch detected', 'mxchat'); ?></strong></p>
195 - <p>
196 - <?php
197 - printf(
198 - /* translators: 1: previously-used model name, 2: currently-selected model name */
199 - esc_html__('Your knowledge base and actions were embedded with %1$s, but %2$s is now selected. Similarity matching will return inaccurate or empty results until you delete all existing embeddings and re-embed your content with the new model.', 'mxchat'),
200 - '<code>' . esc_html($active_label) . '</code>',
201 - '<code>' . esc_html($selected_label) . '</code>'
202 - );
203 - ?>
204 - </p>
205 - <?php if ($dims_differ) : ?>
206 - <p>
207 - <strong><?php esc_html_e('Dimension mismatch:', 'mxchat'); ?></strong>
208 - <?php
209 - printf(
210 - /* translators: 1: old dim count, 2: new dim count */
211 - esc_html__('Existing vectors are %1$d-dimensional but the new model produces %2$d-dimensional vectors. If you use Pinecone, your index will reject queries entirely until re-embedded.', 'mxchat'),
212 - (int) $active_dims,
213 - (int) $selected_dims
214 - );
215 - ?>
216 - </p>
217 - <?php endif; ?>
218 - <p>
219 - <?php esc_html_e('To fix this:', 'mxchat'); ?>
220 - <a href="<?php echo esc_url($kb_url); ?>"><?php esc_html_e('Delete all knowledge base entries', 'mxchat'); ?></a> ·
221 - <a href="<?php echo esc_url($actions_url); ?>"><?php esc_html_e('Delete all actions', 'mxchat'); ?></a> ·
222 - <?php esc_html_e('then re-import / re-add them with the new model selected.', 'mxchat'); ?>
223 - </p>
224 - </div>
225 - <script>
226 - (function($){
227 - $(document).on('click', '.mxchat-embedding-mismatch-notice .notice-dismiss', function(){
228 - $.post(ajaxurl, {
229 - action: 'mxchat_dismiss_embedding_mismatch',
230 - security: '<?php echo esc_js(wp_create_nonce('mxchat_admin_nonce')); ?>'
231 - });
232 - });
233 - })(jQuery);
234 - </script>
235 - <?php
236 - }
237 -
238 96 private function is_license_active() {
239 97 $license_status = get_option('mxchat_license_status', 'inactive');
240 98 return ($license_status === 'active');
241 99 }
@@ -1646,763 +1504,9 @@
1646 1504 fclose($output);
1647 1505 wp_die();
1648 1506 }
1649 1507
1650 -// ============================================================================
1651 -// Leads tab (inside Transcripts)
1652 -//
1653 -// Leads are derived from existing data — no dedicated table. Primary source:
1654 -// wp_mxchat_chat_transcripts rows where user_email is populated. Secondary
1655 -// source: wp_options entries `mxchat_email_{session_id}` / `mxchat_name_{sid}`
1656 -// for "orphan" leads who submitted the pre-chat form but never chatted.
1657 -// ============================================================================
1658 -
1659 1508 /**
1660 - * Fetch leads: dedup-by-email rows, stats strip, and top pages in one call.
1661 - */
1662 -public function mxchat_fetch_leads() {
1663 - if (!current_user_can('manage_options')) {
1664 - wp_send_json_error(['message' => 'Insufficient permissions']);
1665 - wp_die();
1666 - }
1667 -
1668 - global $wpdb;
1669 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
1670 -
1671 - $page = isset($_POST['page']) ? max(1, absint($_POST['page'])) : 1;
1672 - $per_page = isset($_POST['per_page']) ? min(100, max(10, absint($_POST['per_page']))) : 25;
1673 - $offset = ($page - 1) * $per_page;
1674 - $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
1675 - $date_range = isset($_POST['date_range']) ? sanitize_key($_POST['date_range']) : 'all';
1676 - $status = isset($_POST['status']) ? sanitize_key($_POST['status']) : 'all';
1677 - $page_filter = isset($_POST['page_url']) ? esc_url_raw(wp_unslash($_POST['page_url'])) : '';
1678 - $sort = isset($_POST['sort']) ? sanitize_key($_POST['sort']) : 'last_seen';
1679 - $sort_dir = (isset($_POST['sort_dir']) && $_POST['sort_dir'] === 'asc') ? 'ASC' : 'DESC';
1680 -
1681 - $date_cutoff = self::mxchat_leads_date_cutoff($date_range);
1682 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
1683 -
1684 - // Base WHERE for transcripts leads.
1685 - $where_clauses = ["user_email IS NOT NULL", "user_email != ''"];
1686 - $where_params = [];
1687 -
1688 - if ($date_cutoff) {
1689 - $where_clauses[] = 'timestamp >= %s';
1690 - $where_params[] = $date_cutoff;
1691 - }
1692 - if ($page_filter && $has_page_url_column) {
1693 - $where_clauses[] = 'originating_page_url = %s';
1694 - $where_params[] = $page_filter;
1695 - }
1696 - if ($search !== '') {
1697 - $like = '%' . $wpdb->esc_like($search) . '%';
1698 - $where_clauses[] = '(user_email LIKE %s OR user_name LIKE %s)';
1699 - $where_params[] = $like;
1700 - $where_params[] = $like;
1701 - }
1702 - $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);
1703 -
1704 - // Aggregate query grouped by email.
1705 - $select_sql = $has_page_url_column
1706 - ? "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
1707 - COUNT(DISTINCT session_id) AS conversation_count"
1708 - : "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
1709 - COUNT(DISTINCT session_id) AS conversation_count";
1710 -
1711 - $order_column = in_array($sort, ['last_seen', 'conversation_count', 'first_seen'], true) ? $sort : 'last_seen';
1712 - $group_order_limit = " GROUP BY user_email ORDER BY {$order_column} {$sort_dir} LIMIT %d OFFSET %d";
1713 -
1714 - $transcripts_sql = $wpdb->prepare(
1715 - "{$select_sql} FROM {$table} {$where_sql}{$group_order_limit}",
1716 - array_merge($where_params, [$per_page, $offset])
1717 - );
1718 - $transcript_rows = $wpdb->get_results($transcripts_sql);
1719 -
1720 - // Count of unique transcript-based leads under the same filters.
1721 - $count_sql = $wpdb->prepare(
1722 - "SELECT COUNT(DISTINCT user_email) FROM {$table} {$where_sql}",
1723 - $where_params
1724 - );
1725 - $transcripts_lead_count = (int) $wpdb->get_var($count_sql);
1726 -
1727 - // Hydrate each row: name, latest_session_id, top page.
1728 - $leads = [];
1729 - foreach ($transcript_rows as $row) {
1730 - $detail = $has_page_url_column
1731 - ? $wpdb->get_row($wpdb->prepare(
1732 - "SELECT session_id, user_name, originating_page_url, originating_page_title
1733 - FROM {$table} WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
1734 - $row->user_email
1735 - ))
1736 - : $wpdb->get_row($wpdb->prepare(
1737 - "SELECT session_id, user_name FROM {$table}
1738 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
1739 - $row->user_email
1740 - ));
1741 -
1742 - $leads[] = [
1743 - 'email' => $row->user_email,
1744 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
1745 - 'conversation_count' => (int) $row->conversation_count,
1746 - 'last_seen' => $row->last_seen,
1747 - 'last_seen_display' => self::mxchat_leads_format_relative($row->last_seen),
1748 - 'first_seen' => $row->first_seen,
1749 - 'latest_session_id' => isset($detail->session_id) ? $detail->session_id : '',
1750 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
1751 - 'top_page_title' => isset($detail->originating_page_title) ? $detail->originating_page_title : '',
1752 - 'is_orphan' => false,
1753 - 'status' => 'active',
1754 - ];
1755 - }
1756 -
1757 - // Non-transcript lead sources. Built once here, then filtered/merged based on the
1758 - // status filter below. Deduplication priority when the same email appears in multiple
1759 - // sources: transcripts > chat_deleted > orphan.
1760 - $transcripts_emails_seen = array_flip(array_map(
1761 - function ($r) { return strtolower($r['email']); },
1762 - $leads
1763 - ));
1764 -
1765 - // Chat-deleted leads: had a conversation that an admin removed. Preserved via
1766 - // mxchat_lead_del_* options, with timestamps so they respect date filters.
1767 - $chat_deleted_leads_all = [];
1768 - if ($status === 'all' || $status === 'chat_deleted') {
1769 - $chat_deleted_leads_all = self::mxchat_collect_chat_deleted_leads($search, $date_cutoff);
1770 - // Dedup: drop any chat_deleted row whose email is already in the transcripts set.
1771 - $chat_deleted_leads_all = array_values(array_filter(
1772 - $chat_deleted_leads_all,
1773 - function ($row) use ($transcripts_emails_seen) {
1774 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
1775 - }
1776 - ));
1777 - foreach ($chat_deleted_leads_all as $row) {
1778 - $transcripts_emails_seen[strtolower($row['email'])] = true;
1779 - }
1780 - }
1781 -
1782 - // Orphans: pre-chat form captures with no conversation. No timestamp, so skipped
1783 - // when a date filter is active.
1784 - $orphan_leads_all = [];
1785 - if (($status === 'all' || $status === 'orphan') && !$date_cutoff && !$page_filter) {
1786 - $orphan_leads_all = self::mxchat_collect_orphan_leads($search);
1787 - $orphan_leads_all = array_values(array_filter(
1788 - $orphan_leads_all,
1789 - function ($row) use ($transcripts_emails_seen) {
1790 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
1791 - }
1792 - ));
1793 - }
1794 -
1795 - // Apply status filter to the transcripts-derived list.
1796 - if ($status === 'orphan' || $status === 'chat_deleted') {
1797 - $leads = [];
1798 - $transcripts_lead_count = 0;
1799 - }
1800 -
1801 - // Stitch the current page from the three buckets in priority order.
1802 - $total_count = $transcripts_lead_count + count($chat_deleted_leads_all) + count($orphan_leads_all);
1803 - $remaining_slots = $per_page - count($leads);
1804 -
1805 - if ($remaining_slots > 0 && !empty($chat_deleted_leads_all)) {
1806 - $start = max(0, ($page - 1) * $per_page - $transcripts_lead_count);
1807 - if ($start < count($chat_deleted_leads_all)) {
1808 - $leads = array_merge($leads, array_slice($chat_deleted_leads_all, $start, $remaining_slots));
1809 - $remaining_slots = $per_page - count($leads);
1810 - }
1811 - }
1812 -
1813 - if ($remaining_slots > 0 && !empty($orphan_leads_all)) {
1814 - $before = $transcripts_lead_count + count($chat_deleted_leads_all);
1815 - $start = max(0, ($page - 1) * $per_page - $before);
1816 - if ($start < count($orphan_leads_all)) {
1817 - $leads = array_merge($leads, array_slice($orphan_leads_all, $start, $remaining_slots));
1818 - }
1819 - }
1820 -
1821 - $total_pages = $per_page > 0 ? (int) ceil($total_count / $per_page) : 1;
1822 -
1823 - // Stats strip: always computed over full dataset, unaffected by filters.
1824 - $stats = self::mxchat_leads_stats($table, $has_page_url_column);
1825 -
1826 - // Top pages: top 5 by distinct emails captured.
1827 - $top_pages = [];
1828 - if ($has_page_url_column) {
1829 - $top_pages_rows = $wpdb->get_results(
1830 - "SELECT originating_page_url AS url,
1831 - MAX(originating_page_title) AS title,
1832 - COUNT(DISTINCT user_email) AS lead_count
1833 - FROM {$table}
1834 - WHERE user_email IS NOT NULL AND user_email != ''
1835 - AND originating_page_url IS NOT NULL AND originating_page_url != ''
1836 - GROUP BY originating_page_url
1837 - ORDER BY lead_count DESC, url ASC
1838 - LIMIT 5"
1839 - );
1840 - foreach ($top_pages_rows as $p) {
1841 - $top_pages[] = [
1842 - 'url' => $p->url,
1843 - 'title' => $p->title ?: $p->url,
1844 - 'lead_count' => (int) $p->lead_count,
1845 - ];
1846 - }
1847 - }
1848 -
1849 - wp_send_json([
1850 - 'success' => true,
1851 - 'leads' => $leads,
1852 - 'page' => $page,
1853 - 'per_page' => $per_page,
1854 - 'total_count' => $total_count,
1855 - 'total_pages' => $total_pages,
1856 - 'showing_start' => $total_count === 0 ? 0 : ($offset + 1),
1857 - 'showing_end' => min($offset + $per_page, $total_count),
1858 - 'stats' => $stats,
1859 - 'top_pages' => $top_pages,
1860 - ]);
1861 - wp_die();
1862 -}
1863 -
1864 -/**
1865 - * Delete one or more leads by email. Removes every transcripts row for that
1866 - * email and cleans up related wp_options (mxchat_email_{sid}, mxchat_name_{sid},
1867 - * mxchat_history_{sid}) and any orphan option entries matching the email.
1868 - */
1869 -public function mxchat_delete_leads() {
1870 - if (!current_user_can('manage_options')) {
1871 - wp_send_json_error(['message' => 'Insufficient permissions']);
1872 - wp_die();
1873 - }
1874 - check_ajax_referer('mxchat_delete_leads', 'security');
1875 -
1876 - $emails_raw = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
1877 - $emails = [];
1878 - foreach ($emails_raw as $e) {
1879 - $clean = sanitize_email((string) $e);
1880 - if ($clean) {
1881 - $emails[] = $clean;
1882 - }
1883 - }
1884 - if (empty($emails)) {
1885 - wp_send_json_error(['message' => 'No emails provided']);
1886 - wp_die();
1887 - }
1888 -
1889 - $summary = self::mxchat_wipe_leads_by_email($emails);
1890 -
1891 - wp_send_json([
1892 - 'success' => true,
1893 - 'deleted_leads' => count($emails),
1894 - 'deleted_sessions' => $summary['deleted_sessions'],
1895 - 'deleted_rows' => $summary['deleted_rows'],
1896 - ]);
1897 - wp_die();
1898 -}
1899 -
1900 -/**
1901 - * Fully wipe one or more leads by email: every transcripts row, every related wp_options
1902 - * entry (history, pre-chat capture, chat_deleted preservation, agent name, translations).
1903 - *
1904 - * Shared between the Leads-tab Delete button and the transcript-delete opt-in checkbox.
1905 - * Input emails must already be sanitized with sanitize_email().
1906 - */
1907 -private static function mxchat_wipe_leads_by_email(array $emails) {
1908 - global $wpdb;
1909 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
1910 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
1911 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
1912 -
1913 - $deleted_sessions = 0;
1914 - $deleted_rows = 0;
1915 - $emails_lc = array_map('strtolower', $emails);
1916 -
1917 - foreach ($emails as $email) {
1918 - $session_ids = $wpdb->get_col($wpdb->prepare(
1919 - "SELECT DISTINCT session_id FROM {$table} WHERE user_email = %s",
1920 - $email
1921 - ));
1922 -
1923 - $rows_removed = $wpdb->delete($table, ['user_email' => $email], ['%s']);
1924 - if ($rows_removed !== false) {
1925 - $deleted_rows += (int) $rows_removed;
1926 - }
1927 -
1928 - foreach ($session_ids as $sid) {
1929 - $deleted_sessions++;
1930 - wp_cache_delete('chat_session_' . $sid, 'mxchat_chat_sessions');
1931 - delete_option('mxchat_history_' . $sid);
1932 - delete_option('mxchat_email_' . $sid);
1933 - delete_option('mxchat_name_' . $sid);
1934 - delete_option('mxchat_agent_name_' . $sid);
1935 - delete_option('mxchat_lead_del_email_' . $sid);
1936 - delete_option('mxchat_lead_del_name_' . $sid);
1937 - delete_option('mxchat_lead_del_ts_' . $sid);
1938 - if ($has_translations) {
1939 - $wpdb->delete($translations_table, ['session_id' => $sid], ['%s']);
1940 - }
1941 - }
1942 - }
1943 -
1944 - // Clean up any lingering option entries (orphan pre-chat captures + chat_deleted
1945 - // preservations) whose stored value matches one of the emails being wiped.
1946 - $lingering = $wpdb->get_results(
1947 - "SELECT option_name, option_value FROM {$wpdb->options}
1948 - WHERE option_name LIKE 'mxchat_email_%' OR option_name LIKE 'mxchat_lead_del_email_%'"
1949 - );
1950 - foreach ($lingering as $opt) {
1951 - if (!in_array(strtolower(trim($opt->option_value)), $emails_lc, true)) {
1952 - continue;
1953 - }
1954 - if (strpos($opt->option_name, 'mxchat_lead_del_email_') === 0) {
1955 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
1956 - delete_option('mxchat_lead_del_email_' . $sid);
1957 - delete_option('mxchat_lead_del_name_' . $sid);
1958 - delete_option('mxchat_lead_del_ts_' . $sid);
1959 - } else {
1960 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
1961 - delete_option('mxchat_email_' . $sid);
1962 - delete_option('mxchat_name_' . $sid);
1963 - }
1964 - }
1965 -
1966 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
1967 -
1968 - return [
1969 - 'deleted_sessions' => $deleted_sessions,
1970 - 'deleted_rows' => $deleted_rows,
1971 - ];
1972 -}
1973 -
1974 -/**
1975 - * Stream a leads CSV. scope=all exports every lead under current filters is not
1976 - * supported to keep semantics simple; caller either exports all leads or a
1977 - * specific set of selected emails.
1978 - */
1979 -public function mxchat_export_leads() {
1980 - if (!current_user_can('manage_options')) {
1981 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
1982 - }
1983 - check_ajax_referer('mxchat_export_leads', 'security');
1984 -
1985 - $scope = isset($_POST['scope']) ? sanitize_key($_POST['scope']) : 'all';
1986 - $fields_mode = isset($_POST['fields']) ? sanitize_key($_POST['fields']) : 'email_and_name';
1987 - $emails_in = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
1988 -
1989 - $emails_in_clean = [];
1990 - foreach ($emails_in as $e) {
1991 - $clean = sanitize_email((string) $e);
1992 - if ($clean) {
1993 - $emails_in_clean[] = $clean;
1994 - }
1995 - }
1996 -
1997 - global $wpdb;
1998 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
1999 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
2000 -
2001 - // Collect leads from transcripts.
2002 - $transcripts_sql = "SELECT user_email AS email,
2003 - MAX(timestamp) AS last_seen,
2004 - COUNT(DISTINCT session_id) AS conversation_count
2005 - FROM {$table}
2006 - WHERE user_email IS NOT NULL AND user_email != ''";
2007 - $params = [];
2008 - if ($scope === 'selected' && !empty($emails_in_clean)) {
2009 - $placeholders = implode(',', array_fill(0, count($emails_in_clean), '%s'));
2010 - $transcripts_sql .= " AND user_email IN ({$placeholders})";
2011 - $params = $emails_in_clean;
2012 - }
2013 - $transcripts_sql .= " GROUP BY user_email ORDER BY last_seen DESC";
2014 -
2015 - $rows = !empty($params)
2016 - ? $wpdb->get_results($wpdb->prepare($transcripts_sql, $params))
2017 - : $wpdb->get_results($transcripts_sql);
2018 -
2019 - // Hydrate each row with name + top page.
2020 - $export_rows = [];
2021 - foreach ($rows as $row) {
2022 - $detail = $has_page_url_column
2023 - ? $wpdb->get_row($wpdb->prepare(
2024 - "SELECT user_name, originating_page_url FROM {$table}
2025 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2026 - $row->email
2027 - ))
2028 - : $wpdb->get_row($wpdb->prepare(
2029 - "SELECT user_name FROM {$table}
2030 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2031 - $row->email
2032 - ));
2033 - $export_rows[] = [
2034 - 'email' => $row->email,
2035 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2036 - 'conversation_count' => (int) $row->conversation_count,
2037 - 'last_seen' => $row->last_seen,
2038 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2039 - ];
2040 - }
2041 -
2042 - // Include orphan + chat_deleted leads when exporting all.
2043 - if ($scope === 'all') {
2044 - $transcripts_emails_lc = array_flip(array_map(
2045 - function ($r) { return strtolower($r['email']); },
2046 - $export_rows
2047 - ));
2048 - foreach (self::mxchat_collect_chat_deleted_leads('') as $cd) {
2049 - if (isset($transcripts_emails_lc[strtolower($cd['email'])])) continue;
2050 - $transcripts_emails_lc[strtolower($cd['email'])] = true;
2051 - $export_rows[] = [
2052 - 'email' => $cd['email'],
2053 - 'name' => $cd['name'],
2054 - 'conversation_count' => 0,
2055 - 'last_seen' => $cd['last_seen'],
2056 - 'top_page_url' => '',
2057 - ];
2058 - }
2059 - foreach (self::mxchat_collect_orphan_leads('') as $orphan) {
2060 - if (isset($transcripts_emails_lc[strtolower($orphan['email'])])) continue;
2061 - $transcripts_emails_lc[strtolower($orphan['email'])] = true;
2062 - $export_rows[] = [
2063 - 'email' => $orphan['email'],
2064 - 'name' => $orphan['name'],
2065 - 'conversation_count' => 0,
2066 - 'last_seen' => '',
2067 - 'top_page_url' => '',
2068 - ];
2069 - }
2070 - }
2071 -
2072 - if (empty($export_rows)) {
2073 - wp_send_json_error(['message' => 'No leads to export.']);
2074 - wp_die();
2075 - }
2076 -
2077 - $filename = 'mxchat-leads-' . date('Y-m-d') . '.csv';
2078 - header('Content-Type: text/csv');
2079 - header('Content-Disposition: attachment; filename="' . $filename . '"');
2080 - header('Pragma: no-cache');
2081 - header('Expires: 0');
2082 -
2083 - $output = fopen('php://output', 'w');
2084 - fputs($output, "\xEF\xBB\xBF"); // UTF-8 BOM for Excel
2085 -
2086 - if ($fields_mode === 'email_only') {
2087 - fputcsv($output, ['Email']);
2088 - foreach ($export_rows as $r) {
2089 - fputcsv($output, [$r['email']]);
2090 - }
2091 - } else {
2092 - fputcsv($output, ['Email', 'Name', 'Conversations', 'Last seen', 'Top page']);
2093 - foreach ($export_rows as $r) {
2094 - fputcsv($output, [
2095 - $r['email'],
2096 - $r['name'],
2097 - $r['conversation_count'],
2098 - $r['last_seen'],
2099 - $r['top_page_url'],
2100 - ]);
2101 - }
2102 - }
2103 -
2104 - fclose($output);
2105 - wp_die();
2106 -}
2107 -
2108 -/**
2109 - * Stats strip payload (independent of filters).
2110 - */
2111 -private static function mxchat_leads_stats($table, $has_page_url_column) {
2112 - global $wpdb;
2113 -
2114 - $total_transcripts_emails = (int) $wpdb->get_var(
2115 - "SELECT COUNT(DISTINCT user_email) FROM {$table}
2116 - WHERE user_email IS NOT NULL AND user_email != ''"
2117 - );
2118 -
2119 - $new_this_week = (int) $wpdb->get_var($wpdb->prepare(
2120 - "SELECT COUNT(*) FROM (
2121 - SELECT user_email FROM {$table}
2122 - WHERE user_email IS NOT NULL AND user_email != ''
2123 - GROUP BY user_email
2124 - HAVING MIN(timestamp) >= %s
2125 - ) AS new_leads",
2126 - gmdate('Y-m-d H:i:s', strtotime('-7 days'))
2127 - ));
2128 -
2129 - $total_convos = (int) $wpdb->get_var(
2130 - "SELECT COUNT(DISTINCT session_id) FROM {$table}
2131 - WHERE user_email IS NOT NULL AND user_email != ''"
2132 - );
2133 -
2134 - $orphan_count = count(self::mxchat_collect_orphan_leads(''));
2135 - $chat_deleted_count = self::mxchat_count_chat_deleted_leads();
2136 -
2137 - // Total leads = unique emails across all three sources (dedup priority: transcripts > chat_deleted > orphan
2138 - // is already enforced at collection time in mxchat_fetch_leads; stats re-apply it here).
2139 - $total_leads = $total_transcripts_emails + $chat_deleted_count + $orphan_count;
2140 -
2141 - $avg = $total_transcripts_emails > 0
2142 - ? round($total_convos / $total_transcripts_emails, 1)
2143 - : 0;
2144 -
2145 - // Orphan % reflects *true* orphans only (pre-chat dropoffs). Chat-deleted leads are
2146 - // excluded so the metric stays meaningful — admins shouldn't see their cleanups
2147 - // inflate this number.
2148 - $orphan_pct = $total_leads > 0
2149 - ? (int) round(($orphan_count / $total_leads) * 100)
2150 - : 0;
2151 -
2152 - return [
2153 - 'total_leads' => $total_leads,
2154 - 'new_this_week' => $new_this_week,
2155 - 'avg_convos' => $avg,
2156 - 'orphan_pct' => $orphan_pct,
2157 - 'orphan_count' => $orphan_count,
2158 - 'chat_deleted_count' => $chat_deleted_count,
2159 - ];
2160 -}
2161 -
2162 -/**
2163 - * Collect leads who had a conversation that an admin later deleted (preserved via
2164 - * mxchat_lead_del_* options). Returns rows tagged status='chat_deleted' with the
2165 - * original last-seen timestamp so they still sort and filter sensibly.
2166 - *
2167 - * @param string $search Optional email/name substring filter.
2168 - * @param string $date_cutoff Optional 'Y-m-d H:i:s' cutoff — only rows with last_ts >= cutoff.
2169 - * @return array
2170 - */
2171 -private static function mxchat_collect_chat_deleted_leads($search = '', $date_cutoff = '') {
2172 - global $wpdb;
2173 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2174 -
2175 - $rows = $wpdb->get_results(
2176 - "SELECT option_name, option_value FROM {$wpdb->options}
2177 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2178 - );
2179 - if (empty($rows)) {
2180 - return [];
2181 - }
2182 -
2183 - // Emails that currently have transcripts rows should not appear as chat_deleted —
2184 - // they've come back and chatted, so they're active leads again.
2185 - $emails_in_transcripts = array_map(
2186 - 'strtolower',
2187 - (array) $wpdb->get_col(
2188 - "SELECT DISTINCT user_email FROM {$table}
2189 - WHERE user_email IS NOT NULL AND user_email != ''"
2190 - )
2191 - );
2192 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2193 -
2194 - $needle = strtolower(trim((string) $search));
2195 - $by_email = [];
2196 -
2197 - foreach ($rows as $opt) {
2198 - $email = sanitize_email(trim((string) $opt->option_value));
2199 - if (!$email) {
2200 - continue;
2201 - }
2202 - if (isset($emails_in_transcripts[strtolower($email)])) {
2203 - continue;
2204 - }
2205 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2206 - if (!$sid) {
2207 - continue;
2208 - }
2209 - $name = (string) get_option('mxchat_lead_del_name_' . $sid, '');
2210 - $ts = (string) get_option('mxchat_lead_del_ts_' . $sid, '');
2211 -
2212 - if ($date_cutoff !== '' && ($ts === '' || $ts < $date_cutoff)) {
2213 - continue;
2214 - }
2215 - if ($needle !== '') {
2216 - $hay = strtolower($email . ' ' . $name);
2217 - if (strpos($hay, $needle) === false) {
2218 - continue;
2219 - }
2220 - }
2221 -
2222 - $key = strtolower($email);
2223 - if (!isset($by_email[$key]) || (isset($by_email[$key]['last_seen']) && $ts > $by_email[$key]['last_seen'])) {
2224 - $by_email[$key] = [
2225 - 'email' => $email,
2226 - 'name' => $name,
2227 - 'conversation_count' => 0,
2228 - 'last_seen' => $ts,
2229 - 'last_seen_display' => $ts ? self::mxchat_leads_format_relative($ts) : __('Chat deleted', 'mxchat'),
2230 - 'first_seen' => $ts,
2231 - 'latest_session_id' => '',
2232 - 'top_page_url' => '',
2233 - 'top_page_title' => '',
2234 - 'is_orphan' => false,
2235 - 'status' => 'chat_deleted',
2236 - ];
2237 - }
2238 - }
2239 -
2240 - // Newest chat_deleted first.
2241 - usort($by_email, function ($a, $b) {
2242 - return strcmp((string) $b['last_seen'], (string) $a['last_seen']);
2243 - });
2244 - return array_values($by_email);
2245 -}
2246 -
2247 -/**
2248 - * Count unique emails preserved as "chat deleted" (for the stats strip).
2249 - */
2250 -private static function mxchat_count_chat_deleted_leads() {
2251 - global $wpdb;
2252 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2253 -
2254 - $emails = $wpdb->get_col(
2255 - "SELECT DISTINCT option_value FROM {$wpdb->options}
2256 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2257 - );
2258 - if (empty($emails)) {
2259 - return 0;
2260 - }
2261 -
2262 - $transcripts_emails = array_map(
2263 - 'strtolower',
2264 - (array) $wpdb->get_col(
2265 - "SELECT DISTINCT user_email FROM {$table}
2266 - WHERE user_email IS NOT NULL AND user_email != ''"
2267 - )
2268 - );
2269 - $transcripts_emails = array_flip($transcripts_emails);
2270 -
2271 - $count = 0;
2272 - $seen = [];
2273 - foreach ($emails as $raw) {
2274 - $email = strtolower(trim((string) $raw));
2275 - if (!$email || isset($seen[$email]) || isset($transcripts_emails[$email])) {
2276 - continue;
2277 - }
2278 - $seen[$email] = true;
2279 - $count++;
2280 - }
2281 - return $count;
2282 -}
2283 -
2284 -/**
2285 - * Find leads who submitted the pre-chat form but never produced a transcripts row.
2286 - * Returned rows have no conversation_count, no timestamp.
2287 - *
2288 - * @param string $search Optional email/name substring filter.
2289 - * @return array
2290 - */
2291 -private static function mxchat_collect_orphan_leads($search = '') {
2292 - global $wpdb;
2293 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2294 -
2295 - $option_rows = $wpdb->get_results(
2296 - "SELECT option_name, option_value FROM {$wpdb->options}
2297 - WHERE option_name LIKE 'mxchat_email_%'"
2298 - );
2299 - if (empty($option_rows)) {
2300 - return [];
2301 - }
2302 -
2303 - // Collect all session_ids that have real transcripts rows so we can exclude them.
2304 - $session_ids_with_rows = $wpdb->get_col(
2305 - "SELECT DISTINCT session_id FROM {$table}
2306 - WHERE user_email IS NOT NULL AND user_email != ''"
2307 - );
2308 - $session_ids_with_rows = array_flip($session_ids_with_rows);
2309 -
2310 - // Seen emails in transcripts (so orphans only include truly never-chatted leads).
2311 - $emails_in_transcripts = array_map(
2312 - 'strtolower',
2313 - (array) $wpdb->get_col(
2314 - "SELECT DISTINCT user_email FROM {$table}
2315 - WHERE user_email IS NOT NULL AND user_email != ''"
2316 - )
2317 - );
2318 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2319 -
2320 - $orphans_by_email = [];
2321 - $needle = strtolower(trim((string) $search));
2322 -
2323 - foreach ($option_rows as $opt) {
2324 - $email = sanitize_email(trim((string) $opt->option_value));
2325 - if (!$email) {
2326 - continue;
2327 - }
2328 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2329 - if (!$sid) {
2330 - continue;
2331 - }
2332 - // Exclude leads who have any transcripts rows (they appear in the main list).
2333 - if (isset($emails_in_transcripts[strtolower($email)])) {
2334 - continue;
2335 - }
2336 - if (isset($session_ids_with_rows[$sid])) {
2337 - continue;
2338 - }
2339 -
2340 - $name_option = get_option('mxchat_name_' . $sid, '');
2341 - $name = is_string($name_option) ? trim($name_option) : '';
2342 -
2343 - if ($needle !== '') {
2344 - $hay = strtolower($email . ' ' . $name);
2345 - if (strpos($hay, $needle) === false) {
2346 - continue;
2347 - }
2348 - }
2349 -
2350 - $key = strtolower($email);
2351 - if (!isset($orphans_by_email[$key])) {
2352 - $orphans_by_email[$key] = [
2353 - 'email' => $email,
2354 - 'name' => $name,
2355 - 'conversation_count' => 0,
2356 - 'last_seen' => '',
2357 - 'last_seen_display' => __('No conversation yet', 'mxchat'),
2358 - 'first_seen' => '',
2359 - 'latest_session_id' => '',
2360 - 'top_page_url' => '',
2361 - 'top_page_title' => '',
2362 - 'is_orphan' => true,
2363 - 'status' => 'orphan',
2364 - ];
2365 - }
2366 - }
2367 -
2368 - return array_values($orphans_by_email);
2369 -}
2370 -
2371 -/**
2372 - * Map a date_range key to a SQL-comparable cutoff string, or '' for all-time.
2373 - */
2374 -private static function mxchat_leads_date_cutoff($date_range) {
2375 - switch ($date_range) {
2376 - case 'today': return gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
2377 - case '7d': return gmdate('Y-m-d H:i:s', strtotime('-7 days'));
2378 - case '30d': return gmdate('Y-m-d H:i:s', strtotime('-30 days'));
2379 - case '90d': return gmdate('Y-m-d H:i:s', strtotime('-90 days'));
2380 - case 'all':
2381 - default: return '';
2382 - }
2383 -}
2384 -
2385 -/**
2386 - * Turn a UTC timestamp into a short relative display like "2h ago" or "Apr 12".
2387 - */
2388 -private static function mxchat_leads_format_relative($timestamp) {
2389 - if (!$timestamp) {
2390 - return '';
2391 - }
2392 - $ts = strtotime($timestamp . ' UTC');
2393 - if (!$ts) {
2394 - return '';
2395 - }
2396 - $diff = time() - $ts;
2397 - if ($diff < 60) return __('just now', 'mxchat');
2398 - if ($diff < 3600) return floor($diff / 60) . __('m ago', 'mxchat');
2399 - if ($diff < 86400) return floor($diff / 3600) . __('h ago', 'mxchat');
2400 - if ($diff < 604800) return floor($diff / 86400) . __('d ago', 'mxchat');
2401 - return wp_date('M j', $ts);
2402 -}
2403 -
2404 -/**
2405 1509 * Handle translation of chat messages via AJAX
2406 1510 */
2407 1511 public function mxchat_translate_messages() {
2408 1512 if (!current_user_can('manage_options')) {
@@ -3621,103 +2725,53 @@
3621 2725 echo wp_json_encode(['error' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
3622 2726 wp_die();
3623 2727 }
3624 2728 check_ajax_referer('mxchat_delete_chat_history', 'security');
3625 -
3626 - if (!isset($_POST['delete_session_ids']) || !is_array($_POST['delete_session_ids'])) {
3627 - echo wp_json_encode(['error' => esc_html__('No chat sessions selected for deletion.', 'mxchat')]);
3628 - wp_die();
3629 - }
3630 -
3631 2729 global $wpdb;
3632 2730 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3633 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
3634 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
3635 2731
3636 - // When true, any lead attached to these sessions is fully wiped (all their sessions,
3637 - // across the whole table). Default false: the chat rows go away but the lead is
3638 - // preserved as a separate "chat deleted" lead in the Leads tab.
3639 - $also_delete_lead = !empty($_POST['also_delete_lead']) && $_POST['also_delete_lead'] !== 'false';
2732 + if (isset($_POST['delete_session_ids']) && is_array($_POST['delete_session_ids'])) {
2733 + $deleted_count = 0;
2734 + $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
3640 2735
3641 - $deleted_count = 0;
3642 - $preserved_as_deleted_leads = 0;
3643 - $emails_to_fully_wipe = [];
2736 + foreach ($_POST['delete_session_ids'] as $session_id) {
2737 + $session_id_sanitized = sanitize_text_field($session_id);
3644 2738
3645 - foreach ((array) $_POST['delete_session_ids'] as $session_id) {
3646 - $session_id_sanitized = sanitize_text_field($session_id);
3647 - if ($session_id_sanitized === '') {
3648 - continue;
3649 - }
2739 + // Clear relevant cache before deletion
2740 + $cache_key = 'chat_session_' . $session_id_sanitized;
2741 + wp_cache_delete($cache_key, 'mxchat_chat_sessions');
3650 2742
3651 - // Capture the lead info attached to this session *before* we delete the rows.
3652 - $lead_row = $wpdb->get_row($wpdb->prepare(
3653 - "SELECT user_email, user_name, MAX(timestamp) AS last_ts
3654 - FROM {$table_name}
3655 - WHERE session_id = %s AND user_email IS NOT NULL AND user_email != ''
3656 - GROUP BY user_email, user_name
3657 - ORDER BY last_ts DESC LIMIT 1",
3658 - $session_id_sanitized
3659 - ));
2743 + // Perform the deletion from the database table
2744 + $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
3660 2745
3661 - wp_cache_delete('chat_session_' . $session_id_sanitized, 'mxchat_chat_sessions');
3662 - $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
2746 + // Delete any saved translations for this session
2747 + if ($wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table) {
2748 + $wpdb->delete($translations_table, ['session_id' => $session_id_sanitized]);
2749 + }
3663 2750
3664 - if ($has_translations) {
3665 - $wpdb->delete($translations_table, ['session_id' => $session_id_sanitized]);
3666 - }
2751 + // Delete the corresponding option entry from wp_options table
2752 + delete_option("mxchat_history_" . $session_id_sanitized);
3667 2753
3668 - delete_option('mxchat_history_' . $session_id_sanitized);
3669 - delete_option('mxchat_agent_name_' . $session_id_sanitized);
2754 + // Delete any associated metadata options
2755 + delete_option("mxchat_email_" . $session_id_sanitized);
2756 + delete_option("mxchat_agent_name_" . $session_id_sanitized);
3670 2757
3671 - if ($lead_row && !empty($lead_row->user_email)) {
3672 - if ($also_delete_lead) {
3673 - // Full-wipe requested — queue the email so that all their sessions and
3674 - // related options get swept below. Also clear this session's pre-chat
3675 - // capture options (they're no longer meaningful).
3676 - $emails_to_fully_wipe[strtolower($lead_row->user_email)] = $lead_row->user_email;
3677 - delete_option('mxchat_email_' . $session_id_sanitized);
3678 - delete_option('mxchat_name_' . $session_id_sanitized);
3679 - } else {
3680 - // Preserve the lead in a "Chat deleted" state via distinct option keys so
3681 - // they stay out of the orphan bucket (orphan = pre-chat form dropoff).
3682 - update_option('mxchat_lead_del_email_' . $session_id_sanitized, $lead_row->user_email, false);
3683 - if (!empty($lead_row->user_name)) {
3684 - update_option('mxchat_lead_del_name_' . $session_id_sanitized, $lead_row->user_name, false);
3685 - }
3686 - if (!empty($lead_row->last_ts)) {
3687 - update_option('mxchat_lead_del_ts_' . $session_id_sanitized, $lead_row->last_ts, false);
3688 - }
3689 - // Clean up pre-chat capture options for this session — chat_deleted supersedes.
3690 - delete_option('mxchat_email_' . $session_id_sanitized);
3691 - delete_option('mxchat_name_' . $session_id_sanitized);
3692 - $preserved_as_deleted_leads++;
3693 - }
3694 - } else {
3695 - // No lead attached — nothing to preserve. Clean up any orphan options anyway.
3696 - delete_option('mxchat_email_' . $session_id_sanitized);
3697 - delete_option('mxchat_name_' . $session_id_sanitized);
2758 + $deleted_count++;
3698 2759 }
3699 2760
3700 - $deleted_count++;
3701 - }
2761 + // Optionally, clear a general cache if you have one
2762 + wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
3702 2763
3703 - // Opt-in full-lead wipe: sweep every remaining row + every option key (including
3704 - // chat_deleted preservation) for each affected email. Reuses the same internal
3705 - // helper as the Leads-tab Delete button for consistency.
3706 - if (!empty($emails_to_fully_wipe)) {
3707 - self::mxchat_wipe_leads_by_email(array_values($emails_to_fully_wipe));
2764 + echo wp_json_encode([
2765 + 'success' => sprintf(
2766 + esc_html__('%d chat session(s) have been deleted from all storage locations.', 'mxchat'),
2767 + $deleted_count
2768 + )
2769 + ]);
2770 + } else {
2771 + echo wp_json_encode(['error' => esc_html__('No chat sessions selected for deletion.', 'mxchat')]);
3708 2772 }
3709 2773
3710 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
3711 -
3712 - echo wp_json_encode([
3713 - 'success' => sprintf(
3714 - esc_html__('%d chat session(s) have been deleted.', 'mxchat'),
3715 - $deleted_count
3716 - ),
3717 - 'preserved_as_deleted_leads' => $preserved_as_deleted_leads,
3718 - 'leads_fully_wiped' => count($emails_to_fully_wipe),
3719 - ]);
3720 2774 wp_die();
3721 2775 }
3722 2776
3723 2777 /**
@@ -4593,14 +3647,13 @@
4593 3647 'intent_label' => $intent_label,
4594 3648 'phrases' => implode(', ', $phrases_array),
4595 3649 'embedding_vector' => $serialized_vector,
4596 3650 'similarity_threshold' => $similarity_threshold,
4597 - 'enabled_bots' => $enabled_bots_json, // Include enabled_bots in update
4598 - 'embedding_model' => MxChat_Utils::get_active_embedding_model()
3651 + 'enabled_bots' => $enabled_bots_json // Include enabled_bots in update
4599 3652 ),
4600 3653 array('id' => $intent_id),
4601 - array('%s', '%s', '%s', '%f', '%s', '%s'), // Format: string, string, string, float, string, string
4602 - array('%d') // Where format: integer
3654 + array('%s', '%s', '%s', '%f', '%s'), // Format: string, string, string, float, string
3655 + array('%d') // Where format: integer
4603 3656 );
4604 3657
4605 3658 if (false === $result) {
4606 3659 $this->handle_embedding_error(__('Failed to update action in database.', 'mxchat'));
@@ -4713,10 +3766,9 @@
4713 3766 'phrases' => implode(', ', $phrases_array),
4714 3767 'embedding_vector' => $serialized_vector,
4715 3768 'callback_function' => $callback_function,
4716 3769 'similarity_threshold' => $similarity_threshold,
4717 - 'enabled_bots' => $enabled_bots_json, // NEW field
4718 - 'embedding_model' => MxChat_Utils::get_active_embedding_model()
3770 + 'enabled_bots' => $enabled_bots_json // NEW field
4719 3771 ]);
4720 3772
4721 3773 if ($result === false) {
4722 3774 $this->handle_embedding_error(__('Database error: ', 'mxchat') . $wpdb->last_error);
@@ -5009,9 +4061,8 @@
5009 4061 array(
5010 4062 'intent_id' => $intent_id,
5011 4063 'phrase' => $phrase,
5012 4064 'embedding_vector' => maybe_serialize($embedding_vector),
5013 - 'embedding_model' => MxChat_Utils::get_active_embedding_model(),
5014 4065 )
5015 4066 );
5016 4067 }
5017 4068
@@ -5047,9 +4098,8 @@
5047 4098 'similarity_threshold' => $similarity_threshold,
5048 4099 'callback_function' => $callback_function,
5049 4100 'enabled' => 1,
5050 4101 'enabled_bots' => $enabled_bots_json,
5051 - 'embedding_model' => MxChat_Utils::get_active_embedding_model(),
5052 4102 )
5053 4103 );
5054 4104
5055 4105 if ($result === false) {
@@ -5123,9 +4173,8 @@
5123 4173 'embedding_vector' => $serialized_vector,
5124 4174 'similarity_threshold' => $similarity_threshold,
5125 4175 'callback_function' => $callback_function,
5126 4176 'enabled_bots' => json_encode($enabled_bots),
5127 - 'embedding_model' => MxChat_Utils::get_active_embedding_model(),
5128 4177 );
5129 4178 }
5130 4179 }
5131 4180
@@ -5221,9 +4270,8 @@
5221 4270 array(
5222 4271 'intent_id' => $intent_id,
5223 4272 'phrase' => $phrase,
5224 4273 'embedding_vector' => maybe_serialize($embedding_vector),
5225 - 'embedding_model' => MxChat_Utils::get_active_embedding_model(),
5226 4274 )
5227 4275 );
5228 4276
5229 4277 if ($result === false) {
@@ -7231,9 +6279,8 @@
7231 6279 } else {
7232 6280 echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7233 6281 }
7234 6282 echo '</p>';
7235 -
7236 6283 }
7237 6284
7238 6285
7239 6286 public function mxchat_top_bar_title_callback() {
@@ -9573,9 +8620,8 @@
9573 8620 if ($embedding_dimensions !== 1536) {
9574 8621 //error_log('[MXCHAT-EMBED] Warning: Unexpected Gemini embedding dimensions: ' . $embedding_dimensions);
9575 8622 }
9576 8623
9577 - MxChat_Utils::stamp_active_embedding_model($selected_model);
9578 8624 return $response_data['embedding']['values'];
9579 8625 } else {
9580 8626 //error_log('[MXCHAT-EMBED] Error: No embedding found in Gemini response');
9581 8627 //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
@@ -9601,9 +8647,8 @@
9601 8647 ($selected_model === 'voyage-3-large' && $embedding_dimensions !== 2048)) {
9602 8648 //error_log('[MXCHAT-EMBED] Warning: Unexpected embedding dimensions');
9603 8649 }
9604 8650
9605 - MxChat_Utils::stamp_active_embedding_model($selected_model);
9606 8651 return $response_data['data'][0]['embedding'];
9607 8652 } else {
9608 8653 //error_log('[MXCHAT-EMBED] Error: No embedding found in response');
9609 8654 //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));