PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.24
MxChat – AI Chatbot & Content Generation for WordPress v3.2.24
3.2.25 3.2.24 3.2.23 3.2.22 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 All 156 releases
mxchat-basic / includes / admin-knowledge-page.php

admin-knowledge-page.php in MxChat – AI Chatbot & Content Generation for WordPress 3.2.24, at includes/admin-knowledge-page.php

3,043 lines 220.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * MxChat Knowledge Base Page - Redesigned with Sidebar Navigation
4 *
5 * @package MxChat
6 * @since 2.7.0
7 */
8
9 if (!defined('ABSPATH')) {
10 exit;
11 }
12
13 /**
14 * Render the new sidebar-based Knowledge Base page
15 */
16 function mxchat_render_knowledge_page($admin_instance, $knowledge_manager, $page_data) {
17 $is_activated = $admin_instance->is_activated();
18 $plugin_url = plugin_dir_url(dirname(__FILE__));
19
20 // Check if integrations are active
21 $pinecone_options = get_option('mxchat_pinecone_addon_options', array());
22 $is_pinecone_active = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
23
24 $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
25 $is_vectorstore_active = ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') === '1';
26
27 // Extract page data
28 extract($page_data);
29 ?>
30 <div class="mxch-admin-wrapper">
31 <!-- Mobile Header -->
32 <header class="mxch-mobile-header">
33 <a href="#" class="mxch-mobile-logo">
34 <div class="mxch-mobile-logo-icon">
35 <img src="<?php echo esc_url($plugin_url . 'images/icon-128x128.png'); ?>" alt="MxChat">
36 </div>
37 <span class="mxch-mobile-logo-text">MxChat</span>
38 </a>
39 <button type="button" class="mxch-mobile-menu-btn" aria-label="<?php esc_attr_e('Open menu', 'mxchat'); ?>">
40 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="1"/><circle cx="12" cy="5" r="1"/><circle cx="12" cy="19" r="1"/></svg>
41 </button>
42 </header>
43
44 <!-- Mobile Menu Overlay -->
45 <div class="mxch-mobile-overlay"></div>
46
47 <!-- Mobile Menu Modal -->
48 <div class="mxch-mobile-menu">
49 <div class="mxch-mobile-menu-header">
50 <span class="mxch-mobile-menu-title"><?php esc_html_e('Knowledge Base', 'mxchat'); ?></span>
51 <button type="button" class="mxch-mobile-menu-close" aria-label="<?php esc_attr_e('Close menu', 'mxchat'); ?>">
52 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
53 </button>
54 </div>
55 <nav class="mxch-mobile-menu-nav">
56 <!-- Import Section -->
57 <div class="mxch-mobile-nav-section">
58 <div class="mxch-mobile-nav-section-title"><?php esc_html_e('Import', 'mxchat'); ?></div>
59 <button class="mxch-mobile-nav-link active" data-target="import-options">
60 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
61 <span><?php esc_html_e('Import Options', 'mxchat'); ?></span>
62 </button>
63 <button class="mxch-mobile-nav-link" data-target="knowledge-base">
64 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>
65 <span><?php esc_html_e('Knowledge Base', 'mxchat'); ?></span>
66 </button>
67 </div>
68 <!-- Settings Section -->
69 <div class="mxch-mobile-nav-section">
70 <div class="mxch-mobile-nav-section-title"><?php esc_html_e('Settings', 'mxchat'); ?></div>
71 <button class="mxch-mobile-nav-link" data-target="auto-sync">
72 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/></svg>
73 <span><?php esc_html_e('Auto-Sync', 'mxchat'); ?></span>
74 </button>
75 <button class="mxch-mobile-nav-link" data-target="chunking">
76 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
77 <span><?php esc_html_e('Chunking & Retrieval', 'mxchat'); ?></span>
78 </button>
79 <button class="mxch-mobile-nav-link" data-target="role-restrictions">
80 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
81 <span><?php esc_html_e('Role Restrictions', 'mxchat'); ?></span>
82 </button>
83 <button class="mxch-mobile-nav-link" data-target="acf-fields">
84 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/></svg>
85 <span><?php esc_html_e('ACF Fields', 'mxchat'); ?></span>
86 </button>
87 <button class="mxch-mobile-nav-link" data-target="custom-meta">
88 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7V4h16v3"/><path d="M9 20h6"/><path d="M12 4v16"/></svg>
89 <span><?php esc_html_e('Custom Meta', 'mxchat'); ?></span>
90 </button>
91 </div>
92 <!-- Integrations Section -->
93 <div class="mxch-mobile-nav-section">
94 <div class="mxch-mobile-nav-section-title"><?php esc_html_e('Integrations', 'mxchat'); ?></div>
95 <button class="mxch-mobile-nav-link" data-target="pinecone">
96 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>
97 <span><?php esc_html_e('Pinecone', 'mxchat'); ?></span>
98 <?php if ($is_pinecone_active): ?>
99 <span class="mxch-nav-link-badge mxch-active-badge"><?php esc_html_e('Active', 'mxchat'); ?></span>
100 <?php endif; ?>
101 </button>
102 <button class="mxch-mobile-nav-link" data-target="openai-vectorstore">
103 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/><path d="M11 8v6"/><path d="M8 11h6"/></svg>
104 <span><?php esc_html_e('OpenAI Vector Store', 'mxchat'); ?></span>
105 <?php if ($is_vectorstore_active): ?>
106 <span class="mxch-nav-link-badge mxch-active-badge"><?php esc_html_e('Active', 'mxchat'); ?></span>
107 <?php endif; ?>
108 </button>
109 </div>
110 <?php if (!$is_activated): ?>
111 <div class="mxch-mobile-menu-footer">
112 <a href="https://mxchat.ai/" target="_blank" class="mxch-mobile-upgrade-btn">
113 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg>
114 <?php esc_html_e('Upgrade to Pro', 'mxchat'); ?>
115 </a>
116 </div>
117 <?php endif; ?>
118 </nav>
119 </div>
120
121 <!-- Sidebar Navigation -->
122 <aside class="mxch-sidebar">
123 <div class="mxch-sidebar-header">
124 <a href="#" class="mxch-sidebar-logo">
125 <div class="mxch-sidebar-logo-icon">
126 <img src="<?php echo esc_url($plugin_url . 'images/icon-128x128.png'); ?>" alt="MxChat">
127 </div>
128 <span class="mxch-sidebar-logo-text">MxChat</span>
129 <span class="mxch-sidebar-version">v<?php echo esc_html(MXCHAT_VERSION ?? '2.7.0'); ?></span>
130 </a>
131 </div>
132
133 <nav class="mxch-sidebar-nav">
134 <!-- Import Section -->
135 <div class="mxch-nav-section">
136 <div class="mxch-nav-section-title"><?php esc_html_e('Import', 'mxchat'); ?></div>
137
138 <div class="mxch-nav-item" data-section="import-options">
139 <button class="mxch-nav-link active" data-target="import-options">
140 <span class="mxch-nav-link-icon">
141 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
142 </span>
143 <span class="mxch-nav-link-text"><?php esc_html_e('Import Options', 'mxchat'); ?></span>
144 </button>
145 </div>
146
147 <div class="mxch-nav-item" data-section="knowledge-base">
148 <button class="mxch-nav-link" data-target="knowledge-base">
149 <span class="mxch-nav-link-icon">
150 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>
151 </span>
152 <span class="mxch-nav-link-text"><?php esc_html_e('Knowledge Base', 'mxchat'); ?></span>
153 <span id="mxchat-sidebar-count" class="mxch-nav-link-badge"><?php echo esc_html($total_records); ?></span>
154 </button>
155 </div>
156 </div>
157
158 <!-- Settings Section -->
159 <div class="mxch-nav-section">
160 <div class="mxch-nav-section-title"><?php esc_html_e('Settings', 'mxchat'); ?></div>
161
162 <div class="mxch-nav-item" data-section="auto-sync">
163 <button class="mxch-nav-link" data-target="auto-sync">
164 <span class="mxch-nav-link-icon">
165 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/></svg>
166 </span>
167 <span class="mxch-nav-link-text"><?php esc_html_e('Auto-Sync', 'mxchat'); ?></span>
168 </button>
169 </div>
170
171 <div class="mxch-nav-item" data-section="chunking">
172 <button class="mxch-nav-link" data-target="chunking">
173 <span class="mxch-nav-link-icon">
174 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
175 </span>
176 <span class="mxch-nav-link-text"><?php esc_html_e('Chunking & Retrieval', 'mxchat'); ?></span>
177 </button>
178 </div>
179
180 <div class="mxch-nav-item" data-section="role-restrictions">
181 <button class="mxch-nav-link" data-target="role-restrictions">
182 <span class="mxch-nav-link-icon">
183 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
184 </span>
185 <span class="mxch-nav-link-text"><?php esc_html_e('Role Restrictions', 'mxchat'); ?></span>
186 </button>
187 </div>
188
189 <div class="mxch-nav-item" data-section="acf-fields">
190 <button class="mxch-nav-link" data-target="acf-fields">
191 <span class="mxch-nav-link-icon">
192 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/></svg>
193 </span>
194 <span class="mxch-nav-link-text"><?php esc_html_e('ACF Fields', 'mxchat'); ?></span>
195 </button>
196 </div>
197
198 <div class="mxch-nav-item" data-section="custom-meta">
199 <button class="mxch-nav-link" data-target="custom-meta">
200 <span class="mxch-nav-link-icon">
201 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7V4h16v3"/><path d="M9 20h6"/><path d="M12 4v16"/></svg>
202 </span>
203 <span class="mxch-nav-link-text"><?php esc_html_e('Custom Meta', 'mxchat'); ?></span>
204 </button>
205 </div>
206 </div>
207
208 <!-- Integrations Section -->
209 <div class="mxch-nav-section">
210 <div class="mxch-nav-section-title"><?php esc_html_e('Integrations', 'mxchat'); ?></div>
211
212 <div class="mxch-nav-item" data-section="pinecone">
213 <button class="mxch-nav-link" data-target="pinecone">
214 <span class="mxch-nav-link-icon">
215 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>
216 </span>
217 <span class="mxch-nav-link-text"><?php esc_html_e('Pinecone', 'mxchat'); ?></span>
218 <?php if ($is_pinecone_active): ?>
219 <span class="mxch-nav-link-badge mxch-active-badge"><?php esc_html_e('Active', 'mxchat'); ?></span>
220 <?php endif; ?>
221 </button>
222 </div>
223
224 <div class="mxch-nav-item" data-section="openai-vectorstore">
225 <button class="mxch-nav-link" data-target="openai-vectorstore">
226 <span class="mxch-nav-link-icon">
227 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/><path d="M11 8v6"/><path d="M8 11h6"/></svg>
228 </span>
229 <span class="mxch-nav-link-text"><?php esc_html_e('OpenAI Vector Store', 'mxchat'); ?></span>
230 <?php if ($is_vectorstore_active): ?>
231 <span class="mxch-nav-link-badge mxch-active-badge"><?php esc_html_e('Active', 'mxchat'); ?></span>
232 <?php endif; ?>
233 </button>
234 </div>
235 </div>
236 </nav>
237
238 <?php if (!$is_activated): ?>
239 <div class="mxch-sidebar-footer">
240 <a href="https://mxchat.ai/" target="_blank" class="mxch-sidebar-upgrade-v2">
241 <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"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>
242 <?php esc_html_e('Pro Upgrade', 'mxchat'); ?>
243 </a>
244 </div>
245 <?php endif; ?>
246 </aside>
247
248 <!-- Main Content Area -->
249 <main class="mxch-content">
250 <?php
251 // Multi-Bot Selector
252 mxchat_render_knowledge_bot_selector($multibot_active, $current_bot_id);
253
254 // Global Processing Status - Always visible when processing
255 mxchat_render_global_processing_status($page_data, $knowledge_manager);
256
257 // Render content sections
258 mxchat_render_import_options_section($admin_instance, $knowledge_manager, $page_data);
259 mxchat_render_knowledge_base_section($admin_instance, $knowledge_manager, $page_data);
260 mxchat_render_auto_sync_section($knowledge_manager);
261 mxchat_render_chunking_section();
262 mxchat_render_role_restrictions_section($knowledge_manager);
263 mxchat_render_acf_fields_section($knowledge_manager);
264 mxchat_render_custom_meta_section();
265 mxchat_render_pinecone_section();
266 mxchat_render_openai_vectorstore_section();
267 ?>
268
269 </main>
270 </div>
271
272 <?php
273 // Render the Content Selector Modal
274 mxchat_render_content_selector_modal();
275
276 // Render the Edit Entry Modal
277 mxchat_render_edit_entry_modal();
278
279 // Render the read-only Knowledge Inspector modal (plan-d8cb4b)
280 mxchat_render_inspect_entry_modal();
281
282 // Render the navigation JavaScript
283 mxchat_render_knowledge_page_scripts();
284 }
285
286 /**
287 * Whether the selected bot answers from the WordPress database (plan 1f39d9).
288 * That store is one table every bot reads. A bot has knowledge of its own only
289 * on Pinecone (its own host or namespace) or an OpenAI Vector Store, so the
290 * selector must not promise a per-bot knowledge base here.
291 */
292 function mxchat_knowledge_bot_uses_shared_database($bot_id) {
293 $pinecone = class_exists('MxChat_Pinecone_Documents') ? MxChat_Pinecone_Documents::config($bot_id) : array();
294 if (!empty($pinecone['use_pinecone'])) {
295 return false;
296 }
297 $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
298 $vectorstore = apply_filters('mxchat_get_bot_vectorstore_config', array(
299 'use_vectorstore' => (is_array($vectorstore_options) ? ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') : '0') === '1',
300 'vectorstore_ids' => is_array($vectorstore_options) ? ($vectorstore_options['mxchat_vectorstore_ids'] ?? '') : '',
301 ), $bot_id);
302 return empty($vectorstore['use_vectorstore']);
303 }
304
305 /**
306 * Render Multi-Bot Selector
307 */
308 function mxchat_render_knowledge_bot_selector($multibot_active, $current_bot_id) {
309 if (!$multibot_active || !class_exists('MxChat_Multi_Bot_Manager')) {
310 return;
311 }
312
313 $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
314 $available_bots = $multi_bot_manager->get_available_bots();
315 ?>
316 <div class="mxch-card" style="margin-bottom: 24px;">
317 <div class="mxch-card-body">
318 <div style="display: flex; align-items: center; gap: 15px; flex-wrap: wrap;">
319 <label for="mxchat-bot-selector" style="font-weight: 600; white-space: nowrap;">
320 <?php esc_html_e('Select Bot Database:', 'mxchat'); ?>
321 </label>
322 <select id="mxchat-bot-selector" class="mxch-select" style="min-width: 200px; max-width: 300px;">
323 <?php foreach ($available_bots as $bot_id => $bot_name) : ?>
324 <option value="<?php echo esc_attr($bot_id); ?>" <?php selected($current_bot_id, $bot_id); ?>>
325 <?php echo esc_html($bot_name); ?>
326 </option>
327 <?php endforeach; ?>
328 </select>
329 <span style="color: var(--mxch-text-secondary); font-size: 13px;">
330 <?php
331 if (mxchat_knowledge_bot_uses_shared_database($current_bot_id)) {
332 esc_html_e('This bot answers from the WordPress database, which is shared with all bots: content added here is available to every bot that uses it. A bot gets a knowledge base of its own on Pinecone (its own host or namespace) or an OpenAI Vector Store.', 'mxchat');
333 } else {
334 esc_html_e('Content will be added to the selected bot\'s knowledge base', 'mxchat');
335 }
336 ?>
337 </span>
338 <span id="mxchat-bot-save-status" style="display: none; color: var(--mxch-success); font-size: 13px;">
339 ✓ <?php esc_html_e('Saved', 'mxchat'); ?>
340 </span>
341 </div>
342 </div>
343 </div>
344 <?php
345 }
346
347 /**
348 * Render Global Processing Status - Always visible when processing is active
349 */
350 function mxchat_render_global_processing_status($page_data, $knowledge_manager) {
351 extract($page_data);
352
353 // Only show if there's active processing
354 if (!$is_processing) {
355 return;
356 }
357 ?>
358 <div class="mxch-processing-status-global mxchat-import-section" style="margin-bottom: 24px;">
359 <?php
360 // PDF Processing Status - Using mxchat-status-card class for JavaScript compatibility
361 if ($pdf_status && $pdf_status['status'] === 'processing') : ?>
362 <div class="mxchat-status-card mxch-card" data-card-type="pdf" data-queue-id="<?php echo esc_attr(get_transient('mxchat_active_queue_pdf')); ?>" style="border-left: 4px solid var(--mxch-primary); margin-bottom: 16px;">
363 <div class="mxchat-status-header mxch-card-header" style="background: var(--mxch-primary-light);">
364 <h4 style="margin: 0; display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 600;">
365 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>
366 <?php esc_html_e('PDF Processing Status', 'mxchat'); ?>
367 </h4>
368 <div class="mxchat-status-warning" style="background: #fff3cd; color: #856404; padding: 8px 12px; border-radius: 4px; font-size: 13px; margin: 10px 0;">
369 <?php esc_html_e('Keep this tab open - Processing runs in your browser', 'mxchat'); ?>
370 </div>
371 <form method="post" class="mxchat-stop-form" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_stop_processing')); ?>">
372 <?php wp_nonce_field('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce'); ?>
373 <button type="submit" name="stop_processing" class="mxchat-button-secondary mxch-btn mxch-btn-secondary mxch-btn-sm">
374 <?php esc_html_e('Stop Processing', 'mxchat'); ?>
375 </button>
376 </form>
377 </div>
378 <div class="mxchat-progress-bar" style="height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; margin: 0;">
379 <div class="mxchat-progress-fill" style="height: 100%; background: var(--mxch-primary); width: <?php echo esc_attr($pdf_status['percentage']); ?>%; transition: width 0.3s;"></div>
380 </div>
381 <div class="mxchat-status-details mxch-card-body">
382 <p><?php printf(esc_html__('Progress: %1$d of %2$d pages (%3$d%%)', 'mxchat'), absint($pdf_status['processed_pages']), absint($pdf_status['total_pages']), absint($pdf_status['percentage'])); ?></p>
383 <?php if (!empty($pdf_status['failed_pages']) && $pdf_status['failed_pages'] > 0) : ?>
384 <p class="error-count" style="color: var(--mxch-error);"><strong><?php esc_html_e('Failed pages:', 'mxchat'); ?></strong> <?php echo esc_html($pdf_status['failed_pages']); ?></p>
385 <?php endif; ?>
386 <p><strong><?php esc_html_e('Status:', 'mxchat'); ?></strong> <?php esc_html_e('Processing', 'mxchat'); ?></p>
387 </div>
388 </div>
389 <?php endif;
390
391 // Sitemap Processing Status - Using mxchat-status-card class for JavaScript compatibility
392 if ($sitemap_status && $sitemap_status['status'] === 'processing') : ?>
393 <div class="mxchat-status-card mxch-card" data-card-type="sitemap" data-queue-id="<?php echo esc_attr(get_transient('mxchat_active_queue_sitemap')); ?>" style="border-left: 4px solid var(--mxch-primary); margin-bottom: 16px;">
394 <div class="mxchat-status-header mxch-card-header" style="background: var(--mxch-primary-light);">
395 <h4 style="margin: 0; display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 600;">
396 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
397 <?php esc_html_e('Sitemap Processing Status', 'mxchat'); ?>
398 </h4>
399 <div class="mxchat-status-warning" style="background: #fff3cd; color: #856404; padding: 8px 12px; border-radius: 4px; font-size: 13px; margin: 10px 0;">
400 <?php esc_html_e('Keep this tab open - Processing runs in your browser', 'mxchat'); ?>
401 </div>
402 <form method="post" class="mxchat-stop-form" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_stop_processing')); ?>">
403 <?php wp_nonce_field('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce'); ?>
404 <button type="submit" name="stop_processing" class="mxchat-button-secondary mxch-btn mxch-btn-secondary mxch-btn-sm">
405 <?php esc_html_e('Stop Processing', 'mxchat'); ?>
406 </button>
407 </form>
408 </div>
409 <div class="mxchat-progress-bar" style="height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; margin: 0;">
410 <div class="mxchat-progress-fill" style="height: 100%; background: var(--mxch-primary); width: <?php echo esc_attr($sitemap_status['percentage']); ?>%; transition: width 0.3s;"></div>
411 </div>
412 <div class="mxchat-status-details mxch-card-body">
413 <p><?php printf(esc_html__('Progress: %1$d of %2$d URLs (%3$d%%)', 'mxchat'), absint($sitemap_status['processed_urls']), absint($sitemap_status['total_urls']), absint($sitemap_status['percentage'])); ?></p>
414 <?php if (!empty($sitemap_status['failed_urls']) && $sitemap_status['failed_urls'] > 0) : ?>
415 <p class="error-count" style="color: var(--mxch-error);"><strong><?php esc_html_e('Failed URLs:', 'mxchat'); ?></strong> <?php echo esc_html($sitemap_status['failed_urls']); ?></p>
416 <?php endif; ?>
417 <p><strong><?php esc_html_e('Status:', 'mxchat'); ?></strong> <?php esc_html_e('Processing', 'mxchat'); ?></p>
418 </div>
419 </div>
420 <?php endif;
421
422 // Completed status cards
423 echo $knowledge_manager->mxchat_render_completed_status_cards();
424 ?>
425 </div>
426 <?php
427 }
428
429 /**
430 * Render Import Options Section
431 */
432 function mxchat_render_import_options_section($admin_instance, $knowledge_manager, $page_data) {
433 extract($page_data);
434 $options = $admin_instance->options ?? get_option('mxchat_options', array());
435
436 // Check if user is using WordPress database (not Pinecone or OpenAI Vector Store)
437 $pinecone_options = get_option('mxchat_pinecone_addon_options', array());
438 $is_pinecone_active = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
439 $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
440 $is_vectorstore_active = ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') === '1';
441 $is_using_wordpress_db = !$is_pinecone_active && !$is_vectorstore_active;
442
443 // Check embedding API key
444 $embedding_model = isset($options['embedding_model']) ? esc_attr($options['embedding_model']) : 'text-embedding-ada-002';
445 $has_openai_key = !empty($options['api_key']);
446 $has_voyage_key = !empty($options['voyage_api_key']);
447 $has_gemini_key = !empty($options['gemini_api_key']);
448
449 $has_required_key = false;
450 $required_key_type = '';
451
452 if (strpos($embedding_model, 'text-embedding-') !== false && $has_openai_key) {
453 $has_required_key = true;
454 $required_key_type = 'OpenAI';
455 } elseif (strpos($embedding_model, 'voyage-') !== false && $has_voyage_key) {
456 $has_required_key = true;
457 $required_key_type = 'Voyage AI';
458 } elseif (strpos($embedding_model, 'gemini-embedding-') !== false && $has_gemini_key) {
459 $has_required_key = true;
460 $required_key_type = 'Google Gemini';
461 } elseif (strpos($embedding_model, 'text-embedding-') !== false) {
462 $required_key_type = 'OpenAI';
463 } elseif (strpos($embedding_model, 'voyage-') !== false) {
464 $required_key_type = 'Voyage AI';
465 } elseif (strpos($embedding_model, 'gemini-embedding-') !== false) {
466 $required_key_type = 'Google Gemini';
467 }
468
469 // Custom Provider embeddings (plan 418afd): the dropdown above is disabled
470 // on such a site and no OpenAI, Voyage or Gemini key is needed. Ask the
471 // same pre-flight the importers ask, so this notice cannot disagree with them.
472 $embeds_with_custom_provider = is_array($options) && isset($options['custom_provider_for_embeddings']) && $options['custom_provider_for_embeddings'] === 'on';
473 $custom_embedding_blocker = '';
474 if ($embeds_with_custom_provider) {
475 $custom_preflight = MxChat_Utils::embedding_preflight($options);
476 $has_required_key = !empty($custom_preflight['ok']);
477 $required_key_type = 'Custom Provider';
478 $custom_embedding_blocker = (string) ($custom_preflight['reason'] ?? '');
479 }
480 ?>
481 <div id="import-options" class="mxch-section active">
482 <div class="mxch-content-header">
483 <h1 class="mxch-content-title"><?php esc_html_e('Import Options', 'mxchat'); ?></h1>
484 <p class="mxch-content-subtitle"><?php esc_html_e('Import content to your knowledge base from various sources.', 'mxchat'); ?></p>
485 </div>
486
487 <!-- API Key Status -->
488 <div class="mxch-notice <?php echo $has_required_key ? 'mxch-notice-success' : 'mxch-notice-warning'; ?>" style="margin-bottom: 24px;">
489 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
490 <?php if ($has_required_key): ?>
491 <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>
492 <?php else: ?>
493 <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>
494 <?php endif; ?>
495 </svg>
496 <div>
497 <?php if ($embeds_with_custom_provider && $has_required_key): ?>
498 <?php
499 /* translators: %s: the embedding model name configured on the Custom Provider */
500 printf(esc_html__('Knowledge is embedded through your Custom Provider (model: %s). No OpenAI, Voyage AI or Google Gemini key is needed for imports.', 'mxchat'), esc_html(MxChat_Utils::resolve_custom_embedding_model($options)));
501 ?>
502 <?php elseif ($embeds_with_custom_provider): ?>
503 <strong><?php esc_html_e('Important:', 'mxchat'); ?></strong>
504 <?php echo esc_html($custom_embedding_blocker); ?>
505 <a href="<?php echo admin_url('admin.php?page=mxchat-max#api-keys'); ?>"><?php esc_html_e('Go to API Key Settings', 'mxchat'); ?></a>
506 <?php elseif ($has_required_key): ?>
507 <?php echo wp_kses_post(sprintf(__('We detected your %s API key. <strong>Remember to add credits to your %s account</strong> before using the knowledgebase.', 'mxchat'), $required_key_type, $required_key_type)); ?>
508 <?php else: ?>
509 <strong><?php esc_html_e('Important:', 'mxchat'); ?></strong>
510 <?php echo sprintf(esc_html__('Before importing knowledge, you must add a %s API key with sufficient credits in the Chatbot settings.', 'mxchat'), $required_key_type); ?>
511 <a href="<?php echo admin_url('admin.php?page=mxchat-max#api-keys'); ?>"><?php esc_html_e('Go to API Key Settings', 'mxchat'); ?></a>
512 <?php endif; ?>
513 </div>
514 </div>
515
516 <?php if ($is_using_wordpress_db): ?>
517 <!-- WordPress Database Caution Notice -->
518 <div class="mxch-notice mxch-notice-warning" style="margin-bottom: 24px;">
519 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
520 <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>
521 </svg>
522 <div>
523 <strong><?php esc_html_e('Using WordPress Database:', 'mxchat'); ?></strong>
524 <?php esc_html_e('The WordPress database is not optimized for vector search with large datasets. If you plan to have more than 500 knowledge entries, we highly recommend using Pinecone for better performance and scalability.', 'mxchat'); ?>
525 </div>
526 </div>
527 <?php endif; ?>
528
529 <div class="mxch-card">
530 <div class="mxch-card-header">
531 <h3 class="mxch-card-title">
532 <svg class="mxch-card-title-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
533 <?php esc_html_e('Choose Import Method', 'mxchat'); ?>
534 </h3>
535 </div>
536 <div class="mxch-card-body">
537 <!-- Import Options Grid -->
538 <div class="mxchat-import-options">
539 <!-- WordPress Import Option -->
540 <button type="button" id="mxchat-open-content-selector" class="mxchat-import-box mxchat-import-wordpress" data-option="wordpress">
541 <div class="mxchat-import-icon">
542 <span class="dashicons dashicons-wordpress"></span>
543 </div>
544 <div class="mxchat-import-content">
545 <h4><?php esc_html_e('WordPress Content', 'mxchat'); ?></h4>
546 <p><?php esc_html_e('Import specific posts and pages to your knowledge base.', 'mxchat'); ?></p>
547 </div>
548 <div class="mxchat-recommended-tag"><?php esc_html_e('Recommended', 'mxchat'); ?></div>
549 </button>
550
551 <!-- Sitemap Import Option -->
552 <button type="button" class="mxchat-import-box" data-option="sitemap" data-placeholder="<?php esc_attr_e('Enter sitemap URL here', 'mxchat'); ?>" data-type="sitemap">
553 <div class="mxchat-import-icon">
554 <span class="dashicons dashicons-admin-site-alt"></span>
555 </div>
556 <div class="mxchat-import-content">
557 <h4><?php esc_html_e('Sitemap Import', 'mxchat'); ?></h4>
558 <p><?php esc_html_e('Use a content-specific sub-sitemap, not the sitemap index.', 'mxchat'); ?></p>
559 </div>
560 </button>
561
562 <!-- Direct URL Import Option -->
563 <button type="button" class="mxchat-import-box" data-option="url" data-placeholder="<?php esc_attr_e('Enter webpage URL here', 'mxchat'); ?>" data-type="url">
564 <div class="mxchat-import-icon">
565 <span class="dashicons dashicons-admin-links"></span>
566 </div>
567 <div class="mxchat-import-content">
568 <h4><?php esc_html_e('Direct URL', 'mxchat'); ?></h4>
569 <p><?php esc_html_e('Import content from any webpage.', 'mxchat'); ?></p>
570 </div>
571 </button>
572
573 <!-- Direct Content Import Option -->
574 <button type="button" class="mxchat-import-box" data-option="content" data-type="content">
575 <div class="mxchat-import-icon">
576 <span class="dashicons dashicons-editor-paste-text"></span>
577 </div>
578 <div class="mxchat-import-content">
579 <h4><?php esc_html_e('Direct Content', 'mxchat'); ?></h4>
580 <p><?php esc_html_e('Submit content to be vectorized.', 'mxchat'); ?></p>
581 </div>
582 </button>
583
584 <!-- PDF Import Option (URL) -->
585 <button type="button" class="mxchat-import-box" data-option="pdf-url" data-placeholder="<?php esc_attr_e('Enter PDF URL here', 'mxchat'); ?>" data-type="pdf">
586 <div class="mxchat-import-icon">
587 <span class="dashicons dashicons-media-document"></span>
588 </div>
589 <div class="mxchat-import-content">
590 <h4><?php esc_html_e('PDF Import', 'mxchat'); ?></h4>
591 <p><?php esc_html_e('Import knowledge from PDF URL.', 'mxchat'); ?></p>
592 </div>
593 </button>
594
595 <!-- PDF File Upload Option -->
596 <button type="button" class="mxchat-import-box" data-option="pdf-upload" data-type="pdf-upload">
597 <div class="mxchat-import-icon">
598 <span class="dashicons dashicons-upload"></span>
599 </div>
600 <div class="mxchat-import-content">
601 <h4><?php esc_html_e('PDF Upload', 'mxchat'); ?></h4>
602 <p><?php esc_html_e('Upload a PDF file from your computer.', 'mxchat'); ?></p>
603 </div>
604 </button>
605
606 <!-- Document File Upload Option (plan 0485e5) -->
607 <button type="button" class="mxchat-import-box" data-option="document-upload" data-type="document-upload">
608 <div class="mxchat-import-icon">
609 <span class="dashicons dashicons-media-text"></span>
610 </div>
611 <div class="mxchat-import-content">
612 <h4><?php esc_html_e('Document Upload', 'mxchat'); ?></h4>
613 <p><?php esc_html_e('Upload a Word document, text, or Markdown file (.docx, .txt, .md).', 'mxchat'); ?></p>
614 </div>
615 </button>
616
617 <!-- YouTube Video Import Option -->
618 <button type="button" class="mxchat-import-box" data-option="youtube" data-type="youtube">
619 <div class="mxchat-import-icon">
620 <span class="dashicons dashicons-youtube"></span>
621 </div>
622 <div class="mxchat-import-content">
623 <h4><?php esc_html_e('YouTube', 'mxchat'); ?></h4>
624 <p><?php esc_html_e('Index a video so the chat can surface it as a playable embed.', 'mxchat'); ?></p>
625 </div>
626 </button>
627 </div>
628
629 <!-- Detected Sitemaps Section (hidden by default, shown when Sitemap Import is clicked) -->
630 <div id="mxchat-detected-sitemaps" class="mxchat-detected-sitemaps" style="display: none;">
631 <div class="mxchat-sitemaps-header">
632 <h4>
633 <span class="dashicons dashicons-admin-site-alt"></span>
634 <?php esc_html_e('Detected Sitemaps', 'mxchat'); ?>
635 </h4>
636 <button type="button" id="mxchat-refresh-sitemaps" class="mxch-btn mxch-btn-ghost mxch-btn-sm" title="<?php esc_attr_e('Refresh', 'mxchat'); ?>">
637 <span class="dashicons dashicons-update"></span>
638 </button>
639 </div>
640 <div id="mxchat-sitemaps-list" class="mxchat-sitemaps-list">
641 <!-- Sitemaps will be loaded here via AJAX -->
642 </div>
643 <input type="hidden" id="mxchat-detect-sitemaps-nonce" value="<?php echo wp_create_nonce('mxchat_detect_sitemaps_nonce'); ?>">
644 <?php if ($multibot_active && $current_bot_id !== 'default') : ?>
645 <input type="hidden" id="mxchat-sitemap-bot-id" value="<?php echo esc_attr($current_bot_id); ?>">
646 <?php endif; ?>
647 </div>
648
649 <!-- No Sitemaps Found Message (hidden by default) -->
650 <div id="mxchat-no-sitemaps" class="mxchat-no-sitemaps" style="display: none;">
651 <span class="dashicons dashicons-info"></span>
652 <p>
653 <?php esc_html_e('No sitemaps detected. You can manually enter a sitemap URL using the input field above.', 'mxchat'); ?>
654 </p>
655 </div>
656
657 <!-- Sitemaps Loading State (hidden by default) -->
658 <div id="mxchat-sitemaps-loading" class="mxchat-sitemaps-loading" style="display: none;">
659 <span class="dashicons dashicons-update spin"></span>
660 <p><?php esc_html_e('Detecting sitemaps...', 'mxchat'); ?></p>
661 </div>
662
663 <!-- Input Areas for URL and Content -->
664 <?php if (!$is_processing) : ?>
665 <div class="mxchat-import-input-area" id="mxchat-url-input-area" style="display: none; margin-top: 20px;">
666 <form id="mxchat-url-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_sitemap')); ?>">
667 <?php wp_nonce_field('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce'); ?>
668 <input type="hidden" name="import_type" id="import_type" value="url">
669 <?php if ($multibot_active && $current_bot_id !== 'default') : ?>
670 <input type="hidden" name="bot_id" value="<?php echo esc_attr($current_bot_id); ?>">
671 <?php endif; ?>
672 <div style="display: flex; gap: 10px;">
673 <input type="url" name="sitemap_url" id="sitemap_url" class="mxch-input" placeholder="<?php esc_attr_e('Enter URL here', 'mxchat'); ?>" required style="flex: 1;" />
674 <button type="submit" name="submit_sitemap" class="mxch-btn mxch-btn-primary">
675 <?php esc_html_e('Import', 'mxchat'); ?>
676 </button>
677 </div>
678 <p class="mxch-field-description" id="url-description-text"></p>
679 </form>
680 </div>
681
682 <div class="mxchat-import-input-area" id="mxchat-content-input-area" style="display: none; margin-top: 20px;">
683 <form id="mxchat-content-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_content')); ?>">
684 <?php wp_nonce_field('mxchat_submit_content_action', 'mxchat_submit_content_nonce'); ?>
685 <?php if ($multibot_active && $current_bot_id !== 'default') : ?>
686 <input type="hidden" name="bot_id" value="<?php echo esc_attr($current_bot_id); ?>">
687 <?php endif; ?>
688 <div class="mxch-field">
689 <textarea name="article_content" id="article_content" class="mxch-textarea" placeholder="<?php esc_attr_e('Enter your content here...', 'mxchat'); ?>" required rows="6"></textarea>
690 </div>
691 <div class="mxch-field">
692 <input type="url" name="article_url" id="article_url" class="mxch-input" placeholder="<?php esc_attr_e('Enter source URL (Optional)', 'mxchat'); ?>">
693 <div style="margin-top: 8px; display: flex; align-items: center; gap: 8px;">
694 <label style="display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--mxch-text-secondary); cursor: pointer;">
695 <input type="checkbox" id="mxchat-unique-url-toggle" style="margin: 0;">
696 <?php esc_html_e('Generate unique URL for duplicate content', 'mxchat'); ?>
697 </label>
698 <button type="button" id="mxchat-generate-unique-url" class="mxch-btn mxch-btn-secondary mxch-btn-sm" style="display: none;">
699 <span class="dashicons dashicons-randomize" style="font-size: 14px; margin-top: 2px;"></span>
700 <?php esc_html_e('Generate Unique', 'mxchat'); ?>
701 </button>
702 </div>
703 <p class="mxch-field-description">
704 <?php esc_html_e('Enable this option to submit multiple entries with the same base URL. A unique reference will be appended.', 'mxchat'); ?>
705 </p>
706 </div>
707 <button type="submit" name="submit_content" class="mxch-btn mxch-btn-primary">
708 <?php esc_html_e('Import Content', 'mxchat'); ?>
709 </button>
710 </form>
711 </div>
712
713 <div class="mxchat-import-input-area" id="mxchat-pdf-upload-area" style="display: none; margin-top: 20px;">
714 <form id="mxchat-pdf-upload-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_pdf_file')); ?>" enctype="multipart/form-data">
715 <?php wp_nonce_field('mxchat_submit_pdf_file_action', 'mxchat_submit_pdf_file_nonce'); ?>
716 <?php if ($multibot_active && $current_bot_id !== 'default') : ?>
717 <input type="hidden" name="bot_id" value="<?php echo esc_attr($current_bot_id); ?>">
718 <?php endif; ?>
719 <div class="mxch-field">
720 <input type="file" name="pdf_file" id="mxchat-pdf-file-input" accept=".pdf" required>
721 </div>
722 <p class="mxch-field-description">
723 <?php esc_html_e('Select a PDF file from your computer to import into the knowledge base. Maximum file size depends on your server settings.', 'mxchat'); ?>
724 </p>
725 <div class="mxch-field">
726 <input type="url" name="source_page_url" id="mxchat-pdf-source-url" class="mxch-input" placeholder="<?php esc_attr_e('Enter source URL (Optional)', 'mxchat'); ?>">
727 <p class="mxch-field-description">
728 <?php esc_html_e('The page this PDF lives on. Answers drawn from it link to that page. Leave empty and answers name the file and page without a link.', 'mxchat'); ?>
729 </p>
730 </div>
731 <button type="submit" name="submit_pdf_file" class="mxch-btn mxch-btn-primary">
732 <?php esc_html_e('Import PDF', 'mxchat'); ?>
733 </button>
734 </form>
735 </div>
736
737 <div class="mxchat-import-input-area" id="mxchat-document-upload-area" style="display: none; margin-top: 20px;">
738 <form id="mxchat-document-upload-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_document_file')); ?>" enctype="multipart/form-data">
739 <?php wp_nonce_field('mxchat_submit_document_file_action', 'mxchat_submit_document_file_nonce'); ?>
740 <?php if ($multibot_active && $current_bot_id !== 'default') : ?>
741 <input type="hidden" name="bot_id" value="<?php echo esc_attr($current_bot_id); ?>">
742 <?php endif; ?>
743 <div class="mxch-field">
744 <input type="file" name="document_file" id="mxchat-document-file-input" accept=".docx,.txt,.md" required>
745 </div>
746 <p class="mxch-field-description">
747 <?php esc_html_e('Select a .docx, .txt, or .md file to import into the knowledge base. The text is extracted and indexed; the file itself is not stored. Re-uploading a file with the same name replaces its previous content.', 'mxchat'); ?>
748 </p>
749 <div class="mxch-field">
750 <input type="url" name="source_page_url" id="mxchat-document-source-url" class="mxch-input" placeholder="<?php esc_attr_e('Enter source URL (Optional)', 'mxchat'); ?>">
751 <p class="mxch-field-description">
752 <?php esc_html_e('The page this document lives on. Answers drawn from it link to that page. Leave empty and answers name the file without a link.', 'mxchat'); ?>
753 </p>
754 </div>
755 <button type="submit" name="submit_document_file" class="mxch-btn mxch-btn-primary">
756 <?php esc_html_e('Import Document', 'mxchat'); ?>
757 </button>
758 </form>
759 </div>
760
761 <?php
762 // Prefill state: set when an auto-import found no transcript — the
763 // handler bounced back here so the admin can augment the entry with
764 // a manual description (re-importing the same URL updates the row).
765 $yt_prefill = isset($_GET['mxchat_yt_prefill']) && $_GET['mxchat_yt_prefill'] === '1';
766 $yt_prefill_url = $yt_prefill && isset($_GET['yt_url']) ? esc_url_raw(rawurldecode(wp_unslash($_GET['yt_url']))) : '';
767 $yt_prefill_title = $yt_prefill && isset($_GET['yt_title']) ? sanitize_text_field(rawurldecode(wp_unslash($_GET['yt_title']))) : '';
768 ?>
769 <div class="mxchat-import-input-area" id="mxchat-youtube-input-area" style="display: none; margin-top: 20px;">
770 <form id="mxchat-youtube-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_youtube')); ?>"<?php echo $yt_prefill ? ' data-yt-prefill="1"' : ''; ?>>
771 <?php wp_nonce_field('mxchat_submit_youtube_action', 'mxchat_submit_youtube_nonce'); ?>
772 <?php if ($multibot_active && $current_bot_id !== 'default') : ?>
773 <input type="hidden" name="bot_id" value="<?php echo esc_attr($current_bot_id); ?>">
774 <?php endif; ?>
775 <div class="mxch-field">
776 <input type="url" name="youtube_url" id="mxchat-youtube-url" class="mxch-input" placeholder="<?php esc_attr_e('Paste a YouTube video URL (watch, youtu.be, or Shorts link)', 'mxchat'); ?>" required value="<?php echo esc_attr($yt_prefill_url); ?>">
777 </div>
778 <div class="mxch-field">
779 <span class="mxch-field-label"><?php esc_html_e('How should this video be described for matching?', 'mxchat'); ?></span>
780 <div style="display: flex; flex-direction: column; gap: 6px; margin-top: 8px;">
781 <label style="display: flex; align-items: baseline; gap: 8px; cursor: pointer;">
782 <input type="radio" name="youtube_description_mode" value="auto" <?php checked(!$yt_prefill); ?>>
783 <span>
784 <strong><?php esc_html_e('Auto-fetch', 'mxchat'); ?></strong>
785 <span class="mxch-field-description" style="display: block; margin: 2px 0 0;"><?php esc_html_e('We pull the video\'s title, channel, and captions (when available) to describe it.', 'mxchat'); ?></span>
786 </span>
787 </label>
788 <label style="display: flex; align-items: baseline; gap: 8px; cursor: pointer;">
789 <input type="radio" name="youtube_description_mode" value="manual" <?php checked($yt_prefill); ?>>
790 <span>
791 <strong><?php esc_html_e('Write my own', 'mxchat'); ?></strong>
792 <span class="mxch-field-description" style="display: block; margin: 2px 0 0;"><?php esc_html_e('You write the description the chatbot matches against — best for curated guides.', 'mxchat'); ?></span>
793 </span>
794 </label>
795 </div>
796 </div>
797 <div class="mxch-field" id="mxchat-youtube-description-field" style="<?php echo $yt_prefill ? '' : 'display: none;'; ?>">
798 <textarea name="youtube_description" id="mxchat-youtube-description" class="mxch-textarea" rows="5" placeholder="<?php esc_attr_e('Describe what this video covers and the questions it answers...', 'mxchat'); ?>"><?php echo esc_textarea($yt_prefill_title !== '' ? $yt_prefill_title . "\n\n" : ''); ?></textarea>
799 <p class="mxch-field-description"><?php esc_html_e('This text is what gets matched against visitor questions. Importing the same video URL again updates its existing entry.', 'mxchat'); ?></p>
800 </div>
801 <button type="submit" name="submit_youtube" value="1" class="mxch-btn mxch-btn-primary">
802 <?php esc_html_e('Import Video', 'mxchat'); ?>
803 </button>
804 </form>
805 </div>
806 <?php endif; ?>
807 </div>
808 </div>
809 </div>
810 <?php
811 }
812
813 /**
814 * Render Processing Status Cards (legacy - kept for reference)
815 * Note: Processing status is now rendered globally via mxchat_render_global_processing_status()
816 */
817 function mxchat_render_processing_status($page_data, $knowledge_manager) {
818 extract($page_data);
819
820 // PDF Processing Status
821 if ($pdf_status && $pdf_status['status'] === 'processing') : ?>
822 <div class="mxch-card" style="margin-top: 20px;">
823 <div class="mxch-card-header" style="background: var(--mxch-primary-light);">
824 <h3 class="mxch-card-title"><?php esc_html_e('PDF Processing Status', 'mxchat'); ?></h3>
825 <div style="display: flex; gap: 10px;">
826 <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_stop_processing')); ?>">
827 <?php wp_nonce_field('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce'); ?>
828 <button type="submit" name="stop_processing" class="mxch-btn mxch-btn-secondary mxch-btn-sm">
829 <?php esc_html_e('Stop Processing', 'mxchat'); ?>
830 </button>
831 </form>
832 <button type="button" class="mxch-btn mxch-btn-primary mxch-btn-sm mxchat-manual-batch-btn" data-process-type="pdf" data-url="<?php echo esc_attr(get_transient('mxchat_last_pdf_url')); ?>">
833 <?php esc_html_e('Process Batch', 'mxchat'); ?>
834 </button>
835 </div>
836 </div>
837 <div class="mxch-card-body">
838 <div class="mxchat-progress-bar" style="height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; margin-bottom: 15px;">
839 <div class="mxchat-progress-fill" style="height: 100%; background: var(--mxch-primary); width: <?php echo esc_attr($pdf_status['percentage']); ?>%; transition: width 0.3s;"></div>
840 </div>
841 <p><?php printf(esc_html__('Progress: %1$d of %2$d pages (%3$d%%)', 'mxchat'), absint($pdf_status['processed_pages']), absint($pdf_status['total_pages']), absint($pdf_status['percentage'])); ?></p>
842 <?php if (!empty($pdf_status['failed_pages']) && $pdf_status['failed_pages'] > 0) : ?>
843 <p><strong><?php esc_html_e('Failed pages:', 'mxchat'); ?></strong> <?php echo esc_html($pdf_status['failed_pages']); ?></p>
844 <?php endif; ?>
845 <p><strong><?php esc_html_e('Last update:', 'mxchat'); ?></strong> <?php echo esc_html($pdf_status['last_update']); ?></p>
846 </div>
847 </div>
848 <?php endif;
849
850 // Sitemap Processing Status
851 if ($sitemap_status && $sitemap_status['status'] === 'processing') : ?>
852 <div class="mxch-card" style="margin-top: 20px;">
853 <div class="mxch-card-header" style="background: var(--mxch-primary-light);">
854 <h3 class="mxch-card-title"><?php esc_html_e('Sitemap Processing Status', 'mxchat'); ?></h3>
855 <div style="display: flex; gap: 10px;">
856 <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_stop_processing')); ?>">
857 <?php wp_nonce_field('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce'); ?>
858 <button type="submit" name="stop_processing" class="mxch-btn mxch-btn-secondary mxch-btn-sm">
859 <?php esc_html_e('Stop Processing', 'mxchat'); ?>
860 </button>
861 </form>
862 <button type="button" class="mxch-btn mxch-btn-primary mxch-btn-sm mxchat-manual-batch-btn" data-process-type="sitemap" data-url="<?php echo esc_attr(get_transient('mxchat_last_sitemap_url')); ?>">
863 <?php esc_html_e('Process Batch', 'mxchat'); ?>
864 </button>
865 </div>
866 </div>
867 <div class="mxch-card-body">
868 <div class="mxchat-progress-bar" style="height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; margin-bottom: 15px;">
869 <div class="mxchat-progress-fill" style="height: 100%; background: var(--mxch-primary); width: <?php echo esc_attr($sitemap_status['percentage']); ?>%; transition: width 0.3s;"></div>
870 </div>
871 <p><?php printf(esc_html__('Progress: %1$d of %2$d URLs (%3$d%%)', 'mxchat'), absint($sitemap_status['processed_urls']), absint($sitemap_status['total_urls']), absint($sitemap_status['percentage'])); ?></p>
872 <?php if (!empty($sitemap_status['failed_urls']) && $sitemap_status['failed_urls'] > 0) : ?>
873 <p><strong><?php esc_html_e('Failed URLs:', 'mxchat'); ?></strong> <?php echo esc_html($sitemap_status['failed_urls']); ?></p>
874 <?php endif; ?>
875 <p><strong><?php esc_html_e('Last update:', 'mxchat'); ?></strong> <?php echo esc_html($sitemap_status['last_update']); ?></p>
876 </div>
877 </div>
878 <?php endif;
879
880 // Completed status cards
881 echo $knowledge_manager->mxchat_render_completed_status_cards();
882 }
883
884 /**
885 * Render Knowledge Base Section (table)
886 */
887 function mxchat_render_knowledge_base_section($admin_instance, $knowledge_manager, $page_data) {
888 extract($page_data);
889
890 // Group prompts by source_url for chunked content display
891 $grouped_prompts = array();
892
893 if ($prompts) {
894 foreach ($prompts as $prompt) {
895 $source_url = $prompt->source_url ?? '';
896
897 // Check if chunk metadata exists on the record itself (Pinecone)
898 if (isset($prompt->chunk_index) && $prompt->chunk_index !== null) {
899 // Pinecone: metadata is already on the record object
900 $prompt->chunk_metadata = array(
901 'chunk_index' => intval($prompt->chunk_index),
902 'total_chunks' => isset($prompt->total_chunks) ? intval($prompt->total_chunks) : null,
903 'is_chunked' => isset($prompt->is_chunked) ? (bool) $prompt->is_chunked : true
904 );
905 $prompt->display_content = $prompt->article_content; // Pinecone content is already clean
906 } else {
907 // WordPress: Parse chunk metadata from JSON prefix in article_content
908 if (class_exists('MxChat_Chunker')) {
909 $chunk_meta = MxChat_Chunker::parse_stored_chunk($prompt->article_content);
910 $prompt->chunk_metadata = $chunk_meta['metadata'];
911 $prompt->display_content = $chunk_meta['text']; // Store clean content without JSON prefix
912 } else {
913 $prompt->chunk_metadata = array();
914 $prompt->display_content = $prompt->article_content;
915 }
916 }
917
918 if (!empty($source_url)) {
919 if (!isset($grouped_prompts[$source_url])) {
920 $grouped_prompts[$source_url] = array();
921 }
922 $grouped_prompts[$source_url][] = $prompt;
923 } else {
924 // Use a unique key for ungrouped prompts
925 $grouped_prompts['_ungrouped_' . $prompt->id] = array($prompt);
926 }
927 }
928
929 // Sort each group by chunk_index from metadata
930 foreach ($grouped_prompts as $source_url => &$group) {
931 usort($group, function($a, $b) {
932 $index_a = isset($a->chunk_metadata['chunk_index']) ? intval($a->chunk_metadata['chunk_index']) : 0;
933 $index_b = isset($b->chunk_metadata['chunk_index']) ? intval($b->chunk_metadata['chunk_index']) : 0;
934 return $index_a - $index_b;
935 });
936 }
937 unset($group); // Break reference
938 }
939 $display_index = 0;
940 ?>
941 <div id="knowledge-base" class="mxch-section">
942 <div class="mxch-content-header">
943 <h1 class="mxch-content-title"><?php esc_html_e('Knowledge Base', 'mxchat'); ?></h1>
944 <p class="mxch-content-subtitle"><?php esc_html_e('View and manage your imported knowledge entries.', 'mxchat'); ?></p>
945 </div>
946
947 <?php if (!empty($use_vectorstore)) : ?>
948 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
949 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
950 <span><strong><?php esc_html_e('OpenAI Vector Store is Active', 'mxchat'); ?></strong> - <?php esc_html_e('Your chatbot is using OpenAI\'s hosted Vector Store for knowledge retrieval. The entries below are stored locally and are not being searched. To use this local database, disable Vector Store in the Integrations settings.', 'mxchat'); ?></span>
951 </div>
952 <?php endif; ?>
953
954 <div class="mxch-card">
955 <div class="mxch-card-header">
956 <h3 class="mxch-card-title">
957 <?php esc_html_e('Knowledge Entries', 'mxchat'); ?>
958 <?php $count_unit = $count_unit ?? ''; ?>
959 <span id="mxchat-entry-count" style="font-weight: normal; color: var(--mxch-text-secondary);" data-count="<?php echo esc_attr($total_records); ?>" data-unit="<?php echo esc_attr($count_unit); ?>"<?php if ($count_unit === 'vectors') : ?> title="<?php esc_attr_e('Pinecone reports vectors, not documents; a long entry is stored as several vectors.', 'mxchat'); ?>"<?php endif; ?>>(<?php echo esc_html(number_format_i18n($total_records)); ?><?php if ($count_unit === 'vectors') : ?> <?php esc_html_e('vectors', 'mxchat'); ?><?php endif; ?>)</span>
960 <?php if (!empty($use_vectorstore)) : ?>
961 <span style="display: inline-flex; align-items: center; gap: 4px; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 500; margin-left: 8px; background: #fff3e0; color: #e65100;">
962 <span class="dashicons dashicons-database" style="font-size: 14px;"></span>
963 <?php esc_html_e('Not in use', 'mxchat'); ?>
964 </span>
965 <?php elseif ($use_pinecone) : ?>
966 <span style="display: inline-flex; align-items: center; gap: 4px; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 500; margin-left: 8px; background: #e3f2fd; color: #1976d2;">
967 <span class="dashicons dashicons-cloud" style="font-size: 14px;"></span>
968 <?php esc_html_e('Pinecone', 'mxchat'); ?>
969 </span>
970 <?php else : ?>
971 <span style="display: inline-flex; align-items: center; gap: 4px; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 500; margin-left: 8px; background: #f3e5f5; color: #7b1fa2;">
972 <span class="dashicons dashicons-database-view" style="font-size: 14px;"></span>
973 <?php esc_html_e('WordPress DB', 'mxchat'); ?>
974 </span>
975 <?php endif; ?>
976 </h3>
977 <div class="mxch-kb-header-controls">
978 <form method="get" id="knowledge-search" class="mxch-kb-search-form">
979 <?php wp_nonce_field('mxchat_prompts_search_nonce'); ?>
980 <input type="hidden" name="page" value="mxchat-prompts" />
981 <?php if ($multibot_active && !empty($current_bot_id) && $current_bot_id !== 'default') : ?>
982 <input type="hidden" name="bot_id" value="<?php echo esc_attr($current_bot_id); ?>" />
983 <?php endif; ?>
984 <input type="text" name="search" class="mxch-input mxch-input-sm mxch-kb-search-input" placeholder="<?php esc_attr_e('Search...', 'mxchat'); ?>" value="<?php echo esc_attr($search_query); ?>" />
985 <select name="content_type" class="mxch-select mxch-kb-type-filter" onchange="this.form.submit()">
986 <option value=""><?php esc_html_e('All Types', 'mxchat'); ?></option>
987 <?php
988 $post_types = get_post_types(array('public' => true), 'objects');
989 foreach ($post_types as $post_type) {
990 echo '<option value="' . esc_attr($post_type->name) . '" ' . selected($content_type_filter, $post_type->name, false) . '>' . esc_html($post_type->label) . '</option>';
991 }
992 ?>
993 <option value="pdf" <?php selected($content_type_filter, 'pdf'); ?>><?php esc_html_e('PDFs', 'mxchat'); ?></option>
994 <option value="url" <?php selected($content_type_filter, 'url'); ?>><?php esc_html_e('URLs', 'mxchat'); ?></option>
995 </select>
996 </form>
997 <!-- Delete Button Container - transforms between Delete All and Delete Selected -->
998 <div class="mxchat-delete-container" id="mxchat-delete-container">
999 <!-- Delete All Form (shown when nothing selected) -->
1000 <?php
1001 // Build confirm message and button text based on active filter
1002 $delete_all_label = __('Delete All', 'mxchat');
1003 $delete_all_confirm = __('Are you sure you want to delete all knowledge?', 'mxchat');
1004 if (!empty($content_type_filter)) {
1005 $filter_display = $content_type_filter;
1006 // Try to get a human-readable label
1007 $pt_obj = get_post_type_object($content_type_filter);
1008 if ($pt_obj) {
1009 $filter_display = $pt_obj->label;
1010 } elseif ($content_type_filter === 'pdf') {
1011 $filter_display = 'PDFs';
1012 } elseif ($content_type_filter === 'url') {
1013 $filter_display = 'URLs';
1014 }
1015 /* translators: %s: content type label (e.g. "Pages", "PDFs") */
1016 $delete_all_label = sprintf(__('Delete All %s', 'mxchat'), $filter_display);
1017 /* translators: %s: content type label */
1018 $delete_all_confirm = sprintf(__('Are you sure you want to delete all %s from the knowledge base?', 'mxchat'), $filter_display);
1019 }
1020 ?>
1021 <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_delete_all_prompts')); ?>" id="mxchat-delete-all-form" onsubmit="return confirm('<?php echo esc_attr($delete_all_confirm); ?>');">
1022 <?php wp_nonce_field('mxchat_delete_all_prompts_action', 'mxchat_delete_all_prompts_nonce'); ?>
1023 <input type="hidden" name="data_source" value="<?php echo esc_attr($data_source); ?>" />
1024 <input type="hidden" name="bot_id" value="<?php echo esc_attr($current_bot_id); ?>" />
1025 <?php if (!empty($content_type_filter)) : ?>
1026 <input type="hidden" name="content_type_filter" value="<?php echo esc_attr($content_type_filter); ?>" />
1027 <?php endif; ?>
1028 <button type="submit" class="mxch-btn mxch-btn-secondary mxch-btn-sm" style="color: var(--mxch-error);">
1029 <span class="dashicons dashicons-trash" style="font-size: 14px;"></span>
1030 <?php echo esc_html($delete_all_label); ?>
1031 </button>
1032 </form>
1033 <!-- Delete Selected Button (shown when items selected) -->
1034 <button type="button"
1035 class="mxch-btn mxch-btn-secondary mxch-btn-sm mxchat-bulk-delete"
1036 id="mxchat-delete-selected-entries"
1037 style="display: none; color: var(--mxch-error);"
1038 data-nonce="<?php echo wp_create_nonce('mxchat_bulk_delete_knowledge_nonce'); ?>"
1039 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1040 data-data-source="<?php echo esc_attr($data_source); ?>">
1041 <span class="dashicons dashicons-trash" style="font-size: 14px;"></span>
1042 <span class="mxchat-bulk-delete-text"><?php esc_html_e('Delete Selected', 'mxchat'); ?></span>
1043 <span class="mxchat-selected-count" id="mxchat-selected-entry-count"></span>
1044 </button>
1045 </div>
1046 </div>
1047 </div>
1048 <div class="mxch-card-body" style="padding: 0;">
1049 <?php if ($use_pinecone) : ?>
1050 <div class="mxch-notice mxch-notice-info mxch-pinecone-notice" style="margin: 16px; border-radius: var(--mxch-radius-md); display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px;">
1051 <div style="display: flex; align-items: center; gap: 8px;">
1052 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1053 <span><?php esc_html_e('Changes may take up to 60 seconds to process in Pinecone. Click "Refresh Entries" to see updates.', 'mxchat'); ?></span>
1054 </div>
1055 <button type="button" id="mxchat-refresh-pinecone-entries" class="mxch-btn mxch-btn-secondary mxch-btn-sm">
1056 <span class="dashicons dashicons-update"></span>
1057 <?php esc_html_e('Refresh Entries', 'mxchat'); ?>
1058 </button>
1059 </div>
1060 <?php endif; ?>
1061
1062 <div class="mxchat-table-wrapper" style="overflow-x: auto;">
1063 <table class="mxchat-records-table" id="mxchat-records-table" style="width: 100%; border-collapse: collapse;">
1064 <thead>
1065 <tr style="background: #f8fafc; border-bottom: 1px solid var(--mxch-card-border);">
1066 <th style="padding: 12px 16px; width: 40px; text-align: center;">
1067 <input type="checkbox" id="mxchat-select-all-entries" class="mxchat-entry-checkbox-all" title="<?php esc_attr_e('Select All', 'mxchat'); ?>">
1068 </th>
1069 <th style="padding: 12px 16px; text-align: left; font-weight: 600; color: var(--mxch-text-secondary); font-size: 12px; text-transform: uppercase;"><?php esc_html_e('ID', 'mxchat'); ?></th>
1070 <th style="padding: 12px 16px; text-align: left; font-weight: 600; color: var(--mxch-text-secondary); font-size: 12px; text-transform: uppercase;"><?php esc_html_e('Content', 'mxchat'); ?></th>
1071 <th style="padding: 12px 16px; text-align: left; font-weight: 600; color: var(--mxch-text-secondary); font-size: 12px; text-transform: uppercase;"><?php esc_html_e('Source', 'mxchat'); ?></th>
1072 <th style="padding: 12px 16px; text-align: left; font-weight: 600; color: var(--mxch-text-secondary); font-size: 12px; text-transform: uppercase;"><?php esc_html_e('Actions', 'mxchat'); ?></th>
1073 </tr>
1074 </thead>
1075 <tbody id="mxchat-entries-tbody">
1076 <?php if (empty($grouped_prompts)) : ?>
1077 <tr>
1078 <td colspan="5" style="padding: 40px; text-align: center; color: var(--mxch-text-muted);">
1079 <?php esc_html_e('No knowledge entries found. Use the Import Options to add content.', 'mxchat'); ?>
1080 </td>
1081 </tr>
1082 <?php else : ?>
1083 <?php
1084 // Display grouped prompts
1085 foreach ($grouped_prompts as $source_url => $group) :
1086 $chunk_count = count($group);
1087 $first_prompt = $group[0];
1088 $display_index++;
1089
1090 if ($chunk_count > 1) :
1091 // Multiple chunks - show grouped row with expand button
1092 $group_id = 'group-' . md5($source_url);
1093 ?>
1094 <tr id="prompt-<?php echo esc_attr($first_prompt->id); ?>"
1095 class="mxchat-chunk-group-header"
1096 data-source="<?php echo esc_attr($data_source); ?>"
1097 data-group-id="<?php echo esc_attr($group_id); ?>"
1098 style="border-bottom: 1px solid var(--mxch-card-border); <?php if ($data_source === 'pinecone') echo 'background: rgba(33, 150, 243, 0.02);'; ?>">
1099 <td style="padding: 12px 16px; text-align: center;">
1100 <input type="checkbox"
1101 class="mxchat-entry-checkbox"
1102 data-entry-id="<?php echo esc_attr($first_prompt->id); ?>"
1103 data-source="<?php echo esc_attr($data_source); ?>"
1104 data-source-url="<?php echo esc_attr($source_url); ?>"
1105 data-is-group="true"
1106 data-chunk-count="<?php echo esc_attr($chunk_count); ?>">
1107 </td>
1108 <td style="padding: 12px 16px; font-size: 13px;">
1109 <?php if ($data_source === 'pinecone') : ?>
1110 <?php echo esc_html($display_index + (($current_page - 1) * $per_page)); ?>
1111 <?php else : ?>
1112 <?php echo esc_html($first_prompt->id); ?>
1113 <?php endif; ?>
1114 </td>
1115 <td class="mxchat-content-cell" style="padding: 12px 16px; font-size: 13px;">
1116 <div class="mxchat-chunk-group-info">
1117 <button type="button" class="mxchat-chunk-toggle" data-group-id="<?php echo esc_attr($group_id); ?>">
1118 <span class="dashicons dashicons-arrow-right-alt2"></span>
1119 </button>
1120 <span class="mxchat-chunk-badge"><?php echo esc_html($chunk_count); ?> <?php esc_html_e('chunks', 'mxchat'); ?></span>
1121 <span class="mxchat-chunk-preview">
1122 <?php
1123 $parent_content = isset($first_prompt->display_content) ? $first_prompt->display_content : $first_prompt->article_content;
1124 $content_preview = mb_substr($parent_content, 0, 100);
1125 echo esc_html($content_preview . '...');
1126 ?>
1127 </span>
1128 </div>
1129 </td>
1130 <td class="mxchat-url-cell" style="padding: 12px 16px; font-size: 13px;">
1131 <?php if (!empty($source_url) && strpos($source_url, 'mxchat://') !== 0 && strpos($source_url, '_ungrouped_') !== 0) : ?>
1132 <a href="<?php echo esc_url($source_url); ?>" target="_blank" style="color: var(--mxch-primary); text-decoration: none;">
1133 <span class="dashicons dashicons-external" style="font-size: 14px;"></span>
1134 <?php esc_html_e('View Source', 'mxchat'); ?>
1135 </a>
1136 <?php else : ?>
1137 <span style="color: var(--mxch-text-muted);"><?php esc_html_e('Manual Content', 'mxchat'); ?></span>
1138 <?php endif; ?>
1139 </td>
1140 <td class="mxchat-actions-cell" style="padding: 12px 16px; white-space: nowrap;">
1141 <button type="button"
1142 class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-inspect-entry-btn"
1143 data-source-url="<?php echo esc_attr($source_url); ?>"
1144 data-entry-id="<?php echo esc_attr($first_prompt->id); ?>"
1145 data-data-source="<?php echo esc_attr($data_source); ?>"
1146 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1147 data-nonce="<?php echo wp_create_nonce('mxchat_inspect_entry_nonce'); ?>"
1148 title="<?php esc_attr_e('View indexed content', 'mxchat'); ?>">
1149 <span class="dashicons dashicons-visibility" style="font-size: 14px;"></span>
1150 </button>
1151 <button type="button"
1152 class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-edit-entry-btn"
1153 data-source-url="<?php echo esc_attr($source_url); ?>"
1154 data-entry-id="<?php echo esc_attr($first_prompt->id); ?>"
1155 data-data-source="<?php echo esc_attr($data_source); ?>"
1156 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1157 data-nonce="<?php echo wp_create_nonce('mxchat_edit_entry_nonce'); ?>"
1158 title="<?php esc_attr_e('Edit content', 'mxchat'); ?>">
1159 <span class="dashicons dashicons-edit" style="font-size: 14px;"></span>
1160 </button>
1161 <button type="button"
1162 class="mxch-btn mxch-btn-ghost mxch-btn-sm delete-button-group"
1163 data-source-url="<?php echo esc_attr($source_url); ?>"
1164 data-chunk-count="<?php echo esc_attr($chunk_count); ?>"
1165 data-data-source="<?php echo esc_attr($data_source); ?>"
1166 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1167 data-nonce="<?php echo wp_create_nonce('mxchat_delete_chunks_nonce'); ?>"
1168 style="color: var(--mxch-error);"
1169 title="<?php esc_attr_e('Delete all chunks', 'mxchat'); ?>">
1170 <span class="dashicons dashicons-trash" style="font-size: 14px;"></span>
1171 </button>
1172 </td>
1173 </tr>
1174 <?php
1175 // Render hidden chunk rows
1176 foreach ($group as $chunk_index => $prompt) :
1177 $meta_chunk_index = isset($prompt->chunk_metadata['chunk_index']) ? intval($prompt->chunk_metadata['chunk_index']) : $chunk_index;
1178 $meta_total_chunks = isset($prompt->chunk_metadata['total_chunks']) ? intval($prompt->chunk_metadata['total_chunks']) : $chunk_count;
1179 $content = isset($prompt->display_content) ? $prompt->display_content : $prompt->article_content;
1180 $preview_length = 150;
1181 $content_preview = mb_strlen($content) > $preview_length
1182 ? mb_substr($content, 0, $preview_length) . '...'
1183 : $content;
1184 ?>
1185 <tr id="prompt-<?php echo esc_attr($prompt->id); ?>"
1186 class="mxchat-chunk-row <?php echo esc_attr($group_id); ?>"
1187 data-source="<?php echo esc_attr($data_source); ?>"
1188 style="display: none; background: #f8f9fa; border-bottom: 1px solid var(--mxch-card-border);">
1189 <td style="padding: 12px 16px; text-align: center;">
1190 <!-- Checkbox placeholder for chunk rows -->
1191 </td>
1192 <td style="padding: 12px 16px 12px 30px; font-size: 13px;">
1193 <!-- Hidden ID column for chunks -->
1194 </td>
1195 <td class="mxchat-content-cell" style="padding: 12px 16px; font-size: 13px;">
1196 <div class="mxchat-accordion-wrapper">
1197 <div class="mxchat-content-preview">
1198 <span class="mxchat-chunk-indicator" style="margin-right: 10px; color: var(--mxch-text-secondary); font-size: 12px;">
1199 <?php printf(esc_html__('Chunk %d of %d', 'mxchat'), $meta_chunk_index + 1, $meta_total_chunks); ?>
1200 </span>
1201 <span class="preview-text"><?php echo esc_html($content_preview); ?></span>
1202 <?php if (mb_strlen($content) > $preview_length) : ?>
1203 <button class="mxchat-expand-toggle" type="button">
1204 <span class="dashicons dashicons-arrow-down-alt2"></span>
1205 </button>
1206 <?php endif; ?>
1207 </div>
1208 <div class="mxchat-content-full" style="display: none;">
1209 <div class="content-view">
1210 <?php
1211 if (preg_match('/[\x{0590}-\x{05FF}]/u', $content)) {
1212 echo '<div dir="rtl" lang="he" class="rtl-content">';
1213 echo wp_kses_post(wpautop($content));
1214 echo '</div>';
1215 } else {
1216 echo wp_kses_post(wpautop($content));
1217 }
1218 ?>
1219 </div>
1220 </div>
1221 </div>
1222 </td>
1223 <td class="mxchat-url-cell" style="padding: 12px 16px; font-size: 13px;">
1224 <span class="mxchat-chunk-label" style="color: var(--mxch-text-muted);"><?php esc_html_e('Same as parent', 'mxchat'); ?></span>
1225 </td>
1226 <td class="mxchat-actions-cell" style="padding: 12px 16px;">
1227 <span class="mxchat-chunk-label" style="color: var(--mxch-text-muted);"><?php esc_html_e('Managed by group', 'mxchat'); ?></span>
1228 </td>
1229 </tr>
1230 <?php endforeach; ?>
1231 <?php else :
1232 // Single entry - display normally with accordion
1233 $prompt = $first_prompt;
1234 $content = isset($prompt->display_content) ? $prompt->display_content : $prompt->article_content;
1235 $preview_length = 150;
1236 $content_preview = mb_strlen($content) > $preview_length
1237 ? mb_substr($content, 0, $preview_length) . '...'
1238 : $content;
1239 ?>
1240 <tr id="prompt-<?php echo esc_attr($prompt->id); ?>"
1241 data-source="<?php echo esc_attr($data_source); ?>"
1242 style="border-bottom: 1px solid var(--mxch-card-border); <?php if ($data_source === 'pinecone') echo 'background: rgba(33, 150, 243, 0.02);'; ?>">
1243 <td style="padding: 12px 16px; text-align: center;">
1244 <input type="checkbox"
1245 class="mxchat-entry-checkbox"
1246 data-entry-id="<?php echo esc_attr($prompt->id); ?>"
1247 data-source="<?php echo esc_attr($data_source); ?>"
1248 data-source-url="<?php echo esc_attr($source_url); ?>"
1249 data-is-group="false">
1250 </td>
1251 <td style="padding: 12px 16px; font-size: 13px;">
1252 <?php if ($data_source === 'pinecone') : ?>
1253 <?php echo esc_html($display_index + (($current_page - 1) * $per_page)); ?>
1254 <?php else : ?>
1255 <?php echo esc_html($prompt->id); ?>
1256 <?php endif; ?>
1257 </td>
1258 <td class="mxchat-content-cell" style="padding: 12px 16px; font-size: 13px;">
1259 <div class="mxchat-accordion-wrapper">
1260 <div class="mxchat-content-preview">
1261 <span class="preview-text"><?php echo esc_html($content_preview); ?></span>
1262 <?php if (mb_strlen($content) > $preview_length) : ?>
1263 <button class="mxchat-expand-toggle" type="button">
1264 <span class="dashicons dashicons-arrow-down-alt2"></span>
1265 </button>
1266 <?php endif; ?>
1267 </div>
1268 <div class="mxchat-content-full" style="display: none;">
1269 <div class="content-view">
1270 <?php
1271 if (preg_match('/[\x{0590}-\x{05FF}]/u', $content)) {
1272 echo '<div dir="rtl" lang="he" class="rtl-content">';
1273 echo wp_kses_post(wpautop($content));
1274 echo '</div>';
1275 } else {
1276 echo wp_kses_post(wpautop($content));
1277 }
1278 ?>
1279 </div>
1280 </div>
1281 </div>
1282 </td>
1283 <td class="mxchat-url-cell" style="padding: 12px 16px; font-size: 13px;">
1284 <?php
1285 $actual_source = $source_url;
1286 if (strpos($source_url, '_ungrouped_') === 0) {
1287 $actual_source = $prompt->source_url ?? '';
1288 }
1289 if (!empty($actual_source) && strpos($actual_source, 'mxchat://') !== 0) : ?>
1290 <a href="<?php echo esc_url($actual_source); ?>" target="_blank" style="color: var(--mxch-primary); text-decoration: none;">
1291 <span class="dashicons dashicons-external" style="font-size: 14px;"></span>
1292 <?php esc_html_e('View', 'mxchat'); ?>
1293 </a>
1294 <?php else : ?>
1295 <span style="color: var(--mxch-text-muted);"><?php esc_html_e('Manual', 'mxchat'); ?></span>
1296 <?php endif; ?>
1297 </td>
1298 <td style="padding: 12px 16px; white-space: nowrap;">
1299 <button type="button"
1300 class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-inspect-entry-btn"
1301 data-source-url="<?php echo esc_attr($prompt->source_url ?? ''); ?>"
1302 data-entry-id="<?php echo esc_attr($prompt->id); ?>"
1303 data-data-source="<?php echo esc_attr($data_source); ?>"
1304 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1305 data-nonce="<?php echo wp_create_nonce('mxchat_inspect_entry_nonce'); ?>"
1306 title="<?php esc_attr_e('View indexed content', 'mxchat'); ?>">
1307 <span class="dashicons dashicons-visibility" style="font-size: 14px;"></span>
1308 </button>
1309 <button type="button"
1310 class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-edit-entry-btn"
1311 data-source-url="<?php echo esc_attr($prompt->source_url ?? ''); ?>"
1312 data-entry-id="<?php echo esc_attr($prompt->id); ?>"
1313 data-data-source="<?php echo esc_attr($data_source); ?>"
1314 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1315 data-nonce="<?php echo wp_create_nonce('mxchat_edit_entry_nonce'); ?>"
1316 title="<?php esc_attr_e('Edit content', 'mxchat'); ?>">
1317 <span class="dashicons dashicons-edit" style="font-size: 14px;"></span>
1318 </button>
1319 <?php if ($data_source === 'pinecone') : ?>
1320 <button type="button" class="mxch-btn mxch-btn-ghost mxch-btn-sm delete-button-ajax" data-vector-id="<?php echo esc_attr($prompt->id); ?>" data-bot-id="<?php echo esc_attr($current_bot_id); ?>" data-nonce="<?php echo wp_create_nonce('mxchat_delete_pinecone_prompt_nonce'); ?>" style="color: var(--mxch-error);">
1321 <span class="dashicons dashicons-trash" style="font-size: 14px;"></span>
1322 </button>
1323 <?php else : ?>
1324 <button type="button" class="mxch-btn mxch-btn-ghost mxch-btn-sm delete-button-wordpress" data-entry-id="<?php echo esc_attr($prompt->id); ?>" data-bot-id="<?php echo esc_attr($current_bot_id); ?>" data-nonce="<?php echo wp_create_nonce('mxchat_delete_wordpress_prompt_nonce'); ?>" style="color: var(--mxch-error);">
1325 <span class="dashicons dashicons-trash" style="font-size: 14px;"></span>
1326 </button>
1327 <?php endif; ?>
1328 </td>
1329 </tr>
1330 <?php endif; ?>
1331 <?php endforeach; ?>
1332 <?php endif; ?>
1333 </tbody>
1334 </table>
1335 </div>
1336
1337 <!-- Pagination wrapper - always present so JS can populate it after processing -->
1338 <?php
1339 // Plan dd6e10: Pinecone's list endpoint is a cursor — there is no
1340 // random access to page N, so over 500 vectors the screen offers
1341 // Previous / Next only. The same markup is built for AJAX page
1342 // loads by MxChat_Knowledge_Manager::mxchat_cursor_pagination_html().
1343 $cursor_pagination = !empty($cursor_pagination);
1344 $has_next = !empty($has_next);
1345 $show_pagination = $cursor_pagination ? ($current_page > 1 || $has_next) : ($total_pages > 1);
1346 ?>
1347 <div id="mxchat-kb-pagination" class="mxchat-kb-pagination-wrapper" style="<?php echo $show_pagination ? 'padding: 16px; border-top: 1px solid var(--mxch-card-border); text-align: center;' : ''; ?>" data-current-page="<?php echo esc_attr($current_page); ?>" data-total-pages="<?php echo esc_attr($total_pages); ?>" data-search="<?php echo esc_attr($search_query); ?>" data-content-type="<?php echo esc_attr($content_type_filter); ?>">
1348 <?php if ($cursor_pagination) : ?>
1349 <?php echo MxChat_Knowledge_Manager::mxchat_cursor_pagination_html($current_page, $has_next, $search_query, $content_type_filter); // phpcs:ignore WordPress.Security.EscapeOutput -- escaped inside ?>
1350 <?php elseif ($total_pages > 1) : ?>
1351 <div class="mxchat-ajax-pagination" data-current-page="<?php echo esc_attr($current_page); ?>" data-total-pages="<?php echo esc_attr($total_pages); ?>">
1352 <?php if ($current_page > 1) : ?>
1353 <a href="#" class="mxchat-page-link" data-page="<?php echo ($current_page - 1); ?>"><?php esc_html_e('&laquo; Previous', 'mxchat'); ?></a>
1354 <?php endif; ?>
1355
1356 <?php
1357 $start_page = max(1, $current_page - 2);
1358 $end_page = min($total_pages, $current_page + 2);
1359
1360 if ($start_page > 1) {
1361 echo '<a href="#" class="mxchat-page-link" data-page="1">1</a> ';
1362 if ($start_page > 2) {
1363 echo '<span class="mxchat-page-dots">...</span> ';
1364 }
1365 }
1366
1367 for ($i = $start_page; $i <= $end_page; $i++) {
1368 if ($i == $current_page) {
1369 echo '<span class="mxchat-page-current">' . $i . '</span> ';
1370 } else {
1371 echo '<a href="#" class="mxchat-page-link" data-page="' . $i . '">' . $i . '</a> ';
1372 }
1373 }
1374
1375 if ($end_page < $total_pages) {
1376 if ($end_page < $total_pages - 1) {
1377 echo '<span class="mxchat-page-dots">...</span> ';
1378 }
1379 echo '<a href="#" class="mxchat-page-link" data-page="' . $total_pages . '">' . $total_pages . '</a> ';
1380 }
1381 ?>
1382
1383 <?php if ($current_page < $total_pages) : ?>
1384 <a href="#" class="mxchat-page-link" data-page="<?php echo ($current_page + 1); ?>"><?php esc_html_e('Next &raquo;', 'mxchat'); ?></a>
1385 <?php endif; ?>
1386 </div>
1387 <?php endif; ?>
1388 </div>
1389 </div>
1390 </div>
1391
1392 <?php mxchat_render_kb_reimport_card(!empty($current_bot_id) ? $current_bot_id : 'default'); ?>
1393 </div>
1394 <?php
1395 }
1396
1397 /**
1398 * "Re-import affected entries" card (plan 89739b).
1399 *
1400 * The owner-facing side of wp mxchat kb-reimport: check first (no embedding
1401 * request, nothing written), read the list, then confirm. Both halves run in
1402 * resumable steps through the mxchat_kb_reimport AJAX action; the script is
1403 * js/knowledge-reimport.js. Everything dynamic is drawn there; this is the
1404 * resting markup.
1405 */
1406 function mxchat_render_kb_reimport_card($current_bot_id = 'default') {
1407 if (!class_exists('MxChat_Knowledge_Manager')) {
1408 return;
1409 }
1410 ?>
1411 <div class="mxch-card mxch-kb-reimport" id="mxchat-kb-reimport"
1412 data-nonce="<?php echo esc_attr(wp_create_nonce('mxchat_kb_reimport')); ?>"
1413 data-bot="<?php echo esc_attr($current_bot_id); ?>">
1414 <div class="mxch-card-header">
1415 <h3 class="mxch-card-title">
1416 <svg class="mxch-card-title-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
1417 <?php esc_html_e('Re-import affected entries', 'mxchat'); ?>
1418 </h3>
1419 </div>
1420 <div class="mxch-card-body">
1421 <p class="mxch-field-description"><?php esc_html_e('Earlier versions stored some imported text incorrectly: currency signs and accents were dropped, HTML character codes were left in, and right-to-left PDF text was saved backwards. This finds the entries that still hold that text and rebuilds them from their source. Checking changes nothing.', 'mxchat'); ?></p>
1422
1423 <div class="mxch-kb-reimport-controls">
1424 <div class="mxch-field">
1425 <label class="mxch-field-label" for="mxchat-kb-reimport-before"><?php esc_html_e('Entries last written before', 'mxchat'); ?></label>
1426 <input type="date" id="mxchat-kb-reimport-before" class="mxch-input mxch-input-sm" value="<?php echo esc_attr(MxChat_Knowledge_Manager::REIMPORT_DEFAULT_BEFORE); ?>" max="<?php echo esc_attr(gmdate('Y-m-d', time() + DAY_IN_SECONDS)); ?>" />
1427 </div>
1428 <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-kb-reimport-check"><?php esc_html_e('Check knowledge base', 'mxchat'); ?></button>
1429 </div>
1430 <p class="mxch-field-hint"><?php esc_html_e('The date is the release that carried the last of these fixes. Choose a later one if this site was updated after that.', 'mxchat'); ?></p>
1431
1432 <div class="mxch-kb-reimport-progress" hidden>
1433 <div class="mxch-progress-bar" hidden><div class="mxch-progress-bar-fill"></div></div>
1434 <p class="mxch-progress-label" aria-live="polite"></p>
1435 </div>
1436
1437 <div class="mxch-notice mxch-notice-error mxch-kb-reimport-error" role="alert" hidden>
1438 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
1439 <span></span>
1440 </div>
1441
1442 <div class="mxch-kb-reimport-results" hidden>
1443 <div class="mxch-notice mxch-notice-success mxch-kb-reimport-done" hidden>
1444 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
1445 <span></span>
1446 </div>
1447 <div class="mxch-kb-reimport-counts"></div>
1448 <ul class="mxch-kb-reimport-list mxch-kb-reimport-entries" hidden></ul>
1449 <p class="mxch-field-hint mxch-kb-reimport-more" hidden></p>
1450 <details class="mxch-disclosure mxch-kb-reimport-others" hidden>
1451 <summary class="mxch-disclosure-summary"><span class="mxch-disclosure-summary-text"></span><span class="mxch-disclosure-summary-hint"><?php esc_html_e('Never changed or removed by this tool', 'mxchat'); ?></span></summary>
1452 <div class="mxch-disclosure-body">
1453 <ul class="mxch-kb-reimport-list mxch-kb-reimport-notes"></ul>
1454 </div>
1455 </details>
1456 </div>
1457 </div>
1458 <div class="mxch-card-footer mxch-kb-reimport-footer" hidden>
1459 <button type="button" class="mxch-btn mxch-btn-primary" id="mxchat-kb-reimport-apply"></button>
1460 <button type="button" class="mxch-btn mxch-btn-ghost" id="mxchat-kb-reimport-clear"><?php esc_html_e('Clear', 'mxchat'); ?></button>
1461 <span class="mxch-field-hint mxch-kb-reimport-cost"><?php esc_html_e('Each rewritten entry is embedded again with your embedding provider.', 'mxchat'); ?></span>
1462 </div>
1463 </div>
1464 <?php
1465 }
1466
1467 /**
1468 * Render Auto-Sync Section
1469 */
1470 function mxchat_render_auto_sync_section($knowledge_manager) {
1471 ?>
1472 <div id="auto-sync" class="mxch-section">
1473 <div class="mxch-content-header">
1474 <h1 class="mxch-content-title"><?php esc_html_e('Auto-Sync Settings', 'mxchat'); ?></h1>
1475 <p class="mxch-content-subtitle"><?php esc_html_e('Automatically sync WordPress content to your knowledge base when published or updated.', 'mxchat'); ?></p>
1476 </div>
1477
1478 <div class="mxch-card">
1479 <div class="mxch-card-body mxchat-autosave-section">
1480 <div class="mxch-field">
1481 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">
1482 <label class="mxchat-toggle-switch">
1483 <input type="checkbox" name="mxchat_auto_sync_posts" class="mxchat-autosave-field" value="1" data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>" <?php checked(get_option('mxchat_auto_sync_posts', '0'), '1'); ?>>
1484 <span class="mxchat-toggle-slider"></span>
1485 </label>
1486 <span style="font-weight: 500;"><?php esc_html_e('Auto-sync Posts', 'mxchat'); ?></span>
1487 </div>
1488 <div style="display: flex; align-items: center; gap: 12px;">
1489 <label class="mxchat-toggle-switch">
1490 <input type="checkbox" name="mxchat_auto_sync_pages" class="mxchat-autosave-field" value="1" data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>" <?php checked(get_option('mxchat_auto_sync_pages', '0'), '1'); ?>>
1491 <span class="mxchat-toggle-slider"></span>
1492 </label>
1493 <span style="font-weight: 500;"><?php esc_html_e('Auto-sync Pages', 'mxchat'); ?></span>
1494 </div>
1495 </div>
1496
1497 <div class="mxch-field" style="margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--mxch-card-border);">
1498 <div style="display: flex; align-items: center; gap: 12px;">
1499 <label class="mxchat-toggle-switch">
1500 <input type="checkbox" name="mxchat_auto_sync_acf_pdfs" class="mxchat-autosave-field" value="1" data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>" <?php checked(get_option('mxchat_auto_sync_acf_pdfs', '0'), '1'); ?>>
1501 <span class="mxchat-toggle-slider"></span>
1502 </label>
1503 <span style="font-weight: 500;"><?php esc_html_e('Extract text from PDFs in ACF fields on save', 'mxchat'); ?></span>
1504 </div>
1505 <p class="mxch-field-description" style="margin-top: 8px;"><?php esc_html_e('When ON, editor saves re-extract every PDF referenced in ACF fields. Default OFF — saves stay fast and don\'t re-parse the same PDFs on every edit. The manual content selector has its own per-batch checkbox; this setting only controls the auto-sync path.', 'mxchat'); ?></p>
1506 </div>
1507
1508 <div style="margin-top: 24px;">
1509 <button id="mxchat-custom-post-types-toggle" class="mxch-btn mxch-btn-secondary">
1510 <?php esc_html_e('Advanced Custom Post Sync Settings', 'mxchat'); ?>
1511 <span style="margin-left: 5px;">▼</span>
1512 </button>
1513 <div id="mxchat-custom-post-types-container" style="display: none; margin-top: 16px; padding: 16px; background: #f8fafc; border-radius: var(--mxch-radius-md);">
1514 <h4 style="margin: 0 0 12px 0;"><?php esc_html_e('Sync Custom Post Types', 'mxchat'); ?></h4>
1515 <?php
1516 $post_types = $knowledge_manager->mxchat_get_public_post_types();
1517 unset($post_types['post'], $post_types['page']);
1518
1519 if (!empty($post_types)) {
1520 foreach ($post_types as $post_type => $label) {
1521 $option_name = 'mxchat_auto_sync_' . $post_type;
1522 $is_enabled = get_option($option_name, '0');
1523 ?>
1524 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
1525 <label class="mxchat-toggle-switch">
1526 <input type="checkbox" name="<?php echo esc_attr($option_name); ?>" class="mxchat-autosave-field" value="1" data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>" <?php checked($is_enabled, '1'); ?>>
1527 <span class="mxchat-toggle-slider"></span>
1528 </label>
1529 <span><?php echo esc_html($label); ?> (<?php echo esc_html($post_type); ?>)</span>
1530 </div>
1531 <?php
1532 }
1533 } else {
1534 echo '<p style="color: var(--mxch-text-muted);">' . esc_html__('No custom post types found.', 'mxchat') . '</p>';
1535 }
1536 ?>
1537 </div>
1538 </div>
1539 </div>
1540 </div>
1541 </div>
1542 <?php
1543 }
1544
1545 /**
1546 * Render Chunking Section
1547 */
1548 function mxchat_render_chunking_section() {
1549 $chunking_settings = MxChat_Chunker::get_settings();
1550 $chunking_enabled = $chunking_settings['chunking_enabled'];
1551 $chunk_size = $chunking_settings['chunk_size'];
1552 ?>
1553 <div id="chunking" class="mxch-section">
1554 <div class="mxch-content-header">
1555 <h1 class="mxch-content-title"><?php esc_html_e('Chunking & Retrieval', 'mxchat'); ?></h1>
1556 <p class="mxch-content-subtitle"><?php esc_html_e('Control how content is split for indexing and how the knowledge base is searched.', 'mxchat'); ?></p>
1557 </div>
1558
1559 <div class="mxch-card">
1560 <div class="mxch-card-header">
1561 <h2 class="mxch-card-title"><?php esc_html_e('Chunking', 'mxchat'); ?></h2>
1562 </div>
1563 <div class="mxch-card-body mxchat-autosave-section">
1564 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1565 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1566 <span><?php esc_html_e('Chunking improves retrieval quality for long documents. All chunks are reassembled before sending to the AI. Only applies to new submissions.', 'mxchat'); ?></span>
1567 </div>
1568
1569 <div class="mxch-field">
1570 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">
1571 <label class="mxchat-toggle-switch">
1572 <input type="checkbox" name="mxchat_chunking_enabled" id="mxchat_chunking_enabled" class="mxchat-autosave-field" value="1" data-option-name="mxchat_chunking_enabled" data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>" <?php checked($chunking_enabled, true); ?>>
1573 <span class="mxchat-toggle-slider"></span>
1574 </label>
1575 <span style="font-weight: 500;"><?php esc_html_e('Enable Content Chunking', 'mxchat'); ?></span>
1576 </div>
1577 </div>
1578
1579 <div class="mxch-field">
1580 <label class="mxch-field-label" for="mxchat_chunk_size"><?php esc_html_e('Chunk Size (characters)', 'mxchat'); ?></label>
1581 <input type="number" name="mxchat_chunk_size" id="mxchat_chunk_size" class="mxch-input mxchat-autosave-field" value="<?php echo esc_attr($chunk_size); ?>" min="1000" max="10000" step="500" data-option-name="mxchat_chunk_size" data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>" style="max-width: 200px;">
1582 <p class="mxch-field-description"><?php esc_html_e('Recommended: 4000 characters (~1000 tokens). Range: 1000-10000. Larger chunks preserve more context.', 'mxchat'); ?></p>
1583 </div>
1584 </div>
1585 </div>
1586
1587 <?php
1588 // Retrieval tuning (plan 11720c) — the hybrid keyword boost moved here
1589 // from Settings → Behavior: it is KB retrieval tuning, so it lives with
1590 // its natural siblings. SAME option key and save transport as before —
1591 // the name routes to the mxchat_save_setting handler, whose
1592 // mxchat_hybrid_keyword_toggle case still runs capability detection.
1593 ?>
1594 <div class="mxch-card">
1595 <div class="mxch-card-header">
1596 <h2 class="mxch-card-title"><?php esc_html_e('Retrieval', 'mxchat'); ?></h2>
1597 </div>
1598 <div class="mxch-card-body mxchat-autosave-section">
1599 <div class="mxch-field">
1600 <div style="display: flex; align-items: center; gap: 12px;">
1601 <label class="mxchat-toggle-switch">
1602 <input type="checkbox" name="mxchat_hybrid_keyword_toggle" id="mxchat_hybrid_keyword_toggle" class="mxchat-autosave-field" value="on" <?php checked(get_option('mxchat_hybrid_keyword_toggle', 'off'), 'on'); ?>>
1603 <span class="mxchat-toggle-slider"></span>
1604 </label>
1605 <span style="font-weight: 500;"><?php esc_html_e('Hybrid keyword boost (WordPress database and Pinecone document indexes)', 'mxchat'); ?></span>
1606 </div>
1607 <p class="mxch-field-description" style="margin-top: 8px;"><?php esc_html_e('Combines keyword matching with vector similarity when searching your WordPress-database knowledge base or a Pinecone document index. Helps exact-token questions — product codes, SKUs, error codes, names — find the right document even when semantic similarity alone would miss it.', 'mxchat'); ?></p>
1608 <p class="mxch-field-hint"><?php esc_html_e('Applies to the WordPress-database knowledge base and to Pinecone when the index type is Document index with full-text search; a classic Pinecone vector index is unaffected. Changes which sources are retrieved on existing installs, so test after enabling. The Transcripts sources panel labels how each match was found while this is on.', 'mxchat'); ?></p>
1609 </div>
1610 </div>
1611 </div>
1612
1613 <?php
1614 // Video cards (plan f52492). Lives on the Knowledge screen because that
1615 // is where the owner imported the video in the first place, and beside
1616 // Retrieval because it is a retrieval-confidence question. Standalone
1617 // options — see the mxchat_video_embed_* cases in class-ajax-handler.php.
1618 $video_embed_enabled = MxChat_Utils::video_embed_enabled();
1619 $video_embed_threshold = (int) round(MxChat_Utils::video_embed_threshold() * 100);
1620 $mxchat_core_options = get_option('mxchat_options', array());
1621 $site_threshold = isset($mxchat_core_options['similarity_threshold'])
1622 ? (int) $mxchat_core_options['similarity_threshold']
1623 : 35;
1624 ?>
1625 <div class="mxch-card">
1626 <div class="mxch-card-header">
1627 <h2 class="mxch-card-title"><?php esc_html_e('Video Cards', 'mxchat'); ?></h2>
1628 </div>
1629 <div class="mxch-card-body mxchat-autosave-section">
1630 <div class="mxch-field" style="margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid var(--mxch-card-border);">
1631 <div style="display: flex; align-items: center; gap: 12px;">
1632 <label class="mxchat-toggle-switch">
1633 <input type="checkbox" name="mxchat_video_embed_enabled" id="mxchat_video_embed_enabled" class="mxchat-autosave-field" value="on" <?php checked($video_embed_enabled, true); ?>>
1634 <span class="mxchat-toggle-slider"></span>
1635 </label>
1636 <span style="font-weight: 500;"><?php esc_html_e('Show a video card when a YouTube source answers the question', 'mxchat'); ?></span>
1637 </div>
1638 <p class="mxch-field-description" style="margin-top: 8px;"><?php esc_html_e('Adds a click-to-play card beneath the reply when the answer came from a YouTube video you imported. Turn this off to stop video cards entirely without removing the videos from your knowledge base.', 'mxchat'); ?></p>
1639 </div>
1640
1641 <div class="mxch-field" id="mxchat-video-embed-threshold-field" style="<?php echo $video_embed_enabled ? '' : 'display: none;'; ?>">
1642 <label class="mxch-field-label" for="mxchat_video_embed_threshold"><?php esc_html_e('Video Card Match Threshold (%)', 'mxchat'); ?></label>
1643 <?php // Slider matching the site-wide Similarity Threshold exactly
1644 // (plan 7afd54): same .slider-container / .range-slider /
1645 // .range-value markup; the shared admin JS live-updates the
1646 // <id>_value span on input and autosaves on change (once per
1647 // drag release, so no request storm). Range/default/clamp
1648 // unchanged — presentation only. ?>
1649 <div class="slider-container">
1650 <input type="range" name="mxchat_video_embed_threshold" id="mxchat_video_embed_threshold" class="range-slider mxchat-autosave-field" value="<?php echo esc_attr($video_embed_threshold); ?>" min="20" max="95" step="1">
1651 <span id="mxchat_video_embed_threshold_value" class="range-value"><?php echo esc_html((int) $video_embed_threshold); ?></span>
1652 </div>
1653 <p class="mxch-field-description"><?php
1654 /* translators: %d is the site-wide Similarity Threshold percentage. */
1655 printf(esc_html__('How closely the video must match the question before its card is shown. Higher means fewer, more relevant cards. This is separate from the site-wide Similarity Threshold (currently %d%%), which decides what the AI reads — a video is worth reading from at a lower score than it is worth putting on screen.', 'mxchat'), (int) $site_threshold);
1656 ?></p>
1657 <p class="mxch-field-hint"><?php esc_html_e('Range 20-95. Raise this if visitors are shown videos unrelated to what they asked; lower it if a video that clearly answers the question is not appearing. The right number depends on your embedding model: older models such as text-embedding-ada-002 score even unrelated content around 70%, so those sites usually need 80 or higher before this has any effect. The Transcripts sources panel shows the match percentage of each source, which is the number to compare against.', 'mxchat'); ?></p>
1658 </div>
1659 </div>
1660 </div>
1661 </div>
1662 <?php
1663 }
1664
1665 /**
1666 * Render Role Restrictions Section
1667 */
1668 function mxchat_render_role_restrictions_section($knowledge_manager) {
1669 // Same source as the per-entry dropdown, so the two selectors cannot drift
1670 // and both offer the site's custom roles (plan 6ab002). This screen used to
1671 // hold its own hardcoded copy of the five built-ins.
1672 $role_options = (is_object($knowledge_manager) && method_exists($knowledge_manager, 'mxchat_get_role_options'))
1673 ? $knowledge_manager->mxchat_get_role_options()
1674 : array(
1675 'public' => __('Public (Everyone)', 'mxchat'),
1676 'logged_in' => __('Logged In Users', 'mxchat'),
1677 );
1678 ?>
1679 <div id="role-restrictions" class="mxch-section">
1680 <div class="mxch-content-header">
1681 <h1 class="mxch-content-title"><?php esc_html_e('Role-Based Content Restrictions', 'mxchat'); ?></h1>
1682 <p class="mxch-content-subtitle"><?php esc_html_e('Automatically restrict tagged posts by role. Pages and untagged content are restricted per entry in the Knowledge list.', 'mxchat'); ?></p>
1683 </div>
1684
1685 <div class="mxch-card">
1686 <div class="mxch-card-body">
1687 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1688 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1689 <span><strong><?php esc_html_e('How it works:', 'mxchat'); ?></strong> <?php esc_html_e('Add a tag below and select which role should have access. Content with that tag will be restricted to that role level. Tags apply to posts — pages and other content have no tags, so restrict those from the role dropdown on the entry itself in the Knowledge list. Any role on this site can be chosen, including custom ones.', 'mxchat'); ?></span>
1690 </div>
1691
1692 <h4 style="margin: 0 0 16px 0;"><?php esc_html_e('Add Tag-Role Mapping', 'mxchat'); ?></h4>
1693 <div style="display: flex; gap: 15px; align-items: flex-end; flex-wrap: wrap; margin-bottom: 24px;">
1694 <div class="mxch-field" style="flex: 1; min-width: 200px; margin-bottom: 0;">
1695 <label class="mxch-field-label" for="mxchat-tag-input"><?php esc_html_e('Tag (name or slug)', 'mxchat'); ?></label>
1696 <input type="text" id="mxchat-tag-input" class="mxch-input" placeholder="<?php esc_attr_e('e.g., Premium Content or premium-content', 'mxchat'); ?>">
1697 <span class="mxch-field-hint"><?php esc_html_e('Enter an existing post tag by its display name or its slug.', 'mxchat'); ?></span>
1698 </div>
1699 <div class="mxch-field" style="flex: 1; min-width: 200px; margin-bottom: 0;">
1700 <label class="mxch-field-label" for="mxchat-role-select"><?php esc_html_e('Required Role', 'mxchat'); ?></label>
1701 <select id="mxchat-role-select" class="mxch-select">
1702 <?php foreach ($role_options as $role_key => $role_label) : ?>
1703 <option value="<?php echo esc_attr($role_key); ?>"><?php echo esc_html($role_label); ?></option>
1704 <?php endforeach; ?>
1705 </select>
1706 </div>
1707 <button type="button" id="mxchat-add-tag-role" class="mxch-btn mxch-btn-primary">
1708 <span class="dashicons dashicons-plus-alt" style="font-size: 16px;"></span>
1709 <?php esc_html_e('Add Mapping', 'mxchat'); ?>
1710 </button>
1711 </div>
1712
1713 <h4 style="margin: 24px 0 16px 0;"><?php esc_html_e('Current Tag-Role Mappings', 'mxchat'); ?></h4>
1714 <div id="mxchat-mappings-container">
1715 <div class="mxchat-loading-mappings" style="text-align: center; padding: 20px; color: var(--mxch-text-muted);">
1716 <?php esc_html_e('Loading mappings...', 'mxchat'); ?>
1717 </div>
1718 </div>
1719 <div id="mxchat-no-mappings" style="display: none; text-align: center; padding: 40px; color: var(--mxch-text-muted);">
1720 <span class="dashicons dashicons-tag" style="font-size: 48px; opacity: 0.3;"></span>
1721 <p><?php esc_html_e('No tag-role mappings yet. Add your first mapping above.', 'mxchat'); ?></p>
1722 </div>
1723
1724 <div style="margin-top: 30px; padding-top: 24px; border-top: 1px solid var(--mxch-card-border);">
1725 <h4 style="margin: 0 0 12px 0;"><?php esc_html_e('Bulk Update Existing Content', 'mxchat'); ?></h4>
1726 <p class="mxch-field-description" style="margin-bottom: 16px;"><?php esc_html_e('Apply role restrictions to all existing content that has the mapped tags.', 'mxchat'); ?></p>
1727 <button type="button" id="mxchat-bulk-update-roles" class="mxch-btn mxch-btn-secondary">
1728 <span class="dashicons dashicons-update" style="font-size: 16px;"></span>
1729 <?php esc_html_e('Update All Existing Content', 'mxchat'); ?>
1730 </button>
1731 <div id="mxchat-bulk-update-progress" style="display: none; margin-top: 15px;">
1732 <div style="height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden;">
1733 <div class="mxchat-progress-fill" style="height: 100%; background: var(--mxch-primary); width: 0%; transition: width 0.3s;"></div>
1734 </div>
1735 <p class="mxchat-progress-text" style="margin-top: 10px; color: var(--mxch-text-secondary);"><?php esc_html_e('Processing...', 'mxchat'); ?></p>
1736 </div>
1737 <div id="mxchat-bulk-update-result" style="display: none; margin-top: 15px;"></div>
1738 </div>
1739 </div>
1740 </div>
1741 </div>
1742 <?php
1743 }
1744
1745 /**
1746 * Render ACF Fields Section
1747 */
1748 function mxchat_render_acf_fields_section($knowledge_manager) {
1749 $excluded_fields = get_option('mxchat_acf_excluded_fields', array());
1750 if (!is_array($excluded_fields)) {
1751 $excluded_fields = array();
1752 }
1753 ?>
1754 <div id="acf-fields" class="mxch-section">
1755 <div class="mxch-content-header">
1756 <h1 class="mxch-content-title"><?php esc_html_e('ACF Field Settings', 'mxchat'); ?></h1>
1757 <p class="mxch-content-subtitle"><?php esc_html_e('Control which Advanced Custom Fields are included in knowledge base embeddings.', 'mxchat'); ?></p>
1758 </div>
1759
1760 <div class="mxch-card">
1761 <div class="mxch-card-body mxchat-autosave-section">
1762 <?php
1763 // Install-level ACF→PDF import extraction (plan 11720c) — moved
1764 // here from a per-import checkbox in the content-selector modal.
1765 // Default OFF, matching its own "recommended only if…" guidance.
1766 ?>
1767 <div class="mxch-field" style="margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid var(--mxch-card-border);">
1768 <div style="display: flex; align-items: center; gap: 12px;">
1769 <label class="mxchat-toggle-switch">
1770 <input type="checkbox" name="mxchat_acf_pdf_extraction" id="mxchat_acf_pdf_extraction" class="mxchat-autosave-field" value="on" <?php checked(get_option('mxchat_acf_pdf_extraction', '0'), '1'); ?>>
1771 <span class="mxchat-toggle-slider"></span>
1772 </label>
1773 <span style="font-weight: 500;"><?php esc_html_e('Extract text from PDFs linked in ACF File/Image fields during imports', 'mxchat'); ?></span>
1774 </div>
1775 <p class="mxch-field-description" style="margin-top: 8px;"><?php esc_html_e('Applies to WordPress Content imports. Adds 200-500ms per post and ~30 KB to each knowledge base entry. Recommended only if your ACF setup uses PDF attachments for primary content. Editor-save extraction has its own toggle under Auto-Sync.', 'mxchat'); ?></p>
1776 </div>
1777 <?php if (!function_exists('acf_get_field_groups')): ?>
1778 <div class="mxch-notice mxch-notice-info">
1779 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1780 <span><?php esc_html_e('Advanced Custom Fields (ACF) plugin is not detected. Install and activate ACF to use this feature.', 'mxchat'); ?></span>
1781 </div>
1782 <?php else:
1783 $all_acf_fields = $knowledge_manager->mxchat_get_all_acf_fields();
1784
1785 if (empty($all_acf_fields)): ?>
1786 <div class="mxch-notice mxch-notice-info">
1787 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1788 <span><?php esc_html_e('No ACF field groups found. Create field groups in ACF to control which fields are included in embeddings.', 'mxchat'); ?></span>
1789 </div>
1790 <?php else: ?>
1791 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1792 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1793 <span><?php esc_html_e('Toggle fields ON to include them in knowledge base embeddings. Toggle OFF to exclude sensitive or irrelevant fields. Exclusions apply everywhere a field appears — ACF location rules (post types, templates) do not scope this list.', 'mxchat'); ?></span>
1794 </div>
1795
1796 <?php foreach ($all_acf_fields as $group_key => $group):
1797 $fields = $group['fields'];
1798 // Group toggle state derives from the per-field state —
1799 // never stored on its own (plan bf57e0).
1800 $excluded_count = 0;
1801 foreach ($fields as $field) {
1802 if (in_array($field['key'], $excluded_fields, true) || in_array($field['name'], $excluded_fields, true)) {
1803 $excluded_count++;
1804 }
1805 }
1806 $group_all_included = ($excluded_count === 0);
1807 $group_partial = ($excluded_count > 0 && $excluded_count < count($fields));
1808 ?>
1809 <div class="mxchat-acf-field-group" style="margin-bottom: 24px;" data-mxchat-acf-group="<?php echo esc_attr($group_key); ?>">
1810 <div style="display: flex; align-items: center; justify-content: space-between; margin: 0 0 12px 0;">
1811 <h4 style="margin: 0; color: var(--mxch-text-primary); font-weight: 600;">
1812 <?php echo esc_html($group['title']); ?>
1813 </h4>
1814 <label class="mxchat-toggle-switch" title="<?php esc_attr_e('Include or exclude every field in this group', 'mxchat'); ?>">
1815 <input type="checkbox"
1816 class="mxchat-acf-group-toggle"
1817 data-group-key="<?php echo esc_attr($group_key); ?>"
1818 data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>"
1819 <?php if ($group_partial): ?>data-indeterminate="1"<?php endif; ?>
1820 <?php checked($group_all_included, true); ?>>
1821 <span class="mxchat-toggle-slider"></span>
1822 </label>
1823 </div>
1824 <div style="background: #f8fafc; border-radius: var(--mxch-radius-md); padding: 16px;">
1825 <?php foreach ($fields as $field):
1826 // Toggles identify fields by ACF field KEY — names are shared
1827 // across groups and collide (plan 30e81f). Legacy name entries
1828 // (group inactive at migration time) still count as excluded.
1829 $is_enabled = !in_array($field['key'], $excluded_fields, true) && !in_array($field['name'], $excluded_fields, true);
1830 ?>
1831 <div style="display: flex; align-items: center; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #e2e8f0;">
1832 <div>
1833 <span style="font-weight: 500;"><?php echo esc_html($field['label']); ?></span>
1834 <span style="color: var(--mxch-text-muted); font-size: 12px; margin-left: 8px;">(<?php echo esc_html($field['name']); ?>)</span>
1835 <span style="color: var(--mxch-text-muted); font-size: 11px; margin-left: 8px; background: #e2e8f0; padding: 2px 6px; border-radius: 4px;"><?php echo esc_html($field['type']); ?></span>
1836 </div>
1837 <label class="mxchat-toggle-switch">
1838 <input type="checkbox"
1839 name="mxchat_acf_field_<?php echo esc_attr($field['key']); ?>"
1840 class="mxchat-autosave-field"
1841 value="on"
1842 data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>"
1843 <?php checked($is_enabled, true); ?>>
1844 <span class="mxchat-toggle-slider"></span>
1845 </label>
1846 </div>
1847 <?php endforeach; ?>
1848 </div>
1849 </div>
1850 <?php endforeach; ?>
1851 <?php endif; ?>
1852 <?php endif; ?>
1853 </div>
1854 </div>
1855 </div>
1856 <?php
1857 }
1858
1859 /**
1860 * Render Custom Meta Section
1861 */
1862 function mxchat_render_custom_meta_section() {
1863 $whitelist = get_option('mxchat_custom_meta_whitelist', '');
1864 ?>
1865 <div id="custom-meta" class="mxch-section">
1866 <div class="mxch-content-header">
1867 <h1 class="mxch-content-title"><?php esc_html_e('Custom Post Meta', 'mxchat'); ?></h1>
1868 <p class="mxch-content-subtitle"><?php esc_html_e('Include custom post meta fields (non-ACF) in knowledge base embeddings.', 'mxchat'); ?></p>
1869 </div>
1870
1871 <div class="mxch-card">
1872 <div class="mxch-card-body mxchat-autosave-section">
1873 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1874 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1875 <span><?php esc_html_e('Enter post meta keys to include in embeddings. This is useful for OptionTree fields, theme meta boxes, or any custom post meta that is not managed by ACF.', 'mxchat'); ?></span>
1876 </div>
1877
1878 <!-- Meta-key discovery scanner (plan-mxchat-20260709-fe8e4e): mirror the ACF picker's
1879 discover-for-you UX for non-ACF meta, so owners click keys instead of typing them blind. -->
1880 <div class="mxch-field mxchat-meta-scan">
1881 <label class="mxch-field-label"><?php esc_html_e('Discover meta keys', 'mxchat'); ?></label>
1882 <p class="mxch-field-description" style="margin-top: 0;">
1883 <?php esc_html_e('Scan your published content for custom meta keys, then click any you want to include. This gives non-ACF meta the same discover-and-click experience as the ACF picker.', 'mxchat'); ?>
1884 </p>
1885 <div class="mxchat-meta-scan-controls">
1886 <button type="button" id="mxchat-scan-meta-btn" class="mxch-btn mxch-btn-secondary" data-nonce="<?php echo esc_attr(wp_create_nonce('mxchat_prompts_setting_nonce')); ?>">
1887 <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
1888 <span class="mxchat-scan-label"><?php esc_html_e('Scan my content for meta keys', 'mxchat'); ?></span>
1889 </button>
1890 <label class="mxchat-meta-scan-internal">
1891 <input type="checkbox" id="mxchat-scan-internal">
1892 <?php esc_html_e('Include internal keys (underscore-prefixed)', 'mxchat'); ?>
1893 </label>
1894 </div>
1895 <div id="mxchat-meta-scan-results" class="mxchat-meta-scan-results" aria-live="polite"></div>
1896 </div>
1897
1898 <div class="mxch-field">
1899 <label class="mxch-field-label" for="mxchat_custom_meta_whitelist">
1900 <?php esc_html_e('Meta Key Whitelist', 'mxchat'); ?>
1901 </label>
1902 <textarea
1903 name="mxchat_custom_meta_whitelist"
1904 id="mxchat_custom_meta_whitelist"
1905 class="mxch-textarea mxchat-autosave-field"
1906 rows="6"
1907 placeholder="speaker_profession&#10;speaker_company&#10;event_location&#10;_custom_field_key"
1908 data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>"
1909 style="font-family: monospace;"
1910 ><?php echo esc_textarea($whitelist); ?></textarea>
1911 <p class="mxch-field-description">
1912 <?php esc_html_e('Enter one meta key per line. These fields will be appended to the content during embedding. Text values are added as-is; array or repeater values are flattened into a comma-separated list. Empty values are skipped.', 'mxchat'); ?>
1913 </p>
1914 </div>
1915
1916 <div style="margin-top: 20px; padding: 16px; background: #f8fafc; border-radius: var(--mxch-radius-md);">
1917 <h4 style="margin: 0 0 12px 0; font-size: 14px;"><?php esc_html_e('How to find meta keys:', 'mxchat'); ?></h4>
1918 <ul style="margin: 0; padding-left: 20px; color: var(--mxch-text-secondary); font-size: 13px;">
1919 <li><?php esc_html_e('Check your theme documentation for meta key names', 'mxchat'); ?></li>
1920 <li><?php esc_html_e('Look in the wp_postmeta database table', 'mxchat'); ?></li>
1921 <li><?php esc_html_e('Use the Scan my content for meta keys button above to discover the keys on your published content automatically', 'mxchat'); ?></li>
1922 <li><?php esc_html_e('Meta keys starting with underscore (_) are usually hidden/internal', 'mxchat'); ?></li>
1923 </ul>
1924 </div>
1925 </div>
1926 </div>
1927 </div>
1928 <?php
1929 }
1930
1931 /**
1932 * Render Pinecone Section
1933 */
1934 function mxchat_render_pinecone_section() {
1935 $pinecone_options = get_option('mxchat_pinecone_addon_options', array());
1936 $use_pinecone = $pinecone_options['mxchat_use_pinecone'] ?? '0';
1937 ?>
1938 <div id="pinecone" class="mxch-section">
1939 <div class="mxch-content-header">
1940 <h1 class="mxch-content-title"><?php esc_html_e('Pinecone Vector Database', 'mxchat'); ?></h1>
1941 <p class="mxch-content-subtitle"><?php esc_html_e('Configure Pinecone for enhanced search performance with larger knowledge bases.', 'mxchat'); ?></p>
1942 </div>
1943
1944 <div class="mxch-card">
1945 <div class="mxch-card-body">
1946 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1947 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
1948 <span><strong><?php esc_html_e('Pinecone is optional.', 'mxchat'); ?></strong> <?php esc_html_e('MxChat works without it. When enabled, content is stored in Pinecone for faster similarity searches.', 'mxchat'); ?></span>
1949 </div>
1950
1951 <form method="post" action="options.php">
1952 <?php settings_fields('mxchat_pinecone_addon_options'); ?>
1953
1954 <div class="mxch-field">
1955 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">
1956 <label class="mxchat-toggle-switch">
1957 <input type="checkbox" name="mxchat_pinecone_addon_options[mxchat_use_pinecone]" value="1" <?php checked($use_pinecone, '1'); ?>>
1958 <span class="mxchat-toggle-slider"></span>
1959 </label>
1960 <span style="font-weight: 500;"><?php esc_html_e('Enable Pinecone Database', 'mxchat'); ?></span>
1961 </div>
1962 </div>
1963
1964 <div class="mxchat-pinecone-settings" <?php echo $use_pinecone ? '' : 'style="display: none;"'; ?>>
1965 <?php if ($use_pinecone) : ?>
1966 <div class="mxch-notice mxch-notice-success" style="margin-bottom: 20px;">
1967 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
1968 <span><?php esc_html_e('Pinecone is enabled. All new knowledge base content will be stored in Pinecone.', 'mxchat'); ?></span>
1969 </div>
1970 <?php endif; ?>
1971
1972 <div class="mxch-field">
1973 <label class="mxch-field-label" for="mxchat_pinecone_api_key">
1974 <?php esc_html_e('Pinecone API Key', 'mxchat'); ?> <span class="mxch-field-label-required">*</span>
1975 </label>
1976 <input type="password" id="mxchat_pinecone_api_key" name="mxchat_pinecone_addon_options[mxchat_pinecone_api_key]" value="<?php echo esc_attr($pinecone_options['mxchat_pinecone_api_key'] ?? ''); ?>" class="mxch-input" placeholder="pcsk_...">
1977 <p class="mxch-field-description">
1978 <?php esc_html_e('Found in your Pinecone dashboard under API Keys.', 'mxchat'); ?>
1979 <a href="https://app.pinecone.io/" target="_blank"><?php esc_html_e('Open Pinecone Dashboard', 'mxchat'); ?></a>
1980 </p>
1981 </div>
1982
1983 <?php
1984 // Index type (plan 362c31): the classic vector index (default) or a
1985 // document index with full-text search. Same key, host and namespace.
1986 $pc_index_type = (($pinecone_options['mxchat_pinecone_index_type'] ?? 'vector') === 'document') ? 'document' : 'vector';
1987 $pc_docs_cloud = $pinecone_options['mxchat_pinecone_docs_cloud'] ?? 'aws';
1988 $pc_docs_region = $pinecone_options['mxchat_pinecone_docs_region'] ?? 'us-east-1';
1989 $pc_docs_lang = $pinecone_options['mxchat_pinecone_docs_language'] ?? 'en';
1990 $pc_verified = $pinecone_options['mxchat_pinecone_docs_verified_host'] ?? '';
1991 $pc_vector_host = $pinecone_options['mxchat_pinecone_vector_host'] ?? '';
1992 $pc_current_host = $pinecone_options['mxchat_pinecone_host'] ?? '';
1993 $pc_docs_class = class_exists('MxChat_Pinecone_Documents');
1994 $pc_expected_dim = $pc_docs_class ? MxChat_Pinecone_Documents::expected_dimension() : 1536;
1995 $pc_migration = $pc_docs_class ? MxChat_Pinecone_Documents::migration_get() : array();
1996 $pc_host_verified = ($pc_current_host !== '' && strtolower(trim($pc_current_host, '/')) === strtolower($pc_verified));
1997 $pc_clouds = $pc_docs_class ? MxChat_Pinecone_Documents::clouds() : array('aws' => 'AWS');
1998 $pc_languages = $pc_docs_class ? MxChat_Pinecone_Documents::languages() : array('en' => 'English');
1999 ?>
2000 <div class="mxch-field" id="mxchat-pinecone-index-type-field">
2001 <span class="mxch-field-label"><?php esc_html_e('Index type', 'mxchat'); ?></span>
2002 <div style="display: flex; flex-direction: column; gap: 6px; margin-top: 8px;">
2003 <label style="display: flex; align-items: baseline; gap: 8px; cursor: pointer;">
2004 <input type="radio" name="mxchat_pinecone_addon_options[mxchat_pinecone_index_type]" class="mxchat-pinecone-index-type" value="vector" <?php checked($pc_index_type, 'vector'); ?>>
2005 <span>
2006 <strong><?php esc_html_e('Vector index (current)', 'mxchat'); ?></strong>
2007 <span class="mxch-field-description" style="display: block; margin: 2px 0 0;"><?php esc_html_e('The classic Pinecone index. Nothing changes for existing setups.', 'mxchat'); ?></span>
2008 </span>
2009 </label>
2010 <label style="display: flex; align-items: baseline; gap: 8px; cursor: pointer;">
2011 <input type="radio" name="mxchat_pinecone_addon_options[mxchat_pinecone_index_type]" class="mxchat-pinecone-index-type" value="document" <?php checked($pc_index_type, 'document'); ?>>
2012 <span>
2013 <strong><?php esc_html_e('Document index with full-text search (new)', 'mxchat'); ?></strong>
2014 <span class="mxch-field-description" style="display: block; margin: 2px 0 0;"><?php esc_html_e('A Pinecone document index keeps a keyword index of your content next to the vectors, so questions with part numbers, SKUs and codes find the exact record. It is a new index: create one below and copy your existing index into it, no re-embedding needed. Turn on the Hybrid keyword boost under Retrieval to use it.', 'mxchat'); ?></span>
2015 </span>
2016 </label>
2017 </div>
2018 </div>
2019 <script type="application/json" id="mxchat-pinecone-docs-state"><?php echo wp_json_encode(array(
2020 'verified_host' => $pc_verified,
2021 'expected_dimension' => (int) $pc_expected_dim,
2022 // 47c61f: the status notice's two texts, so the page can
2023 // keep it in step with the host typed in the field.
2024 'status_checked' => __('Document index checked: %1$s (%2$d dimensions).', 'mxchat'),
2025 'status_unchecked' => __('Not checked yet. Create a document index below, or enter its host above and click Check index. The index type only saves once the host has been checked.', 'mxchat'),
2026 'migration' => $pc_migration,
2027 // 3e83e4: what the LIVE chatbot is on right now, so the
2028 // page can tell a copy-in-progress from a switch.
2029 'index_type' => $pc_index_type,
2030 'stored_host' => strtolower(trim((string) $pc_current_host, '/')),
2031 'stored_index' => (string) ($pinecone_options['mxchat_pinecone_index'] ?? ''),
2032 )); ?></script>
2033
2034 <div class="mxch-field">
2035 <label class="mxch-field-label" for="mxchat_pinecone_environment"><?php esc_html_e('Region', 'mxchat'); ?></label>
2036 <input type="text" id="mxchat_pinecone_environment" name="mxchat_pinecone_addon_options[mxchat_pinecone_environment]" value="<?php echo esc_attr($pinecone_options['mxchat_pinecone_environment'] ?? ''); ?>" class="mxch-input" placeholder="e.g., gcp-starter">
2037 <p class="mxch-field-description"><?php esc_html_e('Your Pinecone environment/region (e.g., gcp-starter, us-west1-gcp)', 'mxchat'); ?></p>
2038 </div>
2039
2040 <div class="mxch-field">
2041 <label class="mxch-field-label" for="mxchat_pinecone_index">
2042 <?php esc_html_e('Index Name', 'mxchat'); ?> <span class="mxch-field-label-required">*</span>
2043 </label>
2044 <input type="text" id="mxchat_pinecone_index" name="mxchat_pinecone_addon_options[mxchat_pinecone_index]" value="<?php echo esc_attr($pinecone_options['mxchat_pinecone_index'] ?? ''); ?>" class="mxch-input" placeholder="e.g., my-wordpress-vectors">
2045 <p class="mxch-field-description"><?php esc_html_e('The name of your Pinecone index. Must be created in your Pinecone dashboard first.', 'mxchat'); ?></p>
2046 </div>
2047
2048 <div class="mxch-field">
2049 <label class="mxch-field-label" for="mxchat_pinecone_host">
2050 <?php esc_html_e('Pinecone Host', 'mxchat'); ?> <span class="mxch-field-label-required">*</span>
2051 </label>
2052 <input type="text" id="mxchat_pinecone_host" name="mxchat_pinecone_addon_options[mxchat_pinecone_host]" value="<?php echo esc_attr($pinecone_options['mxchat_pinecone_host'] ?? ''); ?>" class="mxch-input" placeholder="e.g., my-index-xyz123.svc.pinecone.io">
2053 <p class="mxch-field-description"><?php esc_html_e('The hostname from your Pinecone index URL (exclude https://). Found in index details.', 'mxchat'); ?></p>
2054 </div>
2055
2056 <div class="mxchat-pinecone-docs-settings" <?php echo $pc_index_type === 'document' ? '' : 'style="display: none;"'; ?>>
2057 <div class="mxch-notice <?php echo $pc_host_verified ? 'mxch-notice-success' : 'mxch-notice-warning'; ?>" id="mxchat-pinecone-docs-status" style="margin-bottom: 20px;">
2058 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
2059 <span id="mxchat-pinecone-docs-status-text"><?php
2060 if ($pc_host_verified) {
2061 printf(esc_html__('Document index checked: %1$s (%2$d dimensions).', 'mxchat'), esc_html($pc_verified), (int) $pc_expected_dim);
2062 } else {
2063 esc_html_e('Not checked yet. Create a document index below, or enter its host above and click Check index. The index type only saves once the host has been checked.', 'mxchat');
2064 }
2065 ?></span>
2066 </div>
2067
2068 <div class="mxch-field">
2069 <label class="mxch-field-label" for="mxchat_pinecone_docs_cloud"><?php esc_html_e('Cloud and region for a new index', 'mxchat'); ?></label>
2070 <div style="display: flex; gap: 8px; flex-wrap: wrap;">
2071 <select id="mxchat_pinecone_docs_cloud" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_cloud]" class="mxch-select" style="max-width: 160px;">
2072 <?php foreach ($pc_clouds as $pc_cloud_key => $pc_cloud_label) : ?>
2073 <option value="<?php echo esc_attr($pc_cloud_key); ?>" <?php selected($pc_docs_cloud, $pc_cloud_key); ?>><?php echo esc_html($pc_cloud_label); ?></option>
2074 <?php endforeach; ?>
2075 </select>
2076 <input type="text" id="mxchat_pinecone_docs_region" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_region]" value="<?php echo esc_attr($pc_docs_region); ?>" class="mxch-input" style="max-width: 220px;" placeholder="us-east-1">
2077 <select id="mxchat_pinecone_docs_language" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_language]" class="mxch-select" style="max-width: 200px;">
2078 <?php foreach ($pc_languages as $pc_lang_key => $pc_lang_label) : ?>
2079 <option value="<?php echo esc_attr($pc_lang_key); ?>" <?php selected($pc_docs_lang, $pc_lang_key); ?>><?php echo esc_html($pc_lang_label); ?></option>
2080 <?php endforeach; ?>
2081 </select>
2082 </div>
2083 <p class="mxch-field-description"><?php printf(esc_html__('Create index for me makes a new document index named after the Index Name field (a free name ending in -docs is suggested when you switch to this type), sized for your embedding model (%d dimensions, cosine), with full-text search on the content in the chosen language, then fills in the host. Check index confirms the host above points at a document index MxChat can use. Neither moves your chatbot — that happens when you save.', 'mxchat'), (int) $pc_expected_dim); ?></p>
2084 </div>
2085
2086 <div class="mxch-field" style="display: flex; gap: 8px; flex-wrap: wrap;">
2087 <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-pinecone-docs-create"><?php esc_html_e('Create index for me', 'mxchat'); ?></button>
2088 <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-pinecone-docs-check"><?php esc_html_e('Check index', 'mxchat'); ?></button>
2089 </div>
2090 <div id="mxchat-pinecone-docs-result" style="display: none;"></div>
2091 <p class="mxch-field-hint" id="mxchat-pinecone-docs-gate" style="display: none;"><?php esc_html_e('Check the document index host before saving.', 'mxchat'); ?></p>
2092 <div class="mxch-field" id="mxchat-pinecone-docs-switch-gate" style="display: none;">
2093 <p class="mxch-field-hint" id="mxchat-pinecone-docs-switch-gate-text"></p>
2094 <label class="mxch-field-hint" style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
2095 <input type="checkbox" id="mxchat_pinecone_docs_switch_anyway" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_switch_anyway]" value="1">
2096 <span><?php esc_html_e('Switch anyway — point the chatbot at the document index now and copy the rest afterwards', 'mxchat'); ?></span>
2097 </label>
2098 </div>
2099
2100 <div class="mxch-field" style="margin-top: 20px;">
2101 <label class="mxch-field-label" for="mxchat_pinecone_vector_host"><?php esc_html_e('Copy from vector index host', 'mxchat'); ?></label>
2102 <input type="text" id="mxchat_pinecone_vector_host" name="mxchat_pinecone_addon_options[mxchat_pinecone_vector_host]" value="<?php echo esc_attr($pc_vector_host); ?>" class="mxch-input" placeholder="my-index-xyz123.svc.pinecone.io">
2103 <p class="mxch-field-description"><?php esc_html_e('Migrate copies every record of that index into the document index above — text, vector and metadata, same ids — with no embedding calls. It runs while your chatbot keeps answering from the vector index; save the Pinecone settings afterwards to switch. Safe to run again: records already copied are simply replaced, and an interrupted copy continues where it stopped. Both indexes must use the same embedding dimension.', 'mxchat'); ?></p>
2104 </div>
2105 <div class="mxch-field" style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;">
2106 <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-pinecone-docs-migrate"><?php esc_html_e('Migrate', 'mxchat'); ?></button>
2107 <?php /* e50d2e: offered only when the source index holds records in more than one namespace (the JS shows it from the start response). No name attribute — it is not a saved setting. */ ?>
2108 <label class="mxch-toggle" id="mxchat-pinecone-docs-all-namespaces" style="display: none;" title="<?php esc_attr_e('Copy the records of every namespace of the vector index, each into the same-named namespace of the document index, in one run.', 'mxchat'); ?>">
2109 <input type="checkbox" class="mxch-toggle-input" id="mxchat_pinecone_docs_all_namespaces" value="1">
2110 <span class="mxch-toggle-switch"></span>
2111 <span class="mxch-toggle-label"><?php esc_html_e('Copy every namespace', 'mxchat'); ?></span>
2112 </label>
2113 <span id="mxchat-pinecone-docs-migrate-counts" class="mxch-field-description"></span>
2114 </div>
2115 <div id="mxchat-pinecone-docs-migrate-progress" style="display: none; margin-bottom: 16px;">
2116 <div class="mxch-progress-bar"><div class="mxch-progress-bar-fill" style="width: 0%;"></div></div>
2117 <div class="mxch-progress-label"></div>
2118 </div>
2119
2120 <div class="mxch-field" id="mxchat-pinecone-docs-delete-old" style="display: none;">
2121 <label class="mxch-field-label" for="mxchat_pinecone_docs_delete_confirm"><?php esc_html_e('Delete old index', 'mxchat'); ?></label>
2122 <p class="mxch-field-description"><?php esc_html_e('Available once the copy count matches. Type the old index name to confirm. This deletes the whole vector index at Pinecone and cannot be undone.', 'mxchat'); ?></p>
2123 <div style="display: flex; gap: 8px; flex-wrap: wrap;">
2124 <input type="text" id="mxchat_pinecone_docs_delete_confirm" class="mxch-input" style="max-width: 320px;" placeholder="<?php esc_attr_e('old index name', 'mxchat'); ?>" autocomplete="off">
2125 <button type="button" class="mxch-btn mxch-btn-danger" id="mxchat-pinecone-docs-delete-old-btn"><?php esc_html_e('Delete old index', 'mxchat'); ?></button>
2126 </div>
2127 </div>
2128 </div>
2129
2130 <div class="mxch-field">
2131 <label class="mxch-field-label" for="mxchat_pinecone_top_k">
2132 <?php esc_html_e('Results Per Query (topK)', 'mxchat'); ?>
2133 </label>
2134 <input type="number" id="mxchat_pinecone_top_k" name="mxchat_pinecone_addon_options[mxchat_pinecone_top_k]" value="<?php echo esc_attr($pinecone_options['mxchat_pinecone_top_k'] ?? '50'); ?>" class="mxch-input" min="1" max="1000" step="1" placeholder="50">
2135 <p class="mxch-field-description"><?php esc_html_e('How many candidate matches each Pinecone query requests (1-1000, default 50). Higher values improve grouping of chunked content at the cost of slightly larger responses.', 'mxchat'); ?></p>
2136 </div>
2137 </div>
2138
2139 <?php submit_button(__('Save Pinecone Settings', 'mxchat'), 'primary', 'submit', true, array('class' => 'mxch-btn mxch-btn-primary')); ?>
2140 </form>
2141 </div>
2142 </div>
2143 </div>
2144 <?php
2145 }
2146
2147 /**
2148 * Render OpenAI Vector Store Section
2149 */
2150 function mxchat_render_openai_vectorstore_section() {
2151 $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
2152 $use_vectorstore = $vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0';
2153 $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? '';
2154 $max_results = $vectorstore_options['mxchat_vectorstore_max_results'] ?? 5;
2155 $sync_enabled = $vectorstore_options['mxchat_vectorstore_sync_enabled'] ?? '0';
2156 $sync_store_id = $vectorstore_options['mxchat_vectorstore_sync_store_id'] ?? '';
2157 $sync_config = class_exists('MxChat_Vectorstore_Manager') ? MxChat_Vectorstore_Manager::get_sync_config('default') : array('enabled' => false, 'store_id' => '');
2158 $mapped_count = class_exists('MxChat_Vectorstore_Manager') ? MxChat_Vectorstore_Manager::mapped_file_count() : 0;
2159
2160 // Get current chat model to check compatibility
2161 $mxchat_options = get_option('mxchat_options', array());
2162 $current_model = $mxchat_options['model'] ?? 'gpt-5.6-sol';
2163 $is_openai_model = preg_match('/^(gpt-|o1-|o3-)/', $current_model);
2164 ?>
2165 <div id="openai-vectorstore" class="mxch-section">
2166 <div class="mxch-content-header">
2167 <h1 class="mxch-content-title"><?php esc_html_e('OpenAI Vector Store', 'mxchat'); ?></h1>
2168 <p class="mxch-content-subtitle"><?php esc_html_e('Use OpenAI\'s hosted vector database for knowledge retrieval. Your documents are stored and searched directly on OpenAI\'s platform.', 'mxchat'); ?></p>
2169 </div>
2170
2171 <div class="mxch-card">
2172 <div class="mxch-card-body">
2173 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
2174 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
2175 <span><strong><?php esc_html_e('Requires OpenAI Chat Model.', 'mxchat'); ?></strong> <?php esc_html_e('Vector Store search only works with OpenAI models (gpt-5.6-sol, gpt-5.6-terra, etc.). Create Vector Stores in your OpenAI Dashboard.', 'mxchat'); ?></span>
2176 </div>
2177
2178 <?php if (!$is_openai_model && $use_vectorstore === '1'): ?>
2179 <div class="mxch-notice mxch-notice-warning" style="margin-bottom: 20px;">
2180 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
2181 <span><strong><?php esc_html_e('Model Incompatible:', 'mxchat'); ?></strong> <?php printf(esc_html__('Your current chat model (%s) is not an OpenAI model. Vector Store search will not work until you switch to an OpenAI model.', 'mxchat'), esc_html($current_model)); ?></span>
2182 </div>
2183 <?php endif; ?>
2184
2185 <form method="post" action="options.php" id="mxchat-vectorstore-form">
2186 <?php settings_fields('mxchat_openai_vectorstore_options'); ?>
2187
2188 <div class="mxch-field">
2189 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">
2190 <label class="mxchat-toggle-switch">
2191 <input type="checkbox" name="mxchat_openai_vectorstore_options[mxchat_use_openai_vectorstore]" value="1" <?php checked($use_vectorstore, '1'); ?> id="mxchat_use_openai_vectorstore">
2192 <span class="mxchat-toggle-slider"></span>
2193 </label>
2194 <span style="font-weight: 500;"><?php esc_html_e('Enable OpenAI Vector Store', 'mxchat'); ?></span>
2195 </div>
2196 </div>
2197
2198 <div class="mxchat-vectorstore-settings" <?php echo $use_vectorstore === '1' ? '' : 'style="display: none;"'; ?>>
2199 <?php if ($use_vectorstore === '1'): ?>
2200 <div class="mxch-notice mxch-notice-success" style="margin-bottom: 20px;">
2201 <svg class="mxch-notice-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
2202 <span><?php esc_html_e('OpenAI Vector Store is enabled. Queries will search your Vector Store for relevant content.', 'mxchat'); ?></span>
2203 </div>
2204 <?php endif; ?>
2205
2206 <div class="mxch-field">
2207 <label class="mxch-field-label" for="mxchat_vectorstore_ids">
2208 <?php esc_html_e('Vector Store ID(s)', 'mxchat'); ?> <span class="mxch-field-label-required">*</span>
2209 </label>
2210 <input type="text" id="mxchat_vectorstore_ids" name="mxchat_openai_vectorstore_options[mxchat_vectorstore_ids]" value="<?php echo esc_attr($vectorstore_ids); ?>" class="mxch-input" placeholder="vs_abc123xyz">
2211 <p class="mxch-field-description">
2212 <?php esc_html_e('Enter your Vector Store ID from the OpenAI Dashboard. For multiple stores, separate with commas.', 'mxchat'); ?>
2213 <a href="https://platform.openai.com/storage/vector_stores" target="_blank"><?php esc_html_e('Open OpenAI Vector Store Dashboard', 'mxchat'); ?></a>
2214 </p>
2215 </div>
2216
2217 <div class="mxch-field">
2218 <label class="mxch-field-label" for="mxchat_vectorstore_max_results">
2219 <?php esc_html_e('Max Results', 'mxchat'); ?>
2220 </label>
2221 <select id="mxchat_vectorstore_max_results" name="mxchat_openai_vectorstore_options[mxchat_vectorstore_max_results]" class="mxch-input" style="width: auto;">
2222 <?php for ($i = 1; $i <= 10; $i++): ?>
2223 <option value="<?php echo $i; ?>" <?php selected($max_results, $i); ?>><?php echo $i; ?></option>
2224 <?php endfor; ?>
2225 </select>
2226 <p class="mxch-field-description"><?php esc_html_e('Maximum number of content chunks to retrieve from the Vector Store.', 'mxchat'); ?></p>
2227 </div>
2228 </div>
2229
2230 <div class="mxch-field" style="border-top: 1px solid var(--mxch-border, #e2e4e7); padding-top: 20px; margin-top: 4px;">
2231 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
2232 <label class="mxchat-toggle-switch">
2233 <input type="checkbox" name="mxchat_openai_vectorstore_options[mxchat_vectorstore_sync_enabled]" value="1" <?php checked($sync_enabled, '1'); ?> id="mxchat_vectorstore_sync_enabled">
2234 <span class="mxchat-toggle-slider"></span>
2235 </label>
2236 <span style="font-weight: 500;"><?php esc_html_e('Sync Knowledge Base to Vector Store', 'mxchat'); ?></span>
2237 </div>
2238 <p class="mxch-field-description" style="margin-bottom: 16px;">
2239 <?php esc_html_e('Keeps your Vector Store up to date automatically: knowledge base additions, edits, and deletions are mirrored to the store (one file per entry, replaced on change). Without this, the store is frozen at whatever you uploaded manually. Role-restricted entries are never uploaded — OpenAI file search cannot filter by user role.', 'mxchat'); ?>
2240 </p>
2241
2242 <label class="mxch-field-label" for="mxchat_vectorstore_sync_store_id">
2243 <?php esc_html_e('Sync Target Vector Store ID', 'mxchat'); ?>
2244 </label>
2245 <input type="text" id="mxchat_vectorstore_sync_store_id" name="mxchat_openai_vectorstore_options[mxchat_vectorstore_sync_store_id]" value="<?php echo esc_attr($sync_store_id); ?>" class="mxch-input" placeholder="<?php echo esc_attr($sync_config['store_id'] ?: 'vs_abc123xyz'); ?>">
2246 <p class="mxch-field-description">
2247 <?php esc_html_e('Leave blank to use the first Vector Store ID above. Syncing writes to exactly one store.', 'mxchat'); ?>
2248 </p>
2249 </div>
2250
2251 <?php submit_button(__('Save Vector Store Settings', 'mxchat'), 'primary', 'submit', true, array('class' => 'mxch-btn mxch-btn-primary')); ?>
2252 </form>
2253
2254 <?php if ($sync_config['enabled']): ?>
2255 <div class="mxch-field" id="mxchat-vs-import" style="border-top: 1px solid var(--mxch-border, #e2e4e7); padding-top: 20px;"
2256 data-nonce="<?php echo esc_attr(wp_create_nonce('mxchat_admin_nonce')); ?>">
2257 <label class="mxch-field-label"><?php esc_html_e('Import Existing Knowledge Base', 'mxchat'); ?></label>
2258 <p class="mxch-field-description">
2259 <?php printf(esc_html__('One-time (re-runnable) import of every knowledge base entry into the sync target store. Runs in the background via WP-Cron; safe to interrupt and resume — already-imported, unchanged entries are skipped. Currently mirrored: %s files.', 'mxchat'), '<strong id="mxchat-vs-mapped">' . esc_html(number_format_i18n($mapped_count)) . '</strong>'); ?>
2260 </p>
2261 <div style="display: flex; align-items: center; gap: 8px; margin: 10px 0;">
2262 <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-vs-import-start"><?php esc_html_e('Import Knowledge Base to Vector Store', 'mxchat'); ?></button>
2263 <button type="button" class="mxch-btn" id="mxchat-vs-import-resume" style="display:none;"><?php esc_html_e('Resume Import', 'mxchat'); ?></button>
2264 <button type="button" class="mxch-btn" id="mxchat-vs-import-cancel" style="display:none;"><?php esc_html_e('Cancel', 'mxchat'); ?></button>
2265 </div>
2266 <div id="mxchat-vs-import-bar" style="display:none; height: 8px; background: var(--mxch-border, #e2e4e7); border-radius: 4px; overflow: hidden; max-width: 420px;">
2267 <div id="mxchat-vs-import-fill" style="height: 100%; width: 0%; background: #2271b1; transition: width .4s;"></div>
2268 </div>
2269 <p class="mxch-field-description" id="mxchat-vs-import-status" style="margin-top: 8px;"></p>
2270 </div>
2271
2272 <script>
2273 (function() {
2274 var wrap = document.getElementById('mxchat-vs-import');
2275 if (!wrap) { return; }
2276 var nonce = wrap.getAttribute('data-nonce');
2277 var startBtn = document.getElementById('mxchat-vs-import-start');
2278 var resumeBtn = document.getElementById('mxchat-vs-import-resume');
2279 var cancelBtn = document.getElementById('mxchat-vs-import-cancel');
2280 var bar = document.getElementById('mxchat-vs-import-bar');
2281 var fill = document.getElementById('mxchat-vs-import-fill');
2282 var statusEl = document.getElementById('mxchat-vs-import-status');
2283 var mappedEl = document.getElementById('mxchat-vs-mapped');
2284 var pollTimer = null;
2285
2286 function post(action, done) {
2287 var body = 'action=' + encodeURIComponent(action) + '&nonce=' + encodeURIComponent(nonce);
2288 fetch(ajaxurl, {
2289 method: 'POST',
2290 credentials: 'same-origin',
2291 headers: {'Content-Type': 'application/x-www-form-urlencoded'},
2292 body: body
2293 }).then(function(r) { return r.json(); }).then(done).catch(function() {
2294 statusEl.textContent = '<?php echo esc_js(__('Request failed — check the browser console.', 'mxchat')); ?>';
2295 });
2296 }
2297
2298 function render(state, mapped) {
2299 if (typeof mapped === 'number' && mappedEl) { mappedEl.textContent = mapped.toLocaleString(); }
2300 var running = state.status === 'running';
2301 startBtn.style.display = running ? 'none' : '';
2302 cancelBtn.style.display = running ? '' : 'none';
2303 resumeBtn.style.display = (running && state.stalled) ? '' : 'none';
2304 bar.style.display = (running || state.status === 'done') ? '' : 'none';
2305 var pct = state.total > 0 ? Math.min(100, Math.round(state.processed / state.total * 100)) : 0;
2306 if (state.status === 'done') { pct = 100; }
2307 fill.style.width = pct + '%';
2308
2309 var bits = [];
2310 if (state.status === 'running') { bits.push(state.stalled ? '<?php echo esc_js(__('Import stalled (cron missed) — click Resume.', 'mxchat')); ?>' : '<?php echo esc_js(__('Importing…', 'mxchat')); ?>'); }
2311 if (state.status === 'done') { bits.push('<?php echo esc_js(__('Import complete.', 'mxchat')); ?>'); }
2312 if (state.status === 'cancelled') { bits.push('<?php echo esc_js(__('Import cancelled.', 'mxchat')); ?>'); }
2313 if (state.status === 'error') { bits.push('<?php echo esc_js(__('Import error:', 'mxchat')); ?> ' + state.last_error); }
2314 if (state.status !== 'idle') {
2315 bits.push(state.processed + '/' + state.total
2316 + ' — ' + state.imported + ' <?php echo esc_js(__('uploaded', 'mxchat')); ?>'
2317 + ', ' + state.unchanged + ' <?php echo esc_js(__('unchanged', 'mxchat')); ?>'
2318 + ', ' + state.skipped_restricted + ' <?php echo esc_js(__('skipped (role-restricted)', 'mxchat')); ?>'
2319 + ', ' + state.failed + ' <?php echo esc_js(__('failed', 'mxchat')); ?>');
2320 if (state.failed > 0 && state.last_error && state.status !== 'error') {
2321 bits.push('<?php echo esc_js(__('Last error:', 'mxchat')); ?> ' + state.last_error);
2322 }
2323 }
2324 statusEl.textContent = bits.join(' ');
2325
2326 if (running && !pollTimer) {
2327 pollTimer = setInterval(function() {
2328 post('mxchat_vectorstore_import_status', function(res) {
2329 if (res && res.success) { render(res.data.state, res.data.mapped); }
2330 });
2331 }, 3000);
2332 } else if (!running && pollTimer) {
2333 clearInterval(pollTimer);
2334 pollTimer = null;
2335 }
2336 }
2337
2338 startBtn.addEventListener('click', function() {
2339 startBtn.disabled = true;
2340 statusEl.textContent = '<?php echo esc_js(__('Starting…', 'mxchat')); ?>';
2341 post('mxchat_vectorstore_import_start', function(res) {
2342 startBtn.disabled = false;
2343 if (res && res.success) { render(res.data.state); }
2344 else { statusEl.textContent = (res && res.data && res.data.message) ? res.data.message : '<?php echo esc_js(__('Could not start the import.', 'mxchat')); ?>'; }
2345 });
2346 });
2347 resumeBtn.addEventListener('click', function() {
2348 post('mxchat_vectorstore_import_resume', function(res) {
2349 if (res && res.success) { render(res.data.state); }
2350 });
2351 });
2352 cancelBtn.addEventListener('click', function() {
2353 post('mxchat_vectorstore_import_cancel', function(res) {
2354 if (res && res.success) { render(res.data.state); }
2355 });
2356 });
2357
2358 // Pick up an import already in flight when the page loads.
2359 post('mxchat_vectorstore_import_status', function(res) {
2360 if (res && res.success && res.data.state.status !== 'idle') { render(res.data.state, res.data.mapped); }
2361 });
2362 })();
2363 </script>
2364 <?php endif; ?>
2365 </div>
2366 </div>
2367 </div>
2368 <?php
2369 }
2370
2371 /**
2372 * Render Content Selector Modal
2373 */
2374 function mxchat_render_content_selector_modal() {
2375 ?>
2376 <div id="mxchat-kb-content-selector-modal" class="mxchat-kb-modal">
2377 <div class="mxchat-kb-modal-content">
2378 <div class="mxchat-kb-modal-header">
2379 <h3>
2380 <?php esc_html_e('Select WordPress Content', 'mxchat'); ?><br>
2381 <span class="mxchat-kb-header-note"><?php esc_html_e('(Content imported here will be tagged "In Knowledge Base")', 'mxchat'); ?></span>
2382 </h3>
2383 <span class="mxchat-kb-modal-close">&times;</span>
2384 </div>
2385 <div class="mxchat-kb-modal-filters">
2386 <div class="mxchat-kb-search-group">
2387 <input type="text" id="mxchat-kb-content-search" placeholder="<?php esc_attr_e('Search...', 'mxchat'); ?>">
2388 </div>
2389 <div class="mxchat-kb-filter-group">
2390 <select id="mxchat-kb-content-type-filter">
2391 <option value="all"><?php esc_html_e('All Content Types', 'mxchat'); ?></option>
2392 <option value="post"><?php esc_html_e('Posts', 'mxchat'); ?></option>
2393 <option value="page"><?php esc_html_e('Pages', 'mxchat'); ?></option>
2394 <?php
2395 $post_types = get_post_types(array('public' => true), 'objects');
2396 foreach ($post_types as $post_type) {
2397 if (!in_array($post_type->name, array('post', 'page'))) {
2398 echo '<option value="' . esc_attr($post_type->name) . '">' . esc_html($post_type->label) . '</option>';
2399 }
2400 }
2401 ?>
2402 </select>
2403 <select id="mxchat-kb-content-status-filter">
2404 <option value="publish"><?php esc_html_e('Published', 'mxchat'); ?></option>
2405 <option value="draft"><?php esc_html_e('Drafts', 'mxchat'); ?></option>
2406 <option value="all"><?php esc_html_e('All Statuses', 'mxchat'); ?></option>
2407 </select>
2408 <select id="mxchat-kb-processed-filter">
2409 <option value="all"><?php esc_html_e('All Content', 'mxchat'); ?></option>
2410 <option value="processed"><?php esc_html_e('In Knowledge Base', 'mxchat'); ?></option>
2411 <option value="unprocessed"><?php esc_html_e('Not In Knowledge Base', 'mxchat'); ?></option>
2412 </select>
2413 </div>
2414 </div>
2415 <?php
2416 // Shown only while Media is the selected type (plan 01010a). Media lists
2417 // just the files whose text MxChat can read; saying so here is clearer
2418 // than listing images and audio as rows that cannot be selected.
2419 ?>
2420 <div class="mxchat-kb-filter-note" id="mxchat-kb-media-note" hidden>
2421 <svg class="mxchat-kb-filter-note-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
2422 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
2423 <path d="M14 2v6h6"></path>
2424 </svg>
2425 <span><?php esc_html_e('Media lists PDF, Word, text and Markdown files — the types MxChat can read text from. Images, audio and video are not shown.', 'mxchat'); ?></span>
2426 </div>
2427 <div class="mxchat-kb-content-selection">
2428 <div class="mxchat-kb-selection-header">
2429 <label>
2430 <input type="checkbox" id="mxchat-kb-select-all">
2431 <?php esc_html_e('Select All on Page', 'mxchat'); ?>
2432 </label>
2433 <span class="mxchat-kb-selection-count">0 <?php esc_html_e('selected', 'mxchat'); ?></span>
2434 <span class="mxchat-kb-selection-hint" style="margin-left: auto; font-size: 12px; color: var(--mxch-text-muted);">
2435 <span class="dashicons dashicons-info-outline" style="font-size: 14px; vertical-align: middle;"></span>
2436 <?php esc_html_e('Selections persist across pages', 'mxchat'); ?>
2437 </span>
2438 </div>
2439 <div class="mxchat-kb-content-list">
2440 <div class="mxchat-kb-loading">
2441 <span class="mxchat-kb-spinner is-active"></span>
2442 <?php esc_html_e('Loading content...', 'mxchat'); ?>
2443 </div>
2444 </div>
2445 </div>
2446 <div class="mxchat-kb-modal-footer">
2447 <div class="mxchat-kb-pagination"></div>
2448 <div class="mxchat-kb-footer-actions">
2449 <button type="button" id="mxchat-kb-process-selected" class="mxchat-kb-button-primary" disabled>
2450 <?php esc_html_e('Process Selected Content', 'mxchat'); ?>
2451 <span class="mxchat-kb-selected-count">(0)</span>
2452 </button>
2453 <button type="button" class="mxchat-kb-button-secondary mxchat-kb-modal-close">
2454 <?php esc_html_e('Cancel', 'mxchat'); ?>
2455 </button>
2456 </div>
2457 </div>
2458 </div>
2459 </div>
2460 <?php
2461 }
2462
2463 /**
2464 * Render Edit Entry Modal
2465 */
2466 function mxchat_render_edit_entry_modal() {
2467 ?>
2468 <div id="mxchat-kb-edit-modal" class="mxchat-kb-modal">
2469 <div class="mxchat-kb-modal-content mxchat-kb-edit-modal-content">
2470 <div class="mxchat-kb-modal-header">
2471 <h3 id="mxchat-kb-edit-title"><?php esc_html_e('Edit Knowledge Entry', 'mxchat'); ?></h3>
2472 <span class="mxchat-kb-modal-close" id="mxchat-kb-edit-close">&times;</span>
2473 </div>
2474 <div class="mxchat-kb-edit-body">
2475 <div class="mxchat-kb-edit-source" id="mxchat-kb-edit-source"></div>
2476 <textarea id="mxchat-kb-edit-textarea" class="mxchat-kb-edit-textarea" placeholder="<?php esc_attr_e('Loading content...', 'mxchat'); ?>"></textarea>
2477 <div class="mxchat-kb-edit-meta">
2478 <span id="mxchat-kb-edit-charcount"></span>
2479 <span id="mxchat-kb-edit-chunkinfo"></span>
2480 </div>
2481 </div>
2482 <div class="mxchat-kb-edit-footer">
2483 <div class="mxchat-kb-edit-notice" id="mxchat-kb-edit-notice"></div>
2484 <div class="mxchat-kb-edit-actions">
2485 <button type="button" id="mxchat-kb-edit-cancel" class="mxch-btn mxch-btn-ghost">
2486 <?php esc_html_e('Cancel', 'mxchat'); ?>
2487 </button>
2488 <button type="button" id="mxchat-kb-edit-save" class="mxch-btn mxch-btn-primary">
2489 <span class="mxchat-kb-edit-save-text"><?php esc_html_e('Save & Re-embed', 'mxchat'); ?></span>
2490 <span class="mxchat-kb-edit-save-spinner" style="display:none;">
2491 <span class="mxchat-kb-spinner is-active" style="margin: 0;"></span>
2492 <?php esc_html_e('Saving...', 'mxchat'); ?>
2493 </span>
2494 </button>
2495 </div>
2496 </div>
2497 </div>
2498 </div>
2499 <?php
2500 }
2501
2502 /**
2503 * Render the read-only Knowledge Inspector modal (plan-mxchat-20260628-d8cb4b).
2504 * Shows exactly what was indexed for an entry: the per-chunk stored text + lengths
2505 * and (for Pinecone) the stored metadata fields, rendered with the Testing tab's
2506 * own card components so the two surfaces feel like one system. Self-contained
2507 * markup + JS so it doesn't entangle the edit-modal init.
2508 */
2509 function mxchat_render_inspect_entry_modal() {
2510 ?>
2511 <div id="mxchat-kb-inspect-modal" class="mxchat-kb-modal">
2512 <div class="mxchat-kb-modal-content mxchat-kb-inspect-modal-content">
2513 <div class="mxchat-kb-modal-header">
2514 <h3 id="mxchat-kb-inspect-title"><?php esc_html_e('Indexed Content', 'mxchat'); ?></h3>
2515 <span class="mxchat-kb-modal-close" id="mxchat-kb-inspect-close">&times;</span>
2516 </div>
2517 <div class="mxchat-kb-inspect-body">
2518 <div class="mxchat-kb-edit-source" id="mxchat-kb-inspect-source"></div>
2519 <div class="mxch-testing-results" id="mxchat-kb-inspect-results">
2520 <div class="mxch-testing-no-data"><?php esc_html_e('Loading indexed content…', 'mxchat'); ?></div>
2521 </div>
2522 </div>
2523 <div class="mxchat-kb-edit-footer">
2524 <div class="mxchat-kb-edit-notice" id="mxchat-kb-inspect-notice"></div>
2525 <div class="mxchat-kb-edit-actions">
2526 <button type="button" id="mxchat-kb-inspect-close-btn" class="mxch-btn mxch-btn-primary">
2527 <?php esc_html_e('Close', 'mxchat'); ?>
2528 </button>
2529 </div>
2530 </div>
2531 </div>
2532 </div>
2533 <script>
2534 (function() {
2535 'use strict';
2536 document.addEventListener('DOMContentLoaded', function() {
2537 var modal = document.getElementById('mxchat-kb-inspect-modal');
2538 if (!modal) return;
2539 var closeX = document.getElementById('mxchat-kb-inspect-close');
2540 var closeBtn = document.getElementById('mxchat-kb-inspect-close-btn');
2541 var sourceEl = document.getElementById('mxchat-kb-inspect-source');
2542 var resultsEl= document.getElementById('mxchat-kb-inspect-results');
2543 var titleEl = document.getElementById('mxchat-kb-inspect-title');
2544 var noticeEl = document.getElementById('mxchat-kb-inspect-notice');
2545
2546 var I18N = {
2547 title: <?php echo wp_json_encode( esc_html__('Indexed Content', 'mxchat') ); ?>,
2548 loading: <?php echo wp_json_encode( esc_html__('Loading indexed content…', 'mxchat') ); ?>,
2549 manual: <?php echo wp_json_encode( esc_html__('Manual Content', 'mxchat') ); ?>,
2550 source: <?php echo wp_json_encode( esc_html__('Source', 'mxchat') ); ?>,
2551 store: <?php echo wp_json_encode( esc_html__('Storage', 'mxchat') ); ?>,
2552 type: <?php echo wp_json_encode( esc_html__('Content type', 'mxchat') ); ?>,
2553 chunksLbl:<?php echo wp_json_encode( esc_html__('Chunks', 'mxchat') ); ?>,
2554 totalLen: <?php echo wp_json_encode( esc_html__('Total indexed length', 'mxchat') ); ?>,
2555 chunk: <?php echo wp_json_encode( esc_html__('Chunk', 'mxchat') ); ?>,
2556 indexed: <?php echo wp_json_encode( esc_html__('Indexed', 'mxchat') ); ?>,
2557 chars: <?php echo wp_json_encode( esc_html__('chars', 'mxchat') ); ?>,
2558 showText: <?php echo wp_json_encode( esc_html__('Show indexed text', 'mxchat') ); ?>,
2559 hideText: <?php echo wp_json_encode( esc_html__('Hide indexed text', 'mxchat') ); ?>,
2560 wpStore: <?php echo wp_json_encode( esc_html__('Local WordPress database', 'mxchat') ); ?>,
2561 pcStore: <?php echo wp_json_encode( esc_html__('Pinecone', 'mxchat') ); ?>,
2562 meta: <?php echo wp_json_encode( esc_html__('Vector metadata', 'mxchat') ); ?>,
2563 loadFail: <?php echo wp_json_encode( esc_html__('Failed to load indexed content.', 'mxchat') ); ?>,
2564 netErr: <?php echo wp_json_encode( esc_html__('Network error: ', 'mxchat') ); ?>
2565 };
2566
2567 function esc(str) {
2568 var d = document.createElement('div');
2569 d.textContent = (str === null || str === undefined) ? '' : String(str);
2570 return d.innerHTML;
2571 }
2572 function fmt(n) { try { return Number(n).toLocaleString(); } catch (e) { return n; } }
2573
2574 document.addEventListener('click', function(e) {
2575 var btn = e.target.closest('.mxchat-inspect-entry-btn');
2576 if (btn) { e.preventDefault(); open(btn); }
2577 });
2578 if (closeX) closeX.addEventListener('click', close);
2579 if (closeBtn) closeBtn.addEventListener('click', close);
2580 // Overlay click closes, but only when the whole gesture happened on the
2581 // overlay — otherwise selecting indexed text and releasing past the
2582 // dialog edge dispatches the click on the overlay and closes it.
2583 var downOnOverlay = false;
2584 modal.addEventListener('mousedown', function(e) { downOnOverlay = (e.target === modal); });
2585 modal.addEventListener('click', function(e) {
2586 var overlayGesture = downOnOverlay;
2587 downOnOverlay = false;
2588 if (e.target === modal && overlayGesture) close();
2589 });
2590 document.addEventListener('keydown', function(e) {
2591 if (e.key === 'Escape' && modal.classList.contains('active')) close();
2592 });
2593
2594 function close() { modal.classList.remove('active'); }
2595
2596 function open(btn) {
2597 var entry = {
2598 sourceUrl: btn.getAttribute('data-source-url') || '',
2599 entryId: btn.getAttribute('data-entry-id') || '',
2600 dataSource: btn.getAttribute('data-data-source') || 'wordpress',
2601 botId: btn.getAttribute('data-bot-id') || 'default',
2602 nonce: btn.getAttribute('data-nonce') || ''
2603 };
2604
2605 titleEl.textContent = I18N.title;
2606 noticeEl.textContent = '';
2607 noticeEl.className = 'mxchat-kb-edit-notice';
2608 resultsEl.innerHTML = '<div class="mxch-testing-no-data">' + esc(I18N.loading) + '</div>';
2609
2610 if (entry.sourceUrl && entry.sourceUrl.indexOf('mxchat://') !== 0 && entry.sourceUrl.indexOf('_ungrouped_') !== 0) {
2611 sourceEl.innerHTML = esc(I18N.source) + ': <a href="' + esc(entry.sourceUrl) + '" target="_blank" rel="noopener">' + esc(entry.sourceUrl) + '</a>';
2612 } else {
2613 sourceEl.textContent = I18N.manual;
2614 }
2615
2616 modal.classList.add('active');
2617
2618 var fd = new FormData();
2619 fd.append('action', 'mxchat_inspect_entry');
2620 fd.append('nonce', entry.nonce);
2621 fd.append('source_url', entry.sourceUrl);
2622 fd.append('entry_id', entry.entryId);
2623 fd.append('data_source', entry.dataSource);
2624 fd.append('bot_id', entry.botId);
2625
2626 fetch(ajaxurl, { method: 'POST', body: fd })
2627 .then(function(r) { return r.json(); })
2628 .then(function(resp) {
2629 if (resp && resp.success) {
2630 render(resp.data);
2631 } else {
2632 var msg = (resp && resp.data && resp.data.message) || I18N.loadFail;
2633 resultsEl.innerHTML = '';
2634 showNotice(msg, 'error');
2635 }
2636 })
2637 .catch(function(err) {
2638 resultsEl.innerHTML = '';
2639 showNotice(I18N.netErr + err.message, 'error');
2640 });
2641 }
2642
2643 function render(data) {
2644 var storeLabel = data.store === 'pinecone' ? I18N.pcStore : I18N.wpStore;
2645 var html = '';
2646
2647 // Summary card — what this entry is + how much was indexed.
2648 html += '<div class="match-card above-threshold">' +
2649 '<div class="match-header">' +
2650 '<div class="match-title"><span class="status-icon">&#128230;</span> ' + esc(data.chunk_count) + ' ' + esc(I18N.chunksLbl.toLowerCase()) + '</div>' +
2651 '<span class="context-label">' + esc(storeLabel) + '</span>' +
2652 '</div>' +
2653 '<div class="mxch-testing-field"><label>' + esc(I18N.type) + '</label><code>' + esc(data.content_type || '—') + '</code> ' +
2654 '&nbsp; <label style="display:inline; text-transform:none; letter-spacing:0; font-weight:600;">' + esc(I18N.totalLen) + ':</label> ' + esc(fmt(data.assembled_length)) + ' ' + esc(I18N.chars) + '</div>';
2655 if (data.metadata_note) {
2656 html += '<div class="match-source"><span class="source-icon">&#8505;&#65039;</span> ' + esc(data.metadata_note) + '</div>';
2657 }
2658 html += '</div>';
2659
2660 // One card per stored chunk — the actual embedded text.
2661 var chunks = data.chunks || [];
2662 chunks.forEach(function(chunk, i) {
2663 var num = (chunk.index !== null && chunk.index !== undefined) ? (chunk.index + 1) : (i + 1);
2664 var metaRows = '';
2665 if (chunk.metadata && typeof chunk.metadata === 'object') {
2666 var keys = Object.keys(chunk.metadata);
2667 if (keys.length) {
2668 metaRows += '<div class="chunk-detail-row chunk-used" style="display:block;"><span class="chunk-detail-num">' + esc(I18N.meta) + '</span></div>';
2669 keys.forEach(function(k) {
2670 metaRows += '<div class="chunk-detail-row"><span class="chunk-detail-num">' + esc(k) + '</span><span class="chunk-detail-score">' + esc(chunk.metadata[k]) + '</span></div>';
2671 });
2672 }
2673 }
2674 html += '<div class="match-card above-threshold">' +
2675 '<div class="match-header">' +
2676 '<div class="match-title"><span class="status-icon">&#10003;</span> ' + esc(I18N.chunk) + ' ' + esc(num) +
2677 '<span class="chunk-summary">' + esc(fmt(chunk.length)) + ' ' + esc(I18N.chars) + '</span>' +
2678 '</div>' +
2679 '<span class="context-label">' + esc(I18N.indexed) + '</span>' +
2680 '</div>' +
2681 '<span class="chunk-expand-toggle" data-chunk="' + i + '">&#9654; ' + esc(I18N.showText) + '</span>' +
2682 '<div class="chunk-details" data-chunk="' + i + '">' +
2683 '<pre class="mxch-kb-inspect-chunk-text">' + esc(chunk.text) + '</pre>' +
2684 metaRows +
2685 '</div>' +
2686 '</div>';
2687 });
2688
2689 resultsEl.innerHTML = html;
2690
2691 resultsEl.querySelectorAll('.chunk-expand-toggle').forEach(function(toggle) {
2692 toggle.addEventListener('click', function() {
2693 var id = this.getAttribute('data-chunk');
2694 var details = resultsEl.querySelector('.chunk-details[data-chunk="' + id + '"]');
2695 if (!details) return;
2696 var expanded = details.classList.toggle('expanded');
2697 this.innerHTML = (expanded ? '&#9660; ' + esc(I18N.hideText) : '&#9654; ' + esc(I18N.showText));
2698 });
2699 });
2700 }
2701
2702 function showNotice(msg, type) {
2703 noticeEl.textContent = msg;
2704 noticeEl.className = 'mxchat-kb-edit-notice' + (type ? ' ' + type : '');
2705 }
2706 });
2707 })();
2708 </script>
2709 <?php
2710 }
2711
2712 /**
2713 * Render Knowledge Page Navigation Scripts
2714 */
2715 function mxchat_render_knowledge_page_scripts() {
2716 ?>
2717 <script>
2718 (function() {
2719 'use strict';
2720
2721 // Wait for DOM
2722 document.addEventListener('DOMContentLoaded', function() {
2723 // Tab navigation + mobile menu live in the shared shell script
2724 // (js/admin-sidebar.js), enqueued for this page by plan c192a4.
2725 initImportOptions();
2726 initCustomPostTypesToggle();
2727 // Sitemap detection is now initialized when user clicks the Sitemap Import option
2728 });
2729
2730 function initImportOptions() {
2731 const importBoxes = document.querySelectorAll('.mxchat-import-box');
2732 const urlInputArea = document.getElementById('mxchat-url-input-area');
2733 const contentInputArea = document.getElementById('mxchat-content-input-area');
2734 const urlInput = document.getElementById('sitemap_url');
2735 const importTypeField = document.getElementById('import_type');
2736 const descriptionText = document.getElementById('url-description-text');
2737
2738 // Sitemap detection elements
2739 const sitemapsLoading = document.getElementById('mxchat-sitemaps-loading');
2740 const detectedSitemaps = document.getElementById('mxchat-detected-sitemaps');
2741 const noSitemaps = document.getElementById('mxchat-no-sitemaps');
2742
2743 // Helper to hide all sitemap detection UI
2744 function hideSitemapDetection() {
2745 if (sitemapsLoading) sitemapsLoading.style.display = 'none';
2746 if (detectedSitemaps) detectedSitemaps.style.display = 'none';
2747 if (noSitemaps) noSitemaps.style.display = 'none';
2748 }
2749
2750 importBoxes.forEach(box => {
2751 box.addEventListener('click', function() {
2752 const option = this.dataset.option;
2753 const type = this.dataset.type;
2754
2755 // Remove active from all boxes
2756 importBoxes.forEach(b => b.classList.remove('active'));
2757 this.classList.add('active');
2758
2759 // Handle different import types
2760 if (option === 'wordpress') {
2761 // WordPress content selector - handled by existing modal
2762 hideSitemapDetection();
2763 return;
2764 }
2765
2766 if (option === 'content') {
2767 if (urlInputArea) urlInputArea.style.display = 'none';
2768 if (contentInputArea) contentInputArea.style.display = 'block';
2769 hideSitemapDetection();
2770 } else if (type === 'sitemap' || type === 'url' || type === 'pdf') {
2771 if (contentInputArea) contentInputArea.style.display = 'none';
2772 if (urlInputArea) urlInputArea.style.display = 'block';
2773
2774 if (urlInput) {
2775 urlInput.placeholder = this.dataset.placeholder || 'Enter URL here';
2776 }
2777 if (importTypeField) {
2778 importTypeField.value = type;
2779 }
2780 if (descriptionText) {
2781 const descriptions = {
2782 'sitemap': '<?php echo esc_js(__('Use a content-specific sub-sitemap (e.g., post-sitemap.xml), not the main sitemap index.', 'mxchat')); ?>',
2783 'url': '<?php echo esc_js(__('Enter the URL of any webpage to import its content.', 'mxchat')); ?>',
2784 'pdf': '<?php echo esc_js(__('Enter the URL of a publicly accessible PDF file.', 'mxchat')); ?>'
2785 };
2786 descriptionText.textContent = descriptions[type] || '';
2787 }
2788
2789 // Only show sitemap detection when Sitemap Import is selected
2790 if (type === 'sitemap') {
2791 // Initialize sitemap detection (function is defined in knowledge-processing.js)
2792 if (typeof window.mxchatInitSitemapDetection === 'function') {
2793 window.mxchatInitSitemapDetection();
2794 }
2795 } else {
2796 hideSitemapDetection();
2797 }
2798 }
2799 });
2800 });
2801 }
2802
2803 function initCustomPostTypesToggle() {
2804 const toggleBtn = document.getElementById('mxchat-custom-post-types-toggle');
2805 const container = document.getElementById('mxchat-custom-post-types-container');
2806
2807 if (toggleBtn && container) {
2808 toggleBtn.addEventListener('click', function() {
2809 const isHidden = container.style.display === 'none';
2810 container.style.display = isHidden ? 'block' : 'none';
2811 const icon = this.querySelector('span:last-child');
2812 if (icon) {
2813 icon.textContent = isHidden ? '▲' : '▼';
2814 }
2815 });
2816 }
2817 }
2818
2819 // Sitemap detection is now handled by knowledge-processing.js
2820 // It will be initialized when user clicks "Sitemap Import" option
2821
2822 // ─── Edit Entry Modal ────────────────────────────────────
2823 initEditModal();
2824
2825 function initEditModal() {
2826 var modal = document.getElementById('mxchat-kb-edit-modal');
2827 var textarea = document.getElementById('mxchat-kb-edit-textarea');
2828 var saveBtn = document.getElementById('mxchat-kb-edit-save');
2829 var cancelBtn = document.getElementById('mxchat-kb-edit-cancel');
2830 var closeBtn = document.getElementById('mxchat-kb-edit-close');
2831 var notice = document.getElementById('mxchat-kb-edit-notice');
2832 var charCount = document.getElementById('mxchat-kb-edit-charcount');
2833 var chunkInfo = document.getElementById('mxchat-kb-edit-chunkinfo');
2834 var sourceEl = document.getElementById('mxchat-kb-edit-source');
2835 var titleEl = document.getElementById('mxchat-kb-edit-title');
2836 var saveText = saveBtn ? saveBtn.querySelector('.mxchat-kb-edit-save-text') : null;
2837 var saveSpin = saveBtn ? saveBtn.querySelector('.mxchat-kb-edit-save-spinner') : null;
2838
2839 if (!modal) return;
2840
2841 var currentEntry = {};
2842 var loadedContent = '';
2843
2844 var EDIT_I18N = {
2845 discard: <?php echo wp_json_encode( __('Discard your unsaved changes to this entry?', 'mxchat') ); ?>
2846 };
2847
2848 // Bind edit buttons (delegated)
2849 document.addEventListener('click', function(e) {
2850 var btn = e.target.closest('.mxchat-edit-entry-btn');
2851 if (btn) {
2852 e.preventDefault();
2853 openEditModal(btn);
2854 }
2855 });
2856
2857 // Close handlers. The overlay deliberately has no click-to-close: a click
2858 // fires on the common ancestor of its mousedown and mouseup, so releasing
2859 // a text-selection drag past the dialog edge targets the overlay and would
2860 // discard the edit. Closing is explicit only, and confirms when dirty.
2861 if (closeBtn) closeBtn.addEventListener('click', requestClose);
2862 if (cancelBtn) cancelBtn.addEventListener('click', requestClose);
2863 document.addEventListener('keydown', function(e) {
2864 if (e.key === 'Escape' && modal.classList.contains('active')) requestClose();
2865 });
2866
2867 // Character count
2868 if (textarea) {
2869 textarea.addEventListener('input', function() {
2870 updateCharCount();
2871 });
2872 }
2873
2874 // Save handler
2875 if (saveBtn) saveBtn.addEventListener('click', saveContent);
2876
2877 function openEditModal(btn) {
2878 currentEntry = {
2879 sourceUrl: btn.getAttribute('data-source-url') || '',
2880 entryId: btn.getAttribute('data-entry-id') || '',
2881 dataSource: btn.getAttribute('data-data-source') || 'wordpress',
2882 botId: btn.getAttribute('data-bot-id') || 'default',
2883 nonce: btn.getAttribute('data-nonce') || ''
2884 };
2885
2886 // Reset state
2887 textarea.value = '';
2888 loadedContent = '';
2889 textarea.placeholder = 'Loading content...';
2890 textarea.disabled = true;
2891 saveBtn.disabled = true;
2892 notice.textContent = '';
2893 notice.className = 'mxchat-kb-edit-notice';
2894 charCount.textContent = '';
2895 chunkInfo.textContent = '';
2896
2897 // Show source
2898 if (currentEntry.sourceUrl && currentEntry.sourceUrl.indexOf('mxchat://') !== 0) {
2899 sourceEl.innerHTML = 'Source: <a href="' + escapeHtml(currentEntry.sourceUrl) + '" target="_blank">' + escapeHtml(truncate(currentEntry.sourceUrl, 60)) + '</a>';
2900 } else {
2901 sourceEl.textContent = 'Manual Content';
2902 }
2903
2904 // Show modal
2905 modal.classList.add('active');
2906
2907 // Fetch content
2908 var formData = new FormData();
2909 formData.append('action', 'mxchat_get_entry_content');
2910 formData.append('nonce', currentEntry.nonce);
2911 formData.append('source_url', currentEntry.sourceUrl);
2912 formData.append('entry_id', currentEntry.entryId);
2913 formData.append('data_source', currentEntry.dataSource);
2914 formData.append('bot_id', currentEntry.botId);
2915
2916 fetch(ajaxurl, { method: 'POST', body: formData })
2917 .then(function(r) { return r.json(); })
2918 .then(function(resp) {
2919 if (resp.success) {
2920 textarea.value = resp.data.content || '';
2921 loadedContent = textarea.value;
2922 textarea.disabled = false;
2923 textarea.placeholder = 'Edit your content here...';
2924 saveBtn.disabled = false;
2925 currentEntry.contentType = resp.data.content_type || 'content';
2926
2927 updateCharCount();
2928
2929 if (resp.data.is_chunked) {
2930 chunkInfo.textContent = resp.data.chunk_count + ' chunks — will be re-chunked on save';
2931 titleEl.textContent = 'Edit Knowledge Entry (' + resp.data.chunk_count + ' chunks)';
2932 } else {
2933 chunkInfo.textContent = '';
2934 titleEl.textContent = 'Edit Knowledge Entry';
2935 }
2936
2937 textarea.focus();
2938 } else {
2939 textarea.placeholder = '';
2940 showNotice((resp.data && resp.data.message) || 'Failed to load content.', 'error');
2941 }
2942 })
2943 .catch(function(err) {
2944 textarea.placeholder = '';
2945 showNotice('Network error: ' + err.message, 'error');
2946 });
2947 }
2948
2949 function saveContent() {
2950 if (!textarea.value.trim()) {
2951 showNotice('Content cannot be empty.', 'error');
2952 return;
2953 }
2954
2955 saveBtn.disabled = true;
2956 if (saveText) saveText.style.display = 'none';
2957 if (saveSpin) saveSpin.style.display = '';
2958 showNotice('Saving and re-embedding...', '');
2959
2960 var formData = new FormData();
2961 formData.append('action', 'mxchat_save_entry_content');
2962 formData.append('nonce', currentEntry.nonce);
2963 formData.append('source_url', currentEntry.sourceUrl);
2964 formData.append('entry_id', currentEntry.entryId);
2965 formData.append('content', textarea.value);
2966 formData.append('data_source', currentEntry.dataSource);
2967 formData.append('bot_id', currentEntry.botId);
2968 formData.append('content_type', currentEntry.contentType || 'content');
2969
2970 fetch(ajaxurl, { method: 'POST', body: formData })
2971 .then(function(r) { return r.json(); })
2972 .then(function(resp) {
2973 if (saveText) saveText.style.display = '';
2974 if (saveSpin) saveSpin.style.display = 'none';
2975 saveBtn.disabled = false;
2976
2977 if (resp.success) {
2978 if (currentEntry.dataSource === 'pinecone') {
2979 // Pinecone list reads are eventually consistent — the reloaded
2980 // table may show the old text for up to ~60 seconds.
2981 showNotice('Saved! Pinecone changes may take up to 60 seconds to appear — use "Refresh Entries" if the list still shows the old text.', 'success');
2982 setTimeout(function() {
2983 closeModal();
2984 window.location.reload();
2985 }, 2500);
2986 } else {
2987 showNotice('Saved successfully!', 'success');
2988 setTimeout(function() {
2989 closeModal();
2990 window.location.reload();
2991 }, 1000);
2992 }
2993 } else {
2994 showNotice((resp.data && resp.data.message) || 'Save failed.', 'error');
2995 }
2996 })
2997 .catch(function(err) {
2998 if (saveText) saveText.style.display = '';
2999 if (saveSpin) saveSpin.style.display = 'none';
3000 saveBtn.disabled = false;
3001 showNotice('Network error: ' + err.message, 'error');
3002 });
3003 }
3004
3005 function isDirty() {
3006 return !textarea.disabled && textarea.value !== loadedContent;
3007 }
3008
3009 function requestClose() {
3010 if (isDirty() && !window.confirm(EDIT_I18N.discard)) return;
3011 closeModal();
3012 }
3013
3014 function closeModal() {
3015 modal.classList.remove('active');
3016 }
3017
3018 function updateCharCount() {
3019 var len = textarea.value.length;
3020 charCount.textContent = len.toLocaleString() + ' characters';
3021 }
3022
3023 function showNotice(msg, type) {
3024 notice.textContent = msg;
3025 notice.className = 'mxchat-kb-edit-notice' + (type ? ' ' + type : '');
3026 }
3027
3028 function escapeHtml(str) {
3029 var div = document.createElement('div');
3030 div.textContent = str;
3031 return div.innerHTML;
3032 }
3033
3034 function truncate(str, max) {
3035 return str.length > max ? str.substring(0, max) + '...' : str;
3036 }
3037 }
3038
3039 })();
3040 </script>
3041 <?php
3042 }
3043