PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.25
MxChat – AI Chatbot & Content Generation for WordPress v3.2.25
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.25, at includes/admin-knowledge-page.php

3,042 lines 220.4 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 echo MxChat_Knowledge_Manager::mxchat_source_cell_html($source_url, $current_bot_id, true); ?>
1132 </td>
1133 <td class="mxchat-actions-cell" style="padding: 12px 16px; white-space: nowrap;">
1134 <button type="button"
1135 class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-inspect-entry-btn"
1136 data-source-url="<?php echo esc_attr($source_url); ?>"
1137 data-entry-id="<?php echo esc_attr($first_prompt->id); ?>"
1138 data-data-source="<?php echo esc_attr($data_source); ?>"
1139 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1140 data-nonce="<?php echo wp_create_nonce('mxchat_inspect_entry_nonce'); ?>"
1141 title="<?php esc_attr_e('View indexed content', 'mxchat'); ?>">
1142 <span class="dashicons dashicons-visibility" style="font-size: 14px;"></span>
1143 </button>
1144 <button type="button"
1145 class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-edit-entry-btn"
1146 data-source-url="<?php echo esc_attr($source_url); ?>"
1147 data-entry-id="<?php echo esc_attr($first_prompt->id); ?>"
1148 data-data-source="<?php echo esc_attr($data_source); ?>"
1149 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1150 data-nonce="<?php echo wp_create_nonce('mxchat_edit_entry_nonce'); ?>"
1151 title="<?php esc_attr_e('Edit content', 'mxchat'); ?>">
1152 <span class="dashicons dashicons-edit" style="font-size: 14px;"></span>
1153 </button>
1154 <button type="button"
1155 class="mxch-btn mxch-btn-ghost mxch-btn-sm delete-button-group"
1156 data-source-url="<?php echo esc_attr($source_url); ?>"
1157 data-chunk-count="<?php echo esc_attr($chunk_count); ?>"
1158 data-data-source="<?php echo esc_attr($data_source); ?>"
1159 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1160 data-nonce="<?php echo wp_create_nonce('mxchat_delete_chunks_nonce'); ?>"
1161 style="color: var(--mxch-error);"
1162 title="<?php esc_attr_e('Delete all chunks', 'mxchat'); ?>">
1163 <span class="dashicons dashicons-trash" style="font-size: 14px;"></span>
1164 </button>
1165 </td>
1166 </tr>
1167 <?php
1168 // Render hidden chunk rows
1169 foreach ($group as $chunk_index => $prompt) :
1170 $meta_chunk_index = isset($prompt->chunk_metadata['chunk_index']) ? intval($prompt->chunk_metadata['chunk_index']) : $chunk_index;
1171 $meta_total_chunks = isset($prompt->chunk_metadata['total_chunks']) ? intval($prompt->chunk_metadata['total_chunks']) : $chunk_count;
1172 $content = isset($prompt->display_content) ? $prompt->display_content : $prompt->article_content;
1173 $preview_length = 150;
1174 $content_preview = mb_strlen($content) > $preview_length
1175 ? mb_substr($content, 0, $preview_length) . '...'
1176 : $content;
1177 ?>
1178 <tr id="prompt-<?php echo esc_attr($prompt->id); ?>"
1179 class="mxchat-chunk-row <?php echo esc_attr($group_id); ?>"
1180 data-source="<?php echo esc_attr($data_source); ?>"
1181 style="display: none; background: #f8f9fa; border-bottom: 1px solid var(--mxch-card-border);">
1182 <td style="padding: 12px 16px; text-align: center;">
1183 <!-- Checkbox placeholder for chunk rows -->
1184 </td>
1185 <td style="padding: 12px 16px 12px 30px; font-size: 13px;">
1186 <!-- Hidden ID column for chunks -->
1187 </td>
1188 <td class="mxchat-content-cell" style="padding: 12px 16px; font-size: 13px;">
1189 <div class="mxchat-accordion-wrapper">
1190 <div class="mxchat-content-preview">
1191 <span class="mxchat-chunk-indicator" style="margin-right: 10px; color: var(--mxch-text-secondary); font-size: 12px;">
1192 <?php printf(esc_html__('Chunk %d of %d', 'mxchat'), $meta_chunk_index + 1, $meta_total_chunks); ?>
1193 </span>
1194 <span class="preview-text"><?php echo esc_html($content_preview); ?></span>
1195 <?php if (mb_strlen($content) > $preview_length) : ?>
1196 <button class="mxchat-expand-toggle" type="button">
1197 <span class="dashicons dashicons-arrow-down-alt2"></span>
1198 </button>
1199 <?php endif; ?>
1200 </div>
1201 <div class="mxchat-content-full" style="display: none;">
1202 <div class="content-view">
1203 <?php
1204 if (preg_match('/[\x{0590}-\x{05FF}]/u', $content)) {
1205 echo '<div dir="rtl" lang="he" class="rtl-content">';
1206 echo wp_kses_post(wpautop($content));
1207 echo '</div>';
1208 } else {
1209 echo wp_kses_post(wpautop($content));
1210 }
1211 ?>
1212 </div>
1213 </div>
1214 </div>
1215 </td>
1216 <td class="mxchat-url-cell" style="padding: 12px 16px; font-size: 13px;">
1217 <span class="mxchat-chunk-label" style="color: var(--mxch-text-muted);"><?php esc_html_e('Same as parent', 'mxchat'); ?></span>
1218 </td>
1219 <td class="mxchat-actions-cell" style="padding: 12px 16px;">
1220 <span class="mxchat-chunk-label" style="color: var(--mxch-text-muted);"><?php esc_html_e('Managed by group', 'mxchat'); ?></span>
1221 </td>
1222 </tr>
1223 <?php endforeach; ?>
1224 <?php else :
1225 // Single entry - display normally with accordion
1226 $prompt = $first_prompt;
1227 $content = isset($prompt->display_content) ? $prompt->display_content : $prompt->article_content;
1228 $preview_length = 150;
1229 $content_preview = mb_strlen($content) > $preview_length
1230 ? mb_substr($content, 0, $preview_length) . '...'
1231 : $content;
1232 ?>
1233 <tr id="prompt-<?php echo esc_attr($prompt->id); ?>"
1234 data-source="<?php echo esc_attr($data_source); ?>"
1235 style="border-bottom: 1px solid var(--mxch-card-border); <?php if ($data_source === 'pinecone') echo 'background: rgba(33, 150, 243, 0.02);'; ?>">
1236 <td style="padding: 12px 16px; text-align: center;">
1237 <input type="checkbox"
1238 class="mxchat-entry-checkbox"
1239 data-entry-id="<?php echo esc_attr($prompt->id); ?>"
1240 data-source="<?php echo esc_attr($data_source); ?>"
1241 data-source-url="<?php echo esc_attr($source_url); ?>"
1242 data-is-group="false">
1243 </td>
1244 <td style="padding: 12px 16px; font-size: 13px;">
1245 <?php if ($data_source === 'pinecone') : ?>
1246 <?php echo esc_html($display_index + (($current_page - 1) * $per_page)); ?>
1247 <?php else : ?>
1248 <?php echo esc_html($prompt->id); ?>
1249 <?php endif; ?>
1250 </td>
1251 <td class="mxchat-content-cell" style="padding: 12px 16px; font-size: 13px;">
1252 <div class="mxchat-accordion-wrapper">
1253 <div class="mxchat-content-preview">
1254 <span class="preview-text"><?php echo esc_html($content_preview); ?></span>
1255 <?php if (mb_strlen($content) > $preview_length) : ?>
1256 <button class="mxchat-expand-toggle" type="button">
1257 <span class="dashicons dashicons-arrow-down-alt2"></span>
1258 </button>
1259 <?php endif; ?>
1260 </div>
1261 <div class="mxchat-content-full" style="display: none;">
1262 <div class="content-view">
1263 <?php
1264 if (preg_match('/[\x{0590}-\x{05FF}]/u', $content)) {
1265 echo '<div dir="rtl" lang="he" class="rtl-content">';
1266 echo wp_kses_post(wpautop($content));
1267 echo '</div>';
1268 } else {
1269 echo wp_kses_post(wpautop($content));
1270 }
1271 ?>
1272 </div>
1273 </div>
1274 </div>
1275 </td>
1276 <td class="mxchat-url-cell" style="padding: 12px 16px; font-size: 13px;">
1277 <?php
1278 $actual_source = $source_url;
1279 if (strpos($source_url, '_ungrouped_') === 0) {
1280 $actual_source = $prompt->source_url ?? '';
1281 }
1282 echo MxChat_Knowledge_Manager::mxchat_source_cell_html($actual_source, $current_bot_id, false);
1283 ?>
1284 </td>
1285 <td style="padding: 12px 16px; white-space: nowrap;">
1286 <button type="button"
1287 class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-inspect-entry-btn"
1288 data-source-url="<?php echo esc_attr($prompt->source_url ?? ''); ?>"
1289 data-entry-id="<?php echo esc_attr($prompt->id); ?>"
1290 data-data-source="<?php echo esc_attr($data_source); ?>"
1291 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1292 data-nonce="<?php echo wp_create_nonce('mxchat_inspect_entry_nonce'); ?>"
1293 title="<?php esc_attr_e('View indexed content', 'mxchat'); ?>">
1294 <span class="dashicons dashicons-visibility" style="font-size: 14px;"></span>
1295 </button>
1296 <button type="button"
1297 class="mxch-btn mxch-btn-ghost mxch-btn-sm mxchat-edit-entry-btn"
1298 data-source-url="<?php echo esc_attr($prompt->source_url ?? ''); ?>"
1299 data-entry-id="<?php echo esc_attr($prompt->id); ?>"
1300 data-data-source="<?php echo esc_attr($data_source); ?>"
1301 data-bot-id="<?php echo esc_attr($current_bot_id); ?>"
1302 data-nonce="<?php echo wp_create_nonce('mxchat_edit_entry_nonce'); ?>"
1303 title="<?php esc_attr_e('Edit content', 'mxchat'); ?>">
1304 <span class="dashicons dashicons-edit" style="font-size: 14px;"></span>
1305 </button>
1306 <?php if ($data_source === 'pinecone') : ?>
1307 <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);">
1308 <span class="dashicons dashicons-trash" style="font-size: 14px;"></span>
1309 </button>
1310 <?php else : ?>
1311 <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);">
1312 <span class="dashicons dashicons-trash" style="font-size: 14px;"></span>
1313 </button>
1314 <?php endif; ?>
1315 </td>
1316 </tr>
1317 <?php endif; ?>
1318 <?php endforeach; ?>
1319 <?php endif; ?>
1320 </tbody>
1321 </table>
1322 </div>
1323
1324 <!-- Pagination wrapper - always present so JS can populate it after processing -->
1325 <?php
1326 // Plan dd6e10: Pinecone's list endpoint is a cursor — there is no
1327 // random access to page N, so over 500 vectors the screen offers
1328 // Previous / Next only. The same markup is built for AJAX page
1329 // loads by MxChat_Knowledge_Manager::mxchat_cursor_pagination_html().
1330 $cursor_pagination = !empty($cursor_pagination);
1331 $has_next = !empty($has_next);
1332 $show_pagination = $cursor_pagination ? ($current_page > 1 || $has_next) : ($total_pages > 1);
1333 ?>
1334 <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); ?>">
1335 <?php if ($cursor_pagination) : ?>
1336 <?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 ?>
1337 <?php elseif ($total_pages > 1) : ?>
1338 <div class="mxchat-ajax-pagination" data-current-page="<?php echo esc_attr($current_page); ?>" data-total-pages="<?php echo esc_attr($total_pages); ?>">
1339 <?php if ($current_page > 1) : ?>
1340 <a href="#" class="mxchat-page-link" data-page="<?php echo ($current_page - 1); ?>"><?php esc_html_e('&laquo; Previous', 'mxchat'); ?></a>
1341 <?php endif; ?>
1342
1343 <?php
1344 $start_page = max(1, $current_page - 2);
1345 $end_page = min($total_pages, $current_page + 2);
1346
1347 if ($start_page > 1) {
1348 echo '<a href="#" class="mxchat-page-link" data-page="1">1</a> ';
1349 if ($start_page > 2) {
1350 echo '<span class="mxchat-page-dots">...</span> ';
1351 }
1352 }
1353
1354 for ($i = $start_page; $i <= $end_page; $i++) {
1355 if ($i == $current_page) {
1356 echo '<span class="mxchat-page-current">' . $i . '</span> ';
1357 } else {
1358 echo '<a href="#" class="mxchat-page-link" data-page="' . $i . '">' . $i . '</a> ';
1359 }
1360 }
1361
1362 if ($end_page < $total_pages) {
1363 if ($end_page < $total_pages - 1) {
1364 echo '<span class="mxchat-page-dots">...</span> ';
1365 }
1366 echo '<a href="#" class="mxchat-page-link" data-page="' . $total_pages . '">' . $total_pages . '</a> ';
1367 }
1368 ?>
1369
1370 <?php if ($current_page < $total_pages) : ?>
1371 <a href="#" class="mxchat-page-link" data-page="<?php echo ($current_page + 1); ?>"><?php esc_html_e('Next &raquo;', 'mxchat'); ?></a>
1372 <?php endif; ?>
1373 </div>
1374 <?php endif; ?>
1375 </div>
1376 </div>
1377 </div>
1378
1379 <?php mxchat_render_kb_reimport_card(!empty($current_bot_id) ? $current_bot_id : 'default'); ?>
1380 </div>
1381 <?php
1382 }
1383
1384 /**
1385 * "Re-import affected entries" card (plan 89739b).
1386 *
1387 * The owner-facing side of wp mxchat kb-reimport: check first (no embedding
1388 * request, nothing written), read the list, then confirm. Both halves run in
1389 * resumable steps through the mxchat_kb_reimport AJAX action; the script is
1390 * js/knowledge-reimport.js. Everything dynamic is drawn there; this is the
1391 * resting markup.
1392 */
1393 function mxchat_render_kb_reimport_card($current_bot_id = 'default') {
1394 if (!class_exists('MxChat_Knowledge_Manager')) {
1395 return;
1396 }
1397 ?>
1398 <div class="mxch-card mxch-kb-reimport" id="mxchat-kb-reimport"
1399 data-nonce="<?php echo esc_attr(wp_create_nonce('mxchat_kb_reimport')); ?>"
1400 data-bot="<?php echo esc_attr($current_bot_id); ?>">
1401 <div class="mxch-card-header">
1402 <h3 class="mxch-card-title">
1403 <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>
1404 <?php esc_html_e('Re-import affected entries', 'mxchat'); ?>
1405 </h3>
1406 </div>
1407 <div class="mxch-card-body">
1408 <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>
1409
1410 <div class="mxch-kb-reimport-controls">
1411 <div class="mxch-field">
1412 <label class="mxch-field-label" for="mxchat-kb-reimport-before"><?php esc_html_e('Entries last written before', 'mxchat'); ?></label>
1413 <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)); ?>" />
1414 </div>
1415 <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-kb-reimport-check"><?php esc_html_e('Check knowledge base', 'mxchat'); ?></button>
1416 </div>
1417 <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>
1418
1419 <!-- Also offer entries whose page was edited after they were imported (plan a00ef8); off by default -->
1420 <div class="mxch-field mxch-kb-reimport-edited">
1421 <label class="toggle-switch">
1422 <input type="checkbox" id="mxchat-kb-reimport-edited" name="mxchat_kb_reimport_edited" value="1" />
1423 <span class="slider"></span>
1424 </label>
1425 <div class="mxch-kb-reimport-edited-text">
1426 <label class="mxch-field-label" for="mxchat-kb-reimport-edited"><?php esc_html_e('Also rewrite entries whose page was edited after they were imported', 'mxchat'); ?></label>
1427 <p class="mxch-field-description"><?php esc_html_e('An entry older than its post, page, product or media file is rebuilt from it as it reads today. A site with auto-sync on does not need this.', 'mxchat'); ?></p>
1428 </div>
1429 </div>
1430
1431 <div class="mxch-kb-reimport-progress" hidden>
1432 <div class="mxch-progress-bar" hidden><div class="mxch-progress-bar-fill"></div></div>
1433 <p class="mxch-progress-label" aria-live="polite"></p>
1434 </div>
1435
1436 <div class="mxch-notice mxch-notice-error mxch-kb-reimport-error" role="alert" hidden>
1437 <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>
1438 <span></span>
1439 </div>
1440
1441 <div class="mxch-kb-reimport-results" hidden>
1442 <div class="mxch-notice mxch-notice-success mxch-kb-reimport-done" hidden>
1443 <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>
1444 <span></span>
1445 </div>
1446 <div class="mxch-kb-reimport-counts"></div>
1447 <ul class="mxch-kb-reimport-list mxch-kb-reimport-entries" hidden></ul>
1448 <p class="mxch-field-hint mxch-kb-reimport-more" hidden></p>
1449 <details class="mxch-disclosure mxch-kb-reimport-others" hidden>
1450 <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>
1451 <div class="mxch-disclosure-body">
1452 <ul class="mxch-kb-reimport-list mxch-kb-reimport-notes"></ul>
1453 </div>
1454 </details>
1455 </div>
1456 </div>
1457 <div class="mxch-card-footer mxch-kb-reimport-footer" hidden>
1458 <button type="button" class="mxch-btn mxch-btn-primary" id="mxchat-kb-reimport-apply"></button>
1459 <button type="button" class="mxch-btn mxch-btn-ghost" id="mxchat-kb-reimport-clear"><?php esc_html_e('Clear', 'mxchat'); ?></button>
1460 <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>
1461 </div>
1462 </div>
1463 <?php
1464 }
1465
1466 /**
1467 * Render Auto-Sync Section
1468 */
1469 function mxchat_render_auto_sync_section($knowledge_manager) {
1470 ?>
1471 <div id="auto-sync" class="mxch-section">
1472 <div class="mxch-content-header">
1473 <h1 class="mxch-content-title"><?php esc_html_e('Auto-Sync Settings', 'mxchat'); ?></h1>
1474 <p class="mxch-content-subtitle"><?php esc_html_e('Automatically sync WordPress content to your knowledge base when published or updated.', 'mxchat'); ?></p>
1475 </div>
1476
1477 <div class="mxch-card">
1478 <div class="mxch-card-body mxchat-autosave-section">
1479 <div class="mxch-field">
1480 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">
1481 <label class="mxchat-toggle-switch">
1482 <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'); ?>>
1483 <span class="mxchat-toggle-slider"></span>
1484 </label>
1485 <span style="font-weight: 500;"><?php esc_html_e('Auto-sync Posts', 'mxchat'); ?></span>
1486 </div>
1487 <div style="display: flex; align-items: center; gap: 12px;">
1488 <label class="mxchat-toggle-switch">
1489 <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'); ?>>
1490 <span class="mxchat-toggle-slider"></span>
1491 </label>
1492 <span style="font-weight: 500;"><?php esc_html_e('Auto-sync Pages', 'mxchat'); ?></span>
1493 </div>
1494 </div>
1495
1496 <div class="mxch-field" style="margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--mxch-card-border);">
1497 <div style="display: flex; align-items: center; gap: 12px;">
1498 <label class="mxchat-toggle-switch">
1499 <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'); ?>>
1500 <span class="mxchat-toggle-slider"></span>
1501 </label>
1502 <span style="font-weight: 500;"><?php esc_html_e('Extract text from PDFs in ACF fields on save', 'mxchat'); ?></span>
1503 </div>
1504 <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>
1505 </div>
1506
1507 <div style="margin-top: 24px;">
1508 <button id="mxchat-custom-post-types-toggle" class="mxch-btn mxch-btn-secondary">
1509 <?php esc_html_e('Advanced Custom Post Sync Settings', 'mxchat'); ?>
1510 <span style="margin-left: 5px;">▼</span>
1511 </button>
1512 <div id="mxchat-custom-post-types-container" style="display: none; margin-top: 16px; padding: 16px; background: #f8fafc; border-radius: var(--mxch-radius-md);">
1513 <h4 style="margin: 0 0 12px 0;"><?php esc_html_e('Sync Custom Post Types', 'mxchat'); ?></h4>
1514 <?php
1515 $post_types = $knowledge_manager->mxchat_get_public_post_types();
1516 unset($post_types['post'], $post_types['page']);
1517
1518 if (!empty($post_types)) {
1519 foreach ($post_types as $post_type => $label) {
1520 $option_name = 'mxchat_auto_sync_' . $post_type;
1521 $is_enabled = get_option($option_name, '0');
1522 ?>
1523 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
1524 <label class="mxchat-toggle-switch">
1525 <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'); ?>>
1526 <span class="mxchat-toggle-slider"></span>
1527 </label>
1528 <span><?php echo esc_html($label); ?> (<?php echo esc_html($post_type); ?>)</span>
1529 </div>
1530 <?php
1531 }
1532 } else {
1533 echo '<p style="color: var(--mxch-text-muted);">' . esc_html__('No custom post types found.', 'mxchat') . '</p>';
1534 }
1535 ?>
1536 </div>
1537 </div>
1538 </div>
1539 </div>
1540 </div>
1541 <?php
1542 }
1543
1544 /**
1545 * Render Chunking Section
1546 */
1547 function mxchat_render_chunking_section() {
1548 $chunking_settings = MxChat_Chunker::get_settings();
1549 $chunking_enabled = $chunking_settings['chunking_enabled'];
1550 $chunk_size = $chunking_settings['chunk_size'];
1551 ?>
1552 <div id="chunking" class="mxch-section">
1553 <div class="mxch-content-header">
1554 <h1 class="mxch-content-title"><?php esc_html_e('Chunking & Retrieval', 'mxchat'); ?></h1>
1555 <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>
1556 </div>
1557
1558 <div class="mxch-card">
1559 <div class="mxch-card-header">
1560 <h2 class="mxch-card-title"><?php esc_html_e('Chunking', 'mxchat'); ?></h2>
1561 </div>
1562 <div class="mxch-card-body mxchat-autosave-section">
1563 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1564 <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>
1565 <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>
1566 </div>
1567
1568 <div class="mxch-field">
1569 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">
1570 <label class="mxchat-toggle-switch">
1571 <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); ?>>
1572 <span class="mxchat-toggle-slider"></span>
1573 </label>
1574 <span style="font-weight: 500;"><?php esc_html_e('Enable Content Chunking', 'mxchat'); ?></span>
1575 </div>
1576 </div>
1577
1578 <div class="mxch-field">
1579 <label class="mxch-field-label" for="mxchat_chunk_size"><?php esc_html_e('Chunk Size (characters)', 'mxchat'); ?></label>
1580 <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;">
1581 <p class="mxch-field-description"><?php esc_html_e('Recommended: 4000 characters (~1000 tokens). Range: 1000-10000. Larger chunks preserve more context.', 'mxchat'); ?></p>
1582 </div>
1583 </div>
1584 </div>
1585
1586 <?php
1587 // Retrieval tuning (plan 11720c) — the hybrid keyword boost moved here
1588 // from Settings → Behavior: it is KB retrieval tuning, so it lives with
1589 // its natural siblings. SAME option key and save transport as before —
1590 // the name routes to the mxchat_save_setting handler, whose
1591 // mxchat_hybrid_keyword_toggle case still runs capability detection.
1592 ?>
1593 <div class="mxch-card">
1594 <div class="mxch-card-header">
1595 <h2 class="mxch-card-title"><?php esc_html_e('Retrieval', 'mxchat'); ?></h2>
1596 </div>
1597 <div class="mxch-card-body mxchat-autosave-section">
1598 <div class="mxch-field">
1599 <div style="display: flex; align-items: center; gap: 12px;">
1600 <label class="mxchat-toggle-switch">
1601 <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'); ?>>
1602 <span class="mxchat-toggle-slider"></span>
1603 </label>
1604 <span style="font-weight: 500;"><?php esc_html_e('Hybrid keyword boost (WordPress database and Pinecone document indexes)', 'mxchat'); ?></span>
1605 </div>
1606 <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>
1607 <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>
1608 </div>
1609 </div>
1610 </div>
1611
1612 <?php
1613 // Video cards (plan f52492). Lives on the Knowledge screen because that
1614 // is where the owner imported the video in the first place, and beside
1615 // Retrieval because it is a retrieval-confidence question. Standalone
1616 // options — see the mxchat_video_embed_* cases in class-ajax-handler.php.
1617 $video_embed_enabled = MxChat_Utils::video_embed_enabled();
1618 $video_embed_threshold = (int) round(MxChat_Utils::video_embed_threshold() * 100);
1619 $mxchat_core_options = get_option('mxchat_options', array());
1620 $site_threshold = isset($mxchat_core_options['similarity_threshold'])
1621 ? (int) $mxchat_core_options['similarity_threshold']
1622 : 35;
1623 ?>
1624 <div class="mxch-card">
1625 <div class="mxch-card-header">
1626 <h2 class="mxch-card-title"><?php esc_html_e('Video Cards', 'mxchat'); ?></h2>
1627 </div>
1628 <div class="mxch-card-body mxchat-autosave-section">
1629 <div class="mxch-field" style="margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid var(--mxch-card-border);">
1630 <div style="display: flex; align-items: center; gap: 12px;">
1631 <label class="mxchat-toggle-switch">
1632 <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); ?>>
1633 <span class="mxchat-toggle-slider"></span>
1634 </label>
1635 <span style="font-weight: 500;"><?php esc_html_e('Show a video card when a YouTube source answers the question', 'mxchat'); ?></span>
1636 </div>
1637 <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>
1638 </div>
1639
1640 <div class="mxch-field" id="mxchat-video-embed-threshold-field" style="<?php echo $video_embed_enabled ? '' : 'display: none;'; ?>">
1641 <label class="mxch-field-label" for="mxchat_video_embed_threshold"><?php esc_html_e('Video Card Match Threshold (%)', 'mxchat'); ?></label>
1642 <?php // Slider matching the site-wide Similarity Threshold exactly
1643 // (plan 7afd54): same .slider-container / .range-slider /
1644 // .range-value markup; the shared admin JS live-updates the
1645 // <id>_value span on input and autosaves on change (once per
1646 // drag release, so no request storm). Range/default/clamp
1647 // unchanged — presentation only. ?>
1648 <div class="slider-container">
1649 <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">
1650 <span id="mxchat_video_embed_threshold_value" class="range-value"><?php echo esc_html((int) $video_embed_threshold); ?></span>
1651 </div>
1652 <p class="mxch-field-description"><?php
1653 /* translators: %d is the site-wide Similarity Threshold percentage. */
1654 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);
1655 ?></p>
1656 <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>
1657 </div>
1658 </div>
1659 </div>
1660 </div>
1661 <?php
1662 }
1663
1664 /**
1665 * Render Role Restrictions Section
1666 */
1667 function mxchat_render_role_restrictions_section($knowledge_manager) {
1668 // Same source as the per-entry dropdown, so the two selectors cannot drift
1669 // and both offer the site's custom roles (plan 6ab002). This screen used to
1670 // hold its own hardcoded copy of the five built-ins.
1671 $role_options = (is_object($knowledge_manager) && method_exists($knowledge_manager, 'mxchat_get_role_options'))
1672 ? $knowledge_manager->mxchat_get_role_options()
1673 : array(
1674 'public' => __('Public (Everyone)', 'mxchat'),
1675 'logged_in' => __('Logged In Users', 'mxchat'),
1676 );
1677 ?>
1678 <div id="role-restrictions" class="mxch-section">
1679 <div class="mxch-content-header">
1680 <h1 class="mxch-content-title"><?php esc_html_e('Role-Based Content Restrictions', 'mxchat'); ?></h1>
1681 <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>
1682 </div>
1683
1684 <div class="mxch-card">
1685 <div class="mxch-card-body">
1686 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1687 <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>
1688 <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>
1689 </div>
1690
1691 <h4 style="margin: 0 0 16px 0;"><?php esc_html_e('Add Tag-Role Mapping', 'mxchat'); ?></h4>
1692 <div style="display: flex; gap: 15px; align-items: flex-end; flex-wrap: wrap; margin-bottom: 24px;">
1693 <div class="mxch-field" style="flex: 1; min-width: 200px; margin-bottom: 0;">
1694 <label class="mxch-field-label" for="mxchat-tag-input"><?php esc_html_e('Tag (name or slug)', 'mxchat'); ?></label>
1695 <input type="text" id="mxchat-tag-input" class="mxch-input" placeholder="<?php esc_attr_e('e.g., Premium Content or premium-content', 'mxchat'); ?>">
1696 <span class="mxch-field-hint"><?php esc_html_e('Enter an existing post tag by its display name or its slug.', 'mxchat'); ?></span>
1697 </div>
1698 <div class="mxch-field" style="flex: 1; min-width: 200px; margin-bottom: 0;">
1699 <label class="mxch-field-label" for="mxchat-role-select"><?php esc_html_e('Required Role', 'mxchat'); ?></label>
1700 <select id="mxchat-role-select" class="mxch-select">
1701 <?php foreach ($role_options as $role_key => $role_label) : ?>
1702 <option value="<?php echo esc_attr($role_key); ?>"><?php echo esc_html($role_label); ?></option>
1703 <?php endforeach; ?>
1704 </select>
1705 </div>
1706 <button type="button" id="mxchat-add-tag-role" class="mxch-btn mxch-btn-primary">
1707 <span class="dashicons dashicons-plus-alt" style="font-size: 16px;"></span>
1708 <?php esc_html_e('Add Mapping', 'mxchat'); ?>
1709 </button>
1710 </div>
1711
1712 <h4 style="margin: 24px 0 16px 0;"><?php esc_html_e('Current Tag-Role Mappings', 'mxchat'); ?></h4>
1713 <div id="mxchat-mappings-container">
1714 <div class="mxchat-loading-mappings" style="text-align: center; padding: 20px; color: var(--mxch-text-muted);">
1715 <?php esc_html_e('Loading mappings...', 'mxchat'); ?>
1716 </div>
1717 </div>
1718 <div id="mxchat-no-mappings" style="display: none; text-align: center; padding: 40px; color: var(--mxch-text-muted);">
1719 <span class="dashicons dashicons-tag" style="font-size: 48px; opacity: 0.3;"></span>
1720 <p><?php esc_html_e('No tag-role mappings yet. Add your first mapping above.', 'mxchat'); ?></p>
1721 </div>
1722
1723 <div style="margin-top: 30px; padding-top: 24px; border-top: 1px solid var(--mxch-card-border);">
1724 <h4 style="margin: 0 0 12px 0;"><?php esc_html_e('Bulk Update Existing Content', 'mxchat'); ?></h4>
1725 <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>
1726 <button type="button" id="mxchat-bulk-update-roles" class="mxch-btn mxch-btn-secondary">
1727 <span class="dashicons dashicons-update" style="font-size: 16px;"></span>
1728 <?php esc_html_e('Update All Existing Content', 'mxchat'); ?>
1729 </button>
1730 <div id="mxchat-bulk-update-progress" style="display: none; margin-top: 15px;">
1731 <div style="height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden;">
1732 <div class="mxchat-progress-fill" style="height: 100%; background: var(--mxch-primary); width: 0%; transition: width 0.3s;"></div>
1733 </div>
1734 <p class="mxchat-progress-text" style="margin-top: 10px; color: var(--mxch-text-secondary);"><?php esc_html_e('Processing...', 'mxchat'); ?></p>
1735 </div>
1736 <div id="mxchat-bulk-update-result" style="display: none; margin-top: 15px;"></div>
1737 </div>
1738 </div>
1739 </div>
1740 </div>
1741 <?php
1742 }
1743
1744 /**
1745 * Render ACF Fields Section
1746 */
1747 function mxchat_render_acf_fields_section($knowledge_manager) {
1748 $excluded_fields = get_option('mxchat_acf_excluded_fields', array());
1749 if (!is_array($excluded_fields)) {
1750 $excluded_fields = array();
1751 }
1752 ?>
1753 <div id="acf-fields" class="mxch-section">
1754 <div class="mxch-content-header">
1755 <h1 class="mxch-content-title"><?php esc_html_e('ACF Field Settings', 'mxchat'); ?></h1>
1756 <p class="mxch-content-subtitle"><?php esc_html_e('Control which Advanced Custom Fields are included in knowledge base embeddings.', 'mxchat'); ?></p>
1757 </div>
1758
1759 <div class="mxch-card">
1760 <div class="mxch-card-body mxchat-autosave-section">
1761 <?php
1762 // Install-level ACF→PDF import extraction (plan 11720c) — moved
1763 // here from a per-import checkbox in the content-selector modal.
1764 // Default OFF, matching its own "recommended only if…" guidance.
1765 ?>
1766 <div class="mxch-field" style="margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid var(--mxch-card-border);">
1767 <div style="display: flex; align-items: center; gap: 12px;">
1768 <label class="mxchat-toggle-switch">
1769 <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'); ?>>
1770 <span class="mxchat-toggle-slider"></span>
1771 </label>
1772 <span style="font-weight: 500;"><?php esc_html_e('Extract text from PDFs linked in ACF File/Image fields during imports', 'mxchat'); ?></span>
1773 </div>
1774 <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>
1775 </div>
1776 <?php if (!function_exists('acf_get_field_groups')): ?>
1777 <div class="mxch-notice mxch-notice-info">
1778 <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>
1779 <span><?php esc_html_e('Advanced Custom Fields (ACF) plugin is not detected. Install and activate ACF to use this feature.', 'mxchat'); ?></span>
1780 </div>
1781 <?php else:
1782 $all_acf_fields = $knowledge_manager->mxchat_get_all_acf_fields();
1783
1784 if (empty($all_acf_fields)): ?>
1785 <div class="mxch-notice mxch-notice-info">
1786 <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>
1787 <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>
1788 </div>
1789 <?php else: ?>
1790 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1791 <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>
1792 <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>
1793 </div>
1794
1795 <?php foreach ($all_acf_fields as $group_key => $group):
1796 $fields = $group['fields'];
1797 // Group toggle state derives from the per-field state —
1798 // never stored on its own (plan bf57e0).
1799 $excluded_count = 0;
1800 foreach ($fields as $field) {
1801 if (in_array($field['key'], $excluded_fields, true) || in_array($field['name'], $excluded_fields, true)) {
1802 $excluded_count++;
1803 }
1804 }
1805 $group_all_included = ($excluded_count === 0);
1806 $group_partial = ($excluded_count > 0 && $excluded_count < count($fields));
1807 ?>
1808 <div class="mxchat-acf-field-group" style="margin-bottom: 24px;" data-mxchat-acf-group="<?php echo esc_attr($group_key); ?>">
1809 <div style="display: flex; align-items: center; justify-content: space-between; margin: 0 0 12px 0;">
1810 <h4 style="margin: 0; color: var(--mxch-text-primary); font-weight: 600;">
1811 <?php echo esc_html($group['title']); ?>
1812 </h4>
1813 <label class="mxchat-toggle-switch" title="<?php esc_attr_e('Include or exclude every field in this group', 'mxchat'); ?>">
1814 <input type="checkbox"
1815 class="mxchat-acf-group-toggle"
1816 data-group-key="<?php echo esc_attr($group_key); ?>"
1817 data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>"
1818 <?php if ($group_partial): ?>data-indeterminate="1"<?php endif; ?>
1819 <?php checked($group_all_included, true); ?>>
1820 <span class="mxchat-toggle-slider"></span>
1821 </label>
1822 </div>
1823 <div style="background: #f8fafc; border-radius: var(--mxch-radius-md); padding: 16px;">
1824 <?php foreach ($fields as $field):
1825 // Toggles identify fields by ACF field KEY — names are shared
1826 // across groups and collide (plan 30e81f). Legacy name entries
1827 // (group inactive at migration time) still count as excluded.
1828 $is_enabled = !in_array($field['key'], $excluded_fields, true) && !in_array($field['name'], $excluded_fields, true);
1829 ?>
1830 <div style="display: flex; align-items: center; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #e2e8f0;">
1831 <div>
1832 <span style="font-weight: 500;"><?php echo esc_html($field['label']); ?></span>
1833 <span style="color: var(--mxch-text-muted); font-size: 12px; margin-left: 8px;">(<?php echo esc_html($field['name']); ?>)</span>
1834 <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>
1835 </div>
1836 <label class="mxchat-toggle-switch">
1837 <input type="checkbox"
1838 name="mxchat_acf_field_<?php echo esc_attr($field['key']); ?>"
1839 class="mxchat-autosave-field"
1840 value="on"
1841 data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>"
1842 <?php checked($is_enabled, true); ?>>
1843 <span class="mxchat-toggle-slider"></span>
1844 </label>
1845 </div>
1846 <?php endforeach; ?>
1847 </div>
1848 </div>
1849 <?php endforeach; ?>
1850 <?php endif; ?>
1851 <?php endif; ?>
1852 </div>
1853 </div>
1854 </div>
1855 <?php
1856 }
1857
1858 /**
1859 * Render Custom Meta Section
1860 */
1861 function mxchat_render_custom_meta_section() {
1862 $whitelist = get_option('mxchat_custom_meta_whitelist', '');
1863 ?>
1864 <div id="custom-meta" class="mxch-section">
1865 <div class="mxch-content-header">
1866 <h1 class="mxch-content-title"><?php esc_html_e('Custom Post Meta', 'mxchat'); ?></h1>
1867 <p class="mxch-content-subtitle"><?php esc_html_e('Include custom post meta fields (non-ACF) in knowledge base embeddings.', 'mxchat'); ?></p>
1868 </div>
1869
1870 <div class="mxch-card">
1871 <div class="mxch-card-body mxchat-autosave-section">
1872 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1873 <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>
1874 <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>
1875 </div>
1876
1877 <!-- Meta-key discovery scanner (plan-mxchat-20260709-fe8e4e): mirror the ACF picker's
1878 discover-for-you UX for non-ACF meta, so owners click keys instead of typing them blind. -->
1879 <div class="mxch-field mxchat-meta-scan">
1880 <label class="mxch-field-label"><?php esc_html_e('Discover meta keys', 'mxchat'); ?></label>
1881 <p class="mxch-field-description" style="margin-top: 0;">
1882 <?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'); ?>
1883 </p>
1884 <div class="mxchat-meta-scan-controls">
1885 <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')); ?>">
1886 <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>
1887 <span class="mxchat-scan-label"><?php esc_html_e('Scan my content for meta keys', 'mxchat'); ?></span>
1888 </button>
1889 <label class="mxchat-meta-scan-internal">
1890 <input type="checkbox" id="mxchat-scan-internal">
1891 <?php esc_html_e('Include internal keys (underscore-prefixed)', 'mxchat'); ?>
1892 </label>
1893 </div>
1894 <div id="mxchat-meta-scan-results" class="mxchat-meta-scan-results" aria-live="polite"></div>
1895 </div>
1896
1897 <div class="mxch-field">
1898 <label class="mxch-field-label" for="mxchat_custom_meta_whitelist">
1899 <?php esc_html_e('Meta Key Whitelist', 'mxchat'); ?>
1900 </label>
1901 <textarea
1902 name="mxchat_custom_meta_whitelist"
1903 id="mxchat_custom_meta_whitelist"
1904 class="mxch-textarea mxchat-autosave-field"
1905 rows="6"
1906 placeholder="speaker_profession&#10;speaker_company&#10;event_location&#10;_custom_field_key"
1907 data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>"
1908 style="font-family: monospace;"
1909 ><?php echo esc_textarea($whitelist); ?></textarea>
1910 <p class="mxch-field-description">
1911 <?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'); ?>
1912 </p>
1913 </div>
1914
1915 <div style="margin-top: 20px; padding: 16px; background: #f8fafc; border-radius: var(--mxch-radius-md);">
1916 <h4 style="margin: 0 0 12px 0; font-size: 14px;"><?php esc_html_e('How to find meta keys:', 'mxchat'); ?></h4>
1917 <ul style="margin: 0; padding-left: 20px; color: var(--mxch-text-secondary); font-size: 13px;">
1918 <li><?php esc_html_e('Check your theme documentation for meta key names', 'mxchat'); ?></li>
1919 <li><?php esc_html_e('Look in the wp_postmeta database table', 'mxchat'); ?></li>
1920 <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>
1921 <li><?php esc_html_e('Meta keys starting with underscore (_) are usually hidden/internal', 'mxchat'); ?></li>
1922 </ul>
1923 </div>
1924 </div>
1925 </div>
1926 </div>
1927 <?php
1928 }
1929
1930 /**
1931 * Render Pinecone Section
1932 */
1933 function mxchat_render_pinecone_section() {
1934 $pinecone_options = get_option('mxchat_pinecone_addon_options', array());
1935 $use_pinecone = $pinecone_options['mxchat_use_pinecone'] ?? '0';
1936 ?>
1937 <div id="pinecone" class="mxch-section">
1938 <div class="mxch-content-header">
1939 <h1 class="mxch-content-title"><?php esc_html_e('Pinecone Vector Database', 'mxchat'); ?></h1>
1940 <p class="mxch-content-subtitle"><?php esc_html_e('Configure Pinecone for enhanced search performance with larger knowledge bases.', 'mxchat'); ?></p>
1941 </div>
1942
1943 <div class="mxch-card">
1944 <div class="mxch-card-body">
1945 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
1946 <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>
1947 <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>
1948 </div>
1949
1950 <form method="post" action="options.php">
1951 <?php settings_fields('mxchat_pinecone_addon_options'); ?>
1952
1953 <div class="mxch-field">
1954 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">
1955 <label class="mxchat-toggle-switch">
1956 <input type="checkbox" name="mxchat_pinecone_addon_options[mxchat_use_pinecone]" value="1" <?php checked($use_pinecone, '1'); ?>>
1957 <span class="mxchat-toggle-slider"></span>
1958 </label>
1959 <span style="font-weight: 500;"><?php esc_html_e('Enable Pinecone Database', 'mxchat'); ?></span>
1960 </div>
1961 </div>
1962
1963 <div class="mxchat-pinecone-settings" <?php echo $use_pinecone ? '' : 'style="display: none;"'; ?>>
1964 <?php if ($use_pinecone) : ?>
1965 <div class="mxch-notice mxch-notice-success" style="margin-bottom: 20px;">
1966 <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>
1967 <span><?php esc_html_e('Pinecone is enabled. All new knowledge base content will be stored in Pinecone.', 'mxchat'); ?></span>
1968 </div>
1969 <?php endif; ?>
1970
1971 <div class="mxch-field">
1972 <label class="mxch-field-label" for="mxchat_pinecone_api_key">
1973 <?php esc_html_e('Pinecone API Key', 'mxchat'); ?> <span class="mxch-field-label-required">*</span>
1974 </label>
1975 <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_...">
1976 <p class="mxch-field-description">
1977 <?php esc_html_e('Found in your Pinecone dashboard under API Keys.', 'mxchat'); ?>
1978 <a href="https://app.pinecone.io/" target="_blank"><?php esc_html_e('Open Pinecone Dashboard', 'mxchat'); ?></a>
1979 </p>
1980 </div>
1981
1982 <?php
1983 // Index type (plan 362c31): the classic vector index (default) or a
1984 // document index with full-text search. Same key, host and namespace.
1985 $pc_index_type = (($pinecone_options['mxchat_pinecone_index_type'] ?? 'vector') === 'document') ? 'document' : 'vector';
1986 $pc_docs_cloud = $pinecone_options['mxchat_pinecone_docs_cloud'] ?? 'aws';
1987 $pc_docs_region = $pinecone_options['mxchat_pinecone_docs_region'] ?? 'us-east-1';
1988 $pc_docs_lang = $pinecone_options['mxchat_pinecone_docs_language'] ?? 'en';
1989 $pc_verified = $pinecone_options['mxchat_pinecone_docs_verified_host'] ?? '';
1990 $pc_vector_host = $pinecone_options['mxchat_pinecone_vector_host'] ?? '';
1991 $pc_current_host = $pinecone_options['mxchat_pinecone_host'] ?? '';
1992 $pc_docs_class = class_exists('MxChat_Pinecone_Documents');
1993 $pc_expected_dim = $pc_docs_class ? MxChat_Pinecone_Documents::expected_dimension() : 1536;
1994 $pc_migration = $pc_docs_class ? MxChat_Pinecone_Documents::migration_get() : array();
1995 $pc_host_verified = ($pc_current_host !== '' && strtolower(trim($pc_current_host, '/')) === strtolower($pc_verified));
1996 $pc_clouds = $pc_docs_class ? MxChat_Pinecone_Documents::clouds() : array('aws' => 'AWS');
1997 $pc_languages = $pc_docs_class ? MxChat_Pinecone_Documents::languages() : array('en' => 'English');
1998 ?>
1999 <div class="mxch-field" id="mxchat-pinecone-index-type-field">
2000 <span class="mxch-field-label"><?php esc_html_e('Index type', 'mxchat'); ?></span>
2001 <div style="display: flex; flex-direction: column; gap: 6px; margin-top: 8px;">
2002 <label style="display: flex; align-items: baseline; gap: 8px; cursor: pointer;">
2003 <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'); ?>>
2004 <span>
2005 <strong><?php esc_html_e('Vector index (current)', 'mxchat'); ?></strong>
2006 <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>
2007 </span>
2008 </label>
2009 <label style="display: flex; align-items: baseline; gap: 8px; cursor: pointer;">
2010 <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'); ?>>
2011 <span>
2012 <strong><?php esc_html_e('Document index with full-text search (new)', 'mxchat'); ?></strong>
2013 <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>
2014 </span>
2015 </label>
2016 </div>
2017 </div>
2018 <script type="application/json" id="mxchat-pinecone-docs-state"><?php echo wp_json_encode(array(
2019 'verified_host' => $pc_verified,
2020 'expected_dimension' => (int) $pc_expected_dim,
2021 // 47c61f: the status notice's two texts, so the page can
2022 // keep it in step with the host typed in the field.
2023 'status_checked' => __('Document index checked: %1$s (%2$d dimensions).', 'mxchat'),
2024 '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'),
2025 'migration' => $pc_migration,
2026 // 3e83e4: what the LIVE chatbot is on right now, so the
2027 // page can tell a copy-in-progress from a switch.
2028 'index_type' => $pc_index_type,
2029 'stored_host' => strtolower(trim((string) $pc_current_host, '/')),
2030 'stored_index' => (string) ($pinecone_options['mxchat_pinecone_index'] ?? ''),
2031 )); ?></script>
2032
2033 <div class="mxch-field">
2034 <label class="mxch-field-label" for="mxchat_pinecone_environment"><?php esc_html_e('Region', 'mxchat'); ?></label>
2035 <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">
2036 <p class="mxch-field-description"><?php esc_html_e('Your Pinecone environment/region (e.g., gcp-starter, us-west1-gcp)', 'mxchat'); ?></p>
2037 </div>
2038
2039 <div class="mxch-field">
2040 <label class="mxch-field-label" for="mxchat_pinecone_index">
2041 <?php esc_html_e('Index Name', 'mxchat'); ?> <span class="mxch-field-label-required">*</span>
2042 </label>
2043 <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">
2044 <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>
2045 </div>
2046
2047 <div class="mxch-field">
2048 <label class="mxch-field-label" for="mxchat_pinecone_host">
2049 <?php esc_html_e('Pinecone Host', 'mxchat'); ?> <span class="mxch-field-label-required">*</span>
2050 </label>
2051 <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">
2052 <p class="mxch-field-description"><?php esc_html_e('The hostname from your Pinecone index URL (exclude https://). Found in index details.', 'mxchat'); ?></p>
2053 </div>
2054
2055 <div class="mxchat-pinecone-docs-settings" <?php echo $pc_index_type === 'document' ? '' : 'style="display: none;"'; ?>>
2056 <div class="mxch-notice <?php echo $pc_host_verified ? 'mxch-notice-success' : 'mxch-notice-warning'; ?>" id="mxchat-pinecone-docs-status" style="margin-bottom: 20px;">
2057 <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>
2058 <span id="mxchat-pinecone-docs-status-text"><?php
2059 if ($pc_host_verified) {
2060 printf(esc_html__('Document index checked: %1$s (%2$d dimensions).', 'mxchat'), esc_html($pc_verified), (int) $pc_expected_dim);
2061 } else {
2062 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');
2063 }
2064 ?></span>
2065 </div>
2066
2067 <div class="mxch-field">
2068 <label class="mxch-field-label" for="mxchat_pinecone_docs_cloud"><?php esc_html_e('Cloud and region for a new index', 'mxchat'); ?></label>
2069 <div style="display: flex; gap: 8px; flex-wrap: wrap;">
2070 <select id="mxchat_pinecone_docs_cloud" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_cloud]" class="mxch-select" style="max-width: 160px;">
2071 <?php foreach ($pc_clouds as $pc_cloud_key => $pc_cloud_label) : ?>
2072 <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>
2073 <?php endforeach; ?>
2074 </select>
2075 <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">
2076 <select id="mxchat_pinecone_docs_language" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_language]" class="mxch-select" style="max-width: 200px;">
2077 <?php foreach ($pc_languages as $pc_lang_key => $pc_lang_label) : ?>
2078 <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>
2079 <?php endforeach; ?>
2080 </select>
2081 </div>
2082 <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>
2083 </div>
2084
2085 <div class="mxch-field" style="display: flex; gap: 8px; flex-wrap: wrap;">
2086 <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-pinecone-docs-create"><?php esc_html_e('Create index for me', 'mxchat'); ?></button>
2087 <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-pinecone-docs-check"><?php esc_html_e('Check index', 'mxchat'); ?></button>
2088 </div>
2089 <div id="mxchat-pinecone-docs-result" style="display: none;"></div>
2090 <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>
2091 <div class="mxch-field" id="mxchat-pinecone-docs-switch-gate" style="display: none;">
2092 <p class="mxch-field-hint" id="mxchat-pinecone-docs-switch-gate-text"></p>
2093 <label class="mxch-field-hint" style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
2094 <input type="checkbox" id="mxchat_pinecone_docs_switch_anyway" name="mxchat_pinecone_addon_options[mxchat_pinecone_docs_switch_anyway]" value="1">
2095 <span><?php esc_html_e('Switch anyway — point the chatbot at the document index now and copy the rest afterwards', 'mxchat'); ?></span>
2096 </label>
2097 </div>
2098
2099 <div class="mxch-field" style="margin-top: 20px;">
2100 <label class="mxch-field-label" for="mxchat_pinecone_vector_host"><?php esc_html_e('Copy from vector index host', 'mxchat'); ?></label>
2101 <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">
2102 <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>
2103 </div>
2104 <div class="mxch-field" style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;">
2105 <button type="button" class="mxch-btn mxch-btn-secondary" id="mxchat-pinecone-docs-migrate"><?php esc_html_e('Migrate', 'mxchat'); ?></button>
2106 <?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. */ ?>
2107 <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'); ?>">
2108 <input type="checkbox" class="mxch-toggle-input" id="mxchat_pinecone_docs_all_namespaces" value="1">
2109 <span class="mxch-toggle-switch"></span>
2110 <span class="mxch-toggle-label"><?php esc_html_e('Copy every namespace', 'mxchat'); ?></span>
2111 </label>
2112 <span id="mxchat-pinecone-docs-migrate-counts" class="mxch-field-description"></span>
2113 </div>
2114 <div id="mxchat-pinecone-docs-migrate-progress" style="display: none; margin-bottom: 16px;">
2115 <div class="mxch-progress-bar"><div class="mxch-progress-bar-fill" style="width: 0%;"></div></div>
2116 <div class="mxch-progress-label"></div>
2117 </div>
2118
2119 <div class="mxch-field" id="mxchat-pinecone-docs-delete-old" style="display: none;">
2120 <label class="mxch-field-label" for="mxchat_pinecone_docs_delete_confirm"><?php esc_html_e('Delete old index', 'mxchat'); ?></label>
2121 <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>
2122 <div style="display: flex; gap: 8px; flex-wrap: wrap;">
2123 <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">
2124 <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>
2125 </div>
2126 </div>
2127 </div>
2128
2129 <div class="mxch-field">
2130 <label class="mxch-field-label" for="mxchat_pinecone_top_k">
2131 <?php esc_html_e('Results Per Query (topK)', 'mxchat'); ?>
2132 </label>
2133 <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">
2134 <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>
2135 </div>
2136 </div>
2137
2138 <?php submit_button(__('Save Pinecone Settings', 'mxchat'), 'primary', 'submit', true, array('class' => 'mxch-btn mxch-btn-primary')); ?>
2139 </form>
2140 </div>
2141 </div>
2142 </div>
2143 <?php
2144 }
2145
2146 /**
2147 * Render OpenAI Vector Store Section
2148 */
2149 function mxchat_render_openai_vectorstore_section() {
2150 $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
2151 $use_vectorstore = $vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0';
2152 $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? '';
2153 $max_results = $vectorstore_options['mxchat_vectorstore_max_results'] ?? 5;
2154 $sync_enabled = $vectorstore_options['mxchat_vectorstore_sync_enabled'] ?? '0';
2155 $sync_store_id = $vectorstore_options['mxchat_vectorstore_sync_store_id'] ?? '';
2156 $sync_config = class_exists('MxChat_Vectorstore_Manager') ? MxChat_Vectorstore_Manager::get_sync_config('default') : array('enabled' => false, 'store_id' => '');
2157 $mapped_count = class_exists('MxChat_Vectorstore_Manager') ? MxChat_Vectorstore_Manager::mapped_file_count() : 0;
2158
2159 // Get current chat model to check compatibility
2160 $mxchat_options = get_option('mxchat_options', array());
2161 $current_model = $mxchat_options['model'] ?? 'gpt-5.6-sol';
2162 $is_openai_model = preg_match('/^(gpt-|o1-|o3-)/', $current_model);
2163 ?>
2164 <div id="openai-vectorstore" class="mxch-section">
2165 <div class="mxch-content-header">
2166 <h1 class="mxch-content-title"><?php esc_html_e('OpenAI Vector Store', 'mxchat'); ?></h1>
2167 <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>
2168 </div>
2169
2170 <div class="mxch-card">
2171 <div class="mxch-card-body">
2172 <div class="mxch-notice mxch-notice-info" style="margin-bottom: 20px;">
2173 <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>
2174 <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>
2175 </div>
2176
2177 <?php if (!$is_openai_model && $use_vectorstore === '1'): ?>
2178 <div class="mxch-notice mxch-notice-warning" style="margin-bottom: 20px;">
2179 <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>
2180 <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>
2181 </div>
2182 <?php endif; ?>
2183
2184 <form method="post" action="options.php" id="mxchat-vectorstore-form">
2185 <?php settings_fields('mxchat_openai_vectorstore_options'); ?>
2186
2187 <div class="mxch-field">
2188 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">
2189 <label class="mxchat-toggle-switch">
2190 <input type="checkbox" name="mxchat_openai_vectorstore_options[mxchat_use_openai_vectorstore]" value="1" <?php checked($use_vectorstore, '1'); ?> id="mxchat_use_openai_vectorstore">
2191 <span class="mxchat-toggle-slider"></span>
2192 </label>
2193 <span style="font-weight: 500;"><?php esc_html_e('Enable OpenAI Vector Store', 'mxchat'); ?></span>
2194 </div>
2195 </div>
2196
2197 <div class="mxchat-vectorstore-settings" <?php echo $use_vectorstore === '1' ? '' : 'style="display: none;"'; ?>>
2198 <?php if ($use_vectorstore === '1'): ?>
2199 <div class="mxch-notice mxch-notice-success" style="margin-bottom: 20px;">
2200 <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>
2201 <span><?php esc_html_e('OpenAI Vector Store is enabled. Queries will search your Vector Store for relevant content.', 'mxchat'); ?></span>
2202 </div>
2203 <?php endif; ?>
2204
2205 <div class="mxch-field">
2206 <label class="mxch-field-label" for="mxchat_vectorstore_ids">
2207 <?php esc_html_e('Vector Store ID(s)', 'mxchat'); ?> <span class="mxch-field-label-required">*</span>
2208 </label>
2209 <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">
2210 <p class="mxch-field-description">
2211 <?php esc_html_e('Enter your Vector Store ID from the OpenAI Dashboard. For multiple stores, separate with commas.', 'mxchat'); ?>
2212 <a href="https://platform.openai.com/storage/vector_stores" target="_blank"><?php esc_html_e('Open OpenAI Vector Store Dashboard', 'mxchat'); ?></a>
2213 </p>
2214 </div>
2215
2216 <div class="mxch-field">
2217 <label class="mxch-field-label" for="mxchat_vectorstore_max_results">
2218 <?php esc_html_e('Max Results', 'mxchat'); ?>
2219 </label>
2220 <select id="mxchat_vectorstore_max_results" name="mxchat_openai_vectorstore_options[mxchat_vectorstore_max_results]" class="mxch-input" style="width: auto;">
2221 <?php for ($i = 1; $i <= 10; $i++): ?>
2222 <option value="<?php echo $i; ?>" <?php selected($max_results, $i); ?>><?php echo $i; ?></option>
2223 <?php endfor; ?>
2224 </select>
2225 <p class="mxch-field-description"><?php esc_html_e('Maximum number of content chunks to retrieve from the Vector Store.', 'mxchat'); ?></p>
2226 </div>
2227 </div>
2228
2229 <div class="mxch-field" style="border-top: 1px solid var(--mxch-border, #e2e4e7); padding-top: 20px; margin-top: 4px;">
2230 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
2231 <label class="mxchat-toggle-switch">
2232 <input type="checkbox" name="mxchat_openai_vectorstore_options[mxchat_vectorstore_sync_enabled]" value="1" <?php checked($sync_enabled, '1'); ?> id="mxchat_vectorstore_sync_enabled">
2233 <span class="mxchat-toggle-slider"></span>
2234 </label>
2235 <span style="font-weight: 500;"><?php esc_html_e('Sync Knowledge Base to Vector Store', 'mxchat'); ?></span>
2236 </div>
2237 <p class="mxch-field-description" style="margin-bottom: 16px;">
2238 <?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'); ?>
2239 </p>
2240
2241 <label class="mxch-field-label" for="mxchat_vectorstore_sync_store_id">
2242 <?php esc_html_e('Sync Target Vector Store ID', 'mxchat'); ?>
2243 </label>
2244 <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'); ?>">
2245 <p class="mxch-field-description">
2246 <?php esc_html_e('Leave blank to use the first Vector Store ID above. Syncing writes to exactly one store.', 'mxchat'); ?>
2247 </p>
2248 </div>
2249
2250 <?php submit_button(__('Save Vector Store Settings', 'mxchat'), 'primary', 'submit', true, array('class' => 'mxch-btn mxch-btn-primary')); ?>
2251 </form>
2252
2253 <?php if ($sync_config['enabled']): ?>
2254 <div class="mxch-field" id="mxchat-vs-import" style="border-top: 1px solid var(--mxch-border, #e2e4e7); padding-top: 20px;"
2255 data-nonce="<?php echo esc_attr(wp_create_nonce('mxchat_admin_nonce')); ?>">
2256 <label class="mxch-field-label"><?php esc_html_e('Import Existing Knowledge Base', 'mxchat'); ?></label>
2257 <p class="mxch-field-description">
2258 <?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>'); ?>
2259 </p>
2260 <div style="display: flex; align-items: center; gap: 8px; margin: 10px 0;">
2261 <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>
2262 <button type="button" class="mxch-btn" id="mxchat-vs-import-resume" style="display:none;"><?php esc_html_e('Resume Import', 'mxchat'); ?></button>
2263 <button type="button" class="mxch-btn" id="mxchat-vs-import-cancel" style="display:none;"><?php esc_html_e('Cancel', 'mxchat'); ?></button>
2264 </div>
2265 <div id="mxchat-vs-import-bar" style="display:none; height: 8px; background: var(--mxch-border, #e2e4e7); border-radius: 4px; overflow: hidden; max-width: 420px;">
2266 <div id="mxchat-vs-import-fill" style="height: 100%; width: 0%; background: #2271b1; transition: width .4s;"></div>
2267 </div>
2268 <p class="mxch-field-description" id="mxchat-vs-import-status" style="margin-top: 8px;"></p>
2269 </div>
2270
2271 <script>
2272 (function() {
2273 var wrap = document.getElementById('mxchat-vs-import');
2274 if (!wrap) { return; }
2275 var nonce = wrap.getAttribute('data-nonce');
2276 var startBtn = document.getElementById('mxchat-vs-import-start');
2277 var resumeBtn = document.getElementById('mxchat-vs-import-resume');
2278 var cancelBtn = document.getElementById('mxchat-vs-import-cancel');
2279 var bar = document.getElementById('mxchat-vs-import-bar');
2280 var fill = document.getElementById('mxchat-vs-import-fill');
2281 var statusEl = document.getElementById('mxchat-vs-import-status');
2282 var mappedEl = document.getElementById('mxchat-vs-mapped');
2283 var pollTimer = null;
2284
2285 function post(action, done) {
2286 var body = 'action=' + encodeURIComponent(action) + '&nonce=' + encodeURIComponent(nonce);
2287 fetch(ajaxurl, {
2288 method: 'POST',
2289 credentials: 'same-origin',
2290 headers: {'Content-Type': 'application/x-www-form-urlencoded'},
2291 body: body
2292 }).then(function(r) { return r.json(); }).then(done).catch(function() {
2293 statusEl.textContent = '<?php echo esc_js(__('Request failed — check the browser console.', 'mxchat')); ?>';
2294 });
2295 }
2296
2297 function render(state, mapped) {
2298 if (typeof mapped === 'number' && mappedEl) { mappedEl.textContent = mapped.toLocaleString(); }
2299 var running = state.status === 'running';
2300 startBtn.style.display = running ? 'none' : '';
2301 cancelBtn.style.display = running ? '' : 'none';
2302 resumeBtn.style.display = (running && state.stalled) ? '' : 'none';
2303 bar.style.display = (running || state.status === 'done') ? '' : 'none';
2304 var pct = state.total > 0 ? Math.min(100, Math.round(state.processed / state.total * 100)) : 0;
2305 if (state.status === 'done') { pct = 100; }
2306 fill.style.width = pct + '%';
2307
2308 var bits = [];
2309 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')); ?>'); }
2310 if (state.status === 'done') { bits.push('<?php echo esc_js(__('Import complete.', 'mxchat')); ?>'); }
2311 if (state.status === 'cancelled') { bits.push('<?php echo esc_js(__('Import cancelled.', 'mxchat')); ?>'); }
2312 if (state.status === 'error') { bits.push('<?php echo esc_js(__('Import error:', 'mxchat')); ?> ' + state.last_error); }
2313 if (state.status !== 'idle') {
2314 bits.push(state.processed + '/' + state.total
2315 + ' — ' + state.imported + ' <?php echo esc_js(__('uploaded', 'mxchat')); ?>'
2316 + ', ' + state.unchanged + ' <?php echo esc_js(__('unchanged', 'mxchat')); ?>'
2317 + ', ' + state.skipped_restricted + ' <?php echo esc_js(__('skipped (role-restricted)', 'mxchat')); ?>'
2318 + ', ' + state.failed + ' <?php echo esc_js(__('failed', 'mxchat')); ?>');
2319 if (state.failed > 0 && state.last_error && state.status !== 'error') {
2320 bits.push('<?php echo esc_js(__('Last error:', 'mxchat')); ?> ' + state.last_error);
2321 }
2322 }
2323 statusEl.textContent = bits.join(' ');
2324
2325 if (running && !pollTimer) {
2326 pollTimer = setInterval(function() {
2327 post('mxchat_vectorstore_import_status', function(res) {
2328 if (res && res.success) { render(res.data.state, res.data.mapped); }
2329 });
2330 }, 3000);
2331 } else if (!running && pollTimer) {
2332 clearInterval(pollTimer);
2333 pollTimer = null;
2334 }
2335 }
2336
2337 startBtn.addEventListener('click', function() {
2338 startBtn.disabled = true;
2339 statusEl.textContent = '<?php echo esc_js(__('Starting…', 'mxchat')); ?>';
2340 post('mxchat_vectorstore_import_start', function(res) {
2341 startBtn.disabled = false;
2342 if (res && res.success) { render(res.data.state); }
2343 else { statusEl.textContent = (res && res.data && res.data.message) ? res.data.message : '<?php echo esc_js(__('Could not start the import.', 'mxchat')); ?>'; }
2344 });
2345 });
2346 resumeBtn.addEventListener('click', function() {
2347 post('mxchat_vectorstore_import_resume', function(res) {
2348 if (res && res.success) { render(res.data.state); }
2349 });
2350 });
2351 cancelBtn.addEventListener('click', function() {
2352 post('mxchat_vectorstore_import_cancel', function(res) {
2353 if (res && res.success) { render(res.data.state); }
2354 });
2355 });
2356
2357 // Pick up an import already in flight when the page loads.
2358 post('mxchat_vectorstore_import_status', function(res) {
2359 if (res && res.success && res.data.state.status !== 'idle') { render(res.data.state, res.data.mapped); }
2360 });
2361 })();
2362 </script>
2363 <?php endif; ?>
2364 </div>
2365 </div>
2366 </div>
2367 <?php
2368 }
2369
2370 /**
2371 * Render Content Selector Modal
2372 */
2373 function mxchat_render_content_selector_modal() {
2374 ?>
2375 <div id="mxchat-kb-content-selector-modal" class="mxchat-kb-modal">
2376 <div class="mxchat-kb-modal-content">
2377 <div class="mxchat-kb-modal-header">
2378 <h3>
2379 <?php esc_html_e('Select WordPress Content', 'mxchat'); ?><br>
2380 <span class="mxchat-kb-header-note"><?php esc_html_e('(Content imported here will be tagged "In Knowledge Base")', 'mxchat'); ?></span>
2381 </h3>
2382 <span class="mxchat-kb-modal-close">&times;</span>
2383 </div>
2384 <div class="mxchat-kb-modal-filters">
2385 <div class="mxchat-kb-search-group">
2386 <input type="text" id="mxchat-kb-content-search" placeholder="<?php esc_attr_e('Search...', 'mxchat'); ?>">
2387 </div>
2388 <div class="mxchat-kb-filter-group">
2389 <select id="mxchat-kb-content-type-filter">
2390 <option value="all"><?php esc_html_e('All Content Types', 'mxchat'); ?></option>
2391 <option value="post"><?php esc_html_e('Posts', 'mxchat'); ?></option>
2392 <option value="page"><?php esc_html_e('Pages', 'mxchat'); ?></option>
2393 <?php
2394 $post_types = get_post_types(array('public' => true), 'objects');
2395 foreach ($post_types as $post_type) {
2396 if (!in_array($post_type->name, array('post', 'page'))) {
2397 echo '<option value="' . esc_attr($post_type->name) . '">' . esc_html($post_type->label) . '</option>';
2398 }
2399 }
2400 ?>
2401 </select>
2402 <select id="mxchat-kb-content-status-filter">
2403 <option value="publish"><?php esc_html_e('Published', 'mxchat'); ?></option>
2404 <option value="draft"><?php esc_html_e('Drafts', 'mxchat'); ?></option>
2405 <option value="all"><?php esc_html_e('All Statuses', 'mxchat'); ?></option>
2406 </select>
2407 <select id="mxchat-kb-processed-filter">
2408 <option value="all"><?php esc_html_e('All Content', 'mxchat'); ?></option>
2409 <option value="processed"><?php esc_html_e('In Knowledge Base', 'mxchat'); ?></option>
2410 <option value="unprocessed"><?php esc_html_e('Not In Knowledge Base', 'mxchat'); ?></option>
2411 </select>
2412 </div>
2413 </div>
2414 <?php
2415 // Shown only while Media is the selected type (plan 01010a). Media lists
2416 // just the files whose text MxChat can read; saying so here is clearer
2417 // than listing images and audio as rows that cannot be selected.
2418 ?>
2419 <div class="mxchat-kb-filter-note" id="mxchat-kb-media-note" hidden>
2420 <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">
2421 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
2422 <path d="M14 2v6h6"></path>
2423 </svg>
2424 <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>
2425 </div>
2426 <div class="mxchat-kb-content-selection">
2427 <div class="mxchat-kb-selection-header">
2428 <label>
2429 <input type="checkbox" id="mxchat-kb-select-all">
2430 <?php esc_html_e('Select All on Page', 'mxchat'); ?>
2431 </label>
2432 <span class="mxchat-kb-selection-count">0 <?php esc_html_e('selected', 'mxchat'); ?></span>
2433 <span class="mxchat-kb-selection-hint" style="margin-left: auto; font-size: 12px; color: var(--mxch-text-muted);">
2434 <span class="dashicons dashicons-info-outline" style="font-size: 14px; vertical-align: middle;"></span>
2435 <?php esc_html_e('Selections persist across pages', 'mxchat'); ?>
2436 </span>
2437 </div>
2438 <div class="mxchat-kb-content-list">
2439 <div class="mxchat-kb-loading">
2440 <span class="mxchat-kb-spinner is-active"></span>
2441 <?php esc_html_e('Loading content...', 'mxchat'); ?>
2442 </div>
2443 </div>
2444 </div>
2445 <div class="mxchat-kb-modal-footer">
2446 <div class="mxchat-kb-pagination"></div>
2447 <div class="mxchat-kb-footer-actions">
2448 <button type="button" id="mxchat-kb-process-selected" class="mxchat-kb-button-primary" disabled>
2449 <?php esc_html_e('Process Selected Content', 'mxchat'); ?>
2450 <span class="mxchat-kb-selected-count">(0)</span>
2451 </button>
2452 <button type="button" class="mxchat-kb-button-secondary mxchat-kb-modal-close">
2453 <?php esc_html_e('Cancel', 'mxchat'); ?>
2454 </button>
2455 </div>
2456 </div>
2457 </div>
2458 </div>
2459 <?php
2460 }
2461
2462 /**
2463 * Render Edit Entry Modal
2464 */
2465 function mxchat_render_edit_entry_modal() {
2466 ?>
2467 <div id="mxchat-kb-edit-modal" class="mxchat-kb-modal">
2468 <div class="mxchat-kb-modal-content mxchat-kb-edit-modal-content">
2469 <div class="mxchat-kb-modal-header">
2470 <h3 id="mxchat-kb-edit-title"><?php esc_html_e('Edit Knowledge Entry', 'mxchat'); ?></h3>
2471 <span class="mxchat-kb-modal-close" id="mxchat-kb-edit-close">&times;</span>
2472 </div>
2473 <div class="mxchat-kb-edit-body">
2474 <div class="mxchat-kb-edit-source" id="mxchat-kb-edit-source"></div>
2475 <textarea id="mxchat-kb-edit-textarea" class="mxchat-kb-edit-textarea" placeholder="<?php esc_attr_e('Loading content...', 'mxchat'); ?>"></textarea>
2476 <div class="mxchat-kb-edit-meta">
2477 <span id="mxchat-kb-edit-charcount"></span>
2478 <span id="mxchat-kb-edit-chunkinfo"></span>
2479 </div>
2480 </div>
2481 <div class="mxchat-kb-edit-footer">
2482 <div class="mxchat-kb-edit-notice" id="mxchat-kb-edit-notice"></div>
2483 <div class="mxchat-kb-edit-actions">
2484 <button type="button" id="mxchat-kb-edit-cancel" class="mxch-btn mxch-btn-ghost">
2485 <?php esc_html_e('Cancel', 'mxchat'); ?>
2486 </button>
2487 <button type="button" id="mxchat-kb-edit-save" class="mxch-btn mxch-btn-primary">
2488 <span class="mxchat-kb-edit-save-text"><?php esc_html_e('Save & Re-embed', 'mxchat'); ?></span>
2489 <span class="mxchat-kb-edit-save-spinner" style="display:none;">
2490 <span class="mxchat-kb-spinner is-active" style="margin: 0;"></span>
2491 <?php esc_html_e('Saving...', 'mxchat'); ?>
2492 </span>
2493 </button>
2494 </div>
2495 </div>
2496 </div>
2497 </div>
2498 <?php
2499 }
2500
2501 /**
2502 * Render the read-only Knowledge Inspector modal (plan-mxchat-20260628-d8cb4b).
2503 * Shows exactly what was indexed for an entry: the per-chunk stored text + lengths
2504 * and (for Pinecone) the stored metadata fields, rendered with the Testing tab's
2505 * own card components so the two surfaces feel like one system. Self-contained
2506 * markup + JS so it doesn't entangle the edit-modal init.
2507 */
2508 function mxchat_render_inspect_entry_modal() {
2509 ?>
2510 <div id="mxchat-kb-inspect-modal" class="mxchat-kb-modal">
2511 <div class="mxchat-kb-modal-content mxchat-kb-inspect-modal-content">
2512 <div class="mxchat-kb-modal-header">
2513 <h3 id="mxchat-kb-inspect-title"><?php esc_html_e('Indexed Content', 'mxchat'); ?></h3>
2514 <span class="mxchat-kb-modal-close" id="mxchat-kb-inspect-close">&times;</span>
2515 </div>
2516 <div class="mxchat-kb-inspect-body">
2517 <div class="mxchat-kb-edit-source" id="mxchat-kb-inspect-source"></div>
2518 <div class="mxch-testing-results" id="mxchat-kb-inspect-results">
2519 <div class="mxch-testing-no-data"><?php esc_html_e('Loading indexed content…', 'mxchat'); ?></div>
2520 </div>
2521 </div>
2522 <div class="mxchat-kb-edit-footer">
2523 <div class="mxchat-kb-edit-notice" id="mxchat-kb-inspect-notice"></div>
2524 <div class="mxchat-kb-edit-actions">
2525 <button type="button" id="mxchat-kb-inspect-close-btn" class="mxch-btn mxch-btn-primary">
2526 <?php esc_html_e('Close', 'mxchat'); ?>
2527 </button>
2528 </div>
2529 </div>
2530 </div>
2531 </div>
2532 <script>
2533 (function() {
2534 'use strict';
2535 document.addEventListener('DOMContentLoaded', function() {
2536 var modal = document.getElementById('mxchat-kb-inspect-modal');
2537 if (!modal) return;
2538 var closeX = document.getElementById('mxchat-kb-inspect-close');
2539 var closeBtn = document.getElementById('mxchat-kb-inspect-close-btn');
2540 var sourceEl = document.getElementById('mxchat-kb-inspect-source');
2541 var resultsEl= document.getElementById('mxchat-kb-inspect-results');
2542 var titleEl = document.getElementById('mxchat-kb-inspect-title');
2543 var noticeEl = document.getElementById('mxchat-kb-inspect-notice');
2544
2545 var I18N = {
2546 title: <?php echo wp_json_encode( esc_html__('Indexed Content', 'mxchat') ); ?>,
2547 loading: <?php echo wp_json_encode( esc_html__('Loading indexed content…', 'mxchat') ); ?>,
2548 manual: <?php echo wp_json_encode( esc_html__('Manual Content', 'mxchat') ); ?>,
2549 source: <?php echo wp_json_encode( esc_html__('Source', 'mxchat') ); ?>,
2550 store: <?php echo wp_json_encode( esc_html__('Storage', 'mxchat') ); ?>,
2551 type: <?php echo wp_json_encode( esc_html__('Content type', 'mxchat') ); ?>,
2552 chunksLbl:<?php echo wp_json_encode( esc_html__('Chunks', 'mxchat') ); ?>,
2553 totalLen: <?php echo wp_json_encode( esc_html__('Total indexed length', 'mxchat') ); ?>,
2554 chunk: <?php echo wp_json_encode( esc_html__('Chunk', 'mxchat') ); ?>,
2555 indexed: <?php echo wp_json_encode( esc_html__('Indexed', 'mxchat') ); ?>,
2556 chars: <?php echo wp_json_encode( esc_html__('chars', 'mxchat') ); ?>,
2557 showText: <?php echo wp_json_encode( esc_html__('Show indexed text', 'mxchat') ); ?>,
2558 hideText: <?php echo wp_json_encode( esc_html__('Hide indexed text', 'mxchat') ); ?>,
2559 wpStore: <?php echo wp_json_encode( esc_html__('Local WordPress database', 'mxchat') ); ?>,
2560 pcStore: <?php echo wp_json_encode( esc_html__('Pinecone', 'mxchat') ); ?>,
2561 meta: <?php echo wp_json_encode( esc_html__('Vector metadata', 'mxchat') ); ?>,
2562 loadFail: <?php echo wp_json_encode( esc_html__('Failed to load indexed content.', 'mxchat') ); ?>,
2563 netErr: <?php echo wp_json_encode( esc_html__('Network error: ', 'mxchat') ); ?>
2564 };
2565
2566 function esc(str) {
2567 var d = document.createElement('div');
2568 d.textContent = (str === null || str === undefined) ? '' : String(str);
2569 return d.innerHTML;
2570 }
2571 function fmt(n) { try { return Number(n).toLocaleString(); } catch (e) { return n; } }
2572
2573 document.addEventListener('click', function(e) {
2574 var btn = e.target.closest('.mxchat-inspect-entry-btn');
2575 if (btn) { e.preventDefault(); open(btn); }
2576 });
2577 if (closeX) closeX.addEventListener('click', close);
2578 if (closeBtn) closeBtn.addEventListener('click', close);
2579 // Overlay click closes, but only when the whole gesture happened on the
2580 // overlay — otherwise selecting indexed text and releasing past the
2581 // dialog edge dispatches the click on the overlay and closes it.
2582 var downOnOverlay = false;
2583 modal.addEventListener('mousedown', function(e) { downOnOverlay = (e.target === modal); });
2584 modal.addEventListener('click', function(e) {
2585 var overlayGesture = downOnOverlay;
2586 downOnOverlay = false;
2587 if (e.target === modal && overlayGesture) close();
2588 });
2589 document.addEventListener('keydown', function(e) {
2590 if (e.key === 'Escape' && modal.classList.contains('active')) close();
2591 });
2592
2593 function close() { modal.classList.remove('active'); }
2594
2595 function open(btn) {
2596 var entry = {
2597 sourceUrl: btn.getAttribute('data-source-url') || '',
2598 entryId: btn.getAttribute('data-entry-id') || '',
2599 dataSource: btn.getAttribute('data-data-source') || 'wordpress',
2600 botId: btn.getAttribute('data-bot-id') || 'default',
2601 nonce: btn.getAttribute('data-nonce') || ''
2602 };
2603
2604 titleEl.textContent = I18N.title;
2605 noticeEl.textContent = '';
2606 noticeEl.className = 'mxchat-kb-edit-notice';
2607 resultsEl.innerHTML = '<div class="mxch-testing-no-data">' + esc(I18N.loading) + '</div>';
2608
2609 if (entry.sourceUrl && entry.sourceUrl.indexOf('mxchat://') !== 0 && entry.sourceUrl.indexOf('_ungrouped_') !== 0) {
2610 sourceEl.innerHTML = esc(I18N.source) + ': <a href="' + esc(entry.sourceUrl) + '" target="_blank" rel="noopener">' + esc(entry.sourceUrl) + '</a>';
2611 } else {
2612 sourceEl.textContent = I18N.manual;
2613 }
2614
2615 modal.classList.add('active');
2616
2617 var fd = new FormData();
2618 fd.append('action', 'mxchat_inspect_entry');
2619 fd.append('nonce', entry.nonce);
2620 fd.append('source_url', entry.sourceUrl);
2621 fd.append('entry_id', entry.entryId);
2622 fd.append('data_source', entry.dataSource);
2623 fd.append('bot_id', entry.botId);
2624
2625 fetch(ajaxurl, { method: 'POST', body: fd })
2626 .then(function(r) { return r.json(); })
2627 .then(function(resp) {
2628 if (resp && resp.success) {
2629 render(resp.data);
2630 } else {
2631 var msg = (resp && resp.data && resp.data.message) || I18N.loadFail;
2632 resultsEl.innerHTML = '';
2633 showNotice(msg, 'error');
2634 }
2635 })
2636 .catch(function(err) {
2637 resultsEl.innerHTML = '';
2638 showNotice(I18N.netErr + err.message, 'error');
2639 });
2640 }
2641
2642 function render(data) {
2643 var storeLabel = data.store === 'pinecone' ? I18N.pcStore : I18N.wpStore;
2644 var html = '';
2645
2646 // Summary card — what this entry is + how much was indexed.
2647 html += '<div class="match-card above-threshold">' +
2648 '<div class="match-header">' +
2649 '<div class="match-title"><span class="status-icon">&#128230;</span> ' + esc(data.chunk_count) + ' ' + esc(I18N.chunksLbl.toLowerCase()) + '</div>' +
2650 '<span class="context-label">' + esc(storeLabel) + '</span>' +
2651 '</div>' +
2652 '<div class="mxch-testing-field"><label>' + esc(I18N.type) + '</label><code>' + esc(data.content_type || '—') + '</code> ' +
2653 '&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>';
2654 if (data.metadata_note) {
2655 html += '<div class="match-source"><span class="source-icon">&#8505;&#65039;</span> ' + esc(data.metadata_note) + '</div>';
2656 }
2657 html += '</div>';
2658
2659 // One card per stored chunk — the actual embedded text.
2660 var chunks = data.chunks || [];
2661 chunks.forEach(function(chunk, i) {
2662 var num = (chunk.index !== null && chunk.index !== undefined) ? (chunk.index + 1) : (i + 1);
2663 var metaRows = '';
2664 if (chunk.metadata && typeof chunk.metadata === 'object') {
2665 var keys = Object.keys(chunk.metadata);
2666 if (keys.length) {
2667 metaRows += '<div class="chunk-detail-row chunk-used" style="display:block;"><span class="chunk-detail-num">' + esc(I18N.meta) + '</span></div>';
2668 keys.forEach(function(k) {
2669 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>';
2670 });
2671 }
2672 }
2673 html += '<div class="match-card above-threshold">' +
2674 '<div class="match-header">' +
2675 '<div class="match-title"><span class="status-icon">&#10003;</span> ' + esc(I18N.chunk) + ' ' + esc(num) +
2676 '<span class="chunk-summary">' + esc(fmt(chunk.length)) + ' ' + esc(I18N.chars) + '</span>' +
2677 '</div>' +
2678 '<span class="context-label">' + esc(I18N.indexed) + '</span>' +
2679 '</div>' +
2680 '<span class="chunk-expand-toggle" data-chunk="' + i + '">&#9654; ' + esc(I18N.showText) + '</span>' +
2681 '<div class="chunk-details" data-chunk="' + i + '">' +
2682 '<pre class="mxch-kb-inspect-chunk-text">' + esc(chunk.text) + '</pre>' +
2683 metaRows +
2684 '</div>' +
2685 '</div>';
2686 });
2687
2688 resultsEl.innerHTML = html;
2689
2690 resultsEl.querySelectorAll('.chunk-expand-toggle').forEach(function(toggle) {
2691 toggle.addEventListener('click', function() {
2692 var id = this.getAttribute('data-chunk');
2693 var details = resultsEl.querySelector('.chunk-details[data-chunk="' + id + '"]');
2694 if (!details) return;
2695 var expanded = details.classList.toggle('expanded');
2696 this.innerHTML = (expanded ? '&#9660; ' + esc(I18N.hideText) : '&#9654; ' + esc(I18N.showText));
2697 });
2698 });
2699 }
2700
2701 function showNotice(msg, type) {
2702 noticeEl.textContent = msg;
2703 noticeEl.className = 'mxchat-kb-edit-notice' + (type ? ' ' + type : '');
2704 }
2705 });
2706 })();
2707 </script>
2708 <?php
2709 }
2710
2711 /**
2712 * Render Knowledge Page Navigation Scripts
2713 */
2714 function mxchat_render_knowledge_page_scripts() {
2715 ?>
2716 <script>
2717 (function() {
2718 'use strict';
2719
2720 // Wait for DOM
2721 document.addEventListener('DOMContentLoaded', function() {
2722 // Tab navigation + mobile menu live in the shared shell script
2723 // (js/admin-sidebar.js), enqueued for this page by plan c192a4.
2724 initImportOptions();
2725 initCustomPostTypesToggle();
2726 // Sitemap detection is now initialized when user clicks the Sitemap Import option
2727 });
2728
2729 function initImportOptions() {
2730 const importBoxes = document.querySelectorAll('.mxchat-import-box');
2731 const urlInputArea = document.getElementById('mxchat-url-input-area');
2732 const contentInputArea = document.getElementById('mxchat-content-input-area');
2733 const urlInput = document.getElementById('sitemap_url');
2734 const importTypeField = document.getElementById('import_type');
2735 const descriptionText = document.getElementById('url-description-text');
2736
2737 // Sitemap detection elements
2738 const sitemapsLoading = document.getElementById('mxchat-sitemaps-loading');
2739 const detectedSitemaps = document.getElementById('mxchat-detected-sitemaps');
2740 const noSitemaps = document.getElementById('mxchat-no-sitemaps');
2741
2742 // Helper to hide all sitemap detection UI
2743 function hideSitemapDetection() {
2744 if (sitemapsLoading) sitemapsLoading.style.display = 'none';
2745 if (detectedSitemaps) detectedSitemaps.style.display = 'none';
2746 if (noSitemaps) noSitemaps.style.display = 'none';
2747 }
2748
2749 importBoxes.forEach(box => {
2750 box.addEventListener('click', function() {
2751 const option = this.dataset.option;
2752 const type = this.dataset.type;
2753
2754 // Remove active from all boxes
2755 importBoxes.forEach(b => b.classList.remove('active'));
2756 this.classList.add('active');
2757
2758 // Handle different import types
2759 if (option === 'wordpress') {
2760 // WordPress content selector - handled by existing modal
2761 hideSitemapDetection();
2762 return;
2763 }
2764
2765 if (option === 'content') {
2766 if (urlInputArea) urlInputArea.style.display = 'none';
2767 if (contentInputArea) contentInputArea.style.display = 'block';
2768 hideSitemapDetection();
2769 } else if (type === 'sitemap' || type === 'url' || type === 'pdf') {
2770 if (contentInputArea) contentInputArea.style.display = 'none';
2771 if (urlInputArea) urlInputArea.style.display = 'block';
2772
2773 if (urlInput) {
2774 urlInput.placeholder = this.dataset.placeholder || 'Enter URL here';
2775 }
2776 if (importTypeField) {
2777 importTypeField.value = type;
2778 }
2779 if (descriptionText) {
2780 const descriptions = {
2781 'sitemap': '<?php echo esc_js(__('Use a content-specific sub-sitemap (e.g., post-sitemap.xml), not the main sitemap index.', 'mxchat')); ?>',
2782 'url': '<?php echo esc_js(__('Enter the URL of any webpage to import its content.', 'mxchat')); ?>',
2783 'pdf': '<?php echo esc_js(__('Enter the URL of a publicly accessible PDF file.', 'mxchat')); ?>'
2784 };
2785 descriptionText.textContent = descriptions[type] || '';
2786 }
2787
2788 // Only show sitemap detection when Sitemap Import is selected
2789 if (type === 'sitemap') {
2790 // Initialize sitemap detection (function is defined in knowledge-processing.js)
2791 if (typeof window.mxchatInitSitemapDetection === 'function') {
2792 window.mxchatInitSitemapDetection();
2793 }
2794 } else {
2795 hideSitemapDetection();
2796 }
2797 }
2798 });
2799 });
2800 }
2801
2802 function initCustomPostTypesToggle() {
2803 const toggleBtn = document.getElementById('mxchat-custom-post-types-toggle');
2804 const container = document.getElementById('mxchat-custom-post-types-container');
2805
2806 if (toggleBtn && container) {
2807 toggleBtn.addEventListener('click', function() {
2808 const isHidden = container.style.display === 'none';
2809 container.style.display = isHidden ? 'block' : 'none';
2810 const icon = this.querySelector('span:last-child');
2811 if (icon) {
2812 icon.textContent = isHidden ? '▲' : '▼';
2813 }
2814 });
2815 }
2816 }
2817
2818 // Sitemap detection is now handled by knowledge-processing.js
2819 // It will be initialized when user clicks "Sitemap Import" option
2820
2821 // ─── Edit Entry Modal ────────────────────────────────────
2822 initEditModal();
2823
2824 function initEditModal() {
2825 var modal = document.getElementById('mxchat-kb-edit-modal');
2826 var textarea = document.getElementById('mxchat-kb-edit-textarea');
2827 var saveBtn = document.getElementById('mxchat-kb-edit-save');
2828 var cancelBtn = document.getElementById('mxchat-kb-edit-cancel');
2829 var closeBtn = document.getElementById('mxchat-kb-edit-close');
2830 var notice = document.getElementById('mxchat-kb-edit-notice');
2831 var charCount = document.getElementById('mxchat-kb-edit-charcount');
2832 var chunkInfo = document.getElementById('mxchat-kb-edit-chunkinfo');
2833 var sourceEl = document.getElementById('mxchat-kb-edit-source');
2834 var titleEl = document.getElementById('mxchat-kb-edit-title');
2835 var saveText = saveBtn ? saveBtn.querySelector('.mxchat-kb-edit-save-text') : null;
2836 var saveSpin = saveBtn ? saveBtn.querySelector('.mxchat-kb-edit-save-spinner') : null;
2837
2838 if (!modal) return;
2839
2840 var currentEntry = {};
2841 var loadedContent = '';
2842
2843 var EDIT_I18N = {
2844 discard: <?php echo wp_json_encode( __('Discard your unsaved changes to this entry?', 'mxchat') ); ?>
2845 };
2846
2847 // Bind edit buttons (delegated)
2848 document.addEventListener('click', function(e) {
2849 var btn = e.target.closest('.mxchat-edit-entry-btn');
2850 if (btn) {
2851 e.preventDefault();
2852 openEditModal(btn);
2853 }
2854 });
2855
2856 // Close handlers. The overlay deliberately has no click-to-close: a click
2857 // fires on the common ancestor of its mousedown and mouseup, so releasing
2858 // a text-selection drag past the dialog edge targets the overlay and would
2859 // discard the edit. Closing is explicit only, and confirms when dirty.
2860 if (closeBtn) closeBtn.addEventListener('click', requestClose);
2861 if (cancelBtn) cancelBtn.addEventListener('click', requestClose);
2862 document.addEventListener('keydown', function(e) {
2863 if (e.key === 'Escape' && modal.classList.contains('active')) requestClose();
2864 });
2865
2866 // Character count
2867 if (textarea) {
2868 textarea.addEventListener('input', function() {
2869 updateCharCount();
2870 });
2871 }
2872
2873 // Save handler
2874 if (saveBtn) saveBtn.addEventListener('click', saveContent);
2875
2876 function openEditModal(btn) {
2877 currentEntry = {
2878 sourceUrl: btn.getAttribute('data-source-url') || '',
2879 entryId: btn.getAttribute('data-entry-id') || '',
2880 dataSource: btn.getAttribute('data-data-source') || 'wordpress',
2881 botId: btn.getAttribute('data-bot-id') || 'default',
2882 nonce: btn.getAttribute('data-nonce') || ''
2883 };
2884
2885 // Reset state
2886 textarea.value = '';
2887 loadedContent = '';
2888 textarea.placeholder = 'Loading content...';
2889 textarea.disabled = true;
2890 saveBtn.disabled = true;
2891 notice.textContent = '';
2892 notice.className = 'mxchat-kb-edit-notice';
2893 charCount.textContent = '';
2894 chunkInfo.textContent = '';
2895
2896 // Show source
2897 if (currentEntry.sourceUrl && currentEntry.sourceUrl.indexOf('mxchat://') !== 0) {
2898 sourceEl.innerHTML = 'Source: <a href="' + escapeHtml(currentEntry.sourceUrl) + '" target="_blank">' + escapeHtml(truncate(currentEntry.sourceUrl, 60)) + '</a>';
2899 } else {
2900 sourceEl.textContent = 'Manual Content';
2901 }
2902
2903 // Show modal
2904 modal.classList.add('active');
2905
2906 // Fetch content
2907 var formData = new FormData();
2908 formData.append('action', 'mxchat_get_entry_content');
2909 formData.append('nonce', currentEntry.nonce);
2910 formData.append('source_url', currentEntry.sourceUrl);
2911 formData.append('entry_id', currentEntry.entryId);
2912 formData.append('data_source', currentEntry.dataSource);
2913 formData.append('bot_id', currentEntry.botId);
2914
2915 fetch(ajaxurl, { method: 'POST', body: formData })
2916 .then(function(r) { return r.json(); })
2917 .then(function(resp) {
2918 if (resp.success) {
2919 textarea.value = resp.data.content || '';
2920 loadedContent = textarea.value;
2921 textarea.disabled = false;
2922 textarea.placeholder = 'Edit your content here...';
2923 saveBtn.disabled = false;
2924 currentEntry.contentType = resp.data.content_type || 'content';
2925
2926 updateCharCount();
2927
2928 if (resp.data.is_chunked) {
2929 chunkInfo.textContent = resp.data.chunk_count + ' chunks — will be re-chunked on save';
2930 titleEl.textContent = 'Edit Knowledge Entry (' + resp.data.chunk_count + ' chunks)';
2931 } else {
2932 chunkInfo.textContent = '';
2933 titleEl.textContent = 'Edit Knowledge Entry';
2934 }
2935
2936 textarea.focus();
2937 } else {
2938 textarea.placeholder = '';
2939 showNotice((resp.data && resp.data.message) || 'Failed to load content.', 'error');
2940 }
2941 })
2942 .catch(function(err) {
2943 textarea.placeholder = '';
2944 showNotice('Network error: ' + err.message, 'error');
2945 });
2946 }
2947
2948 function saveContent() {
2949 if (!textarea.value.trim()) {
2950 showNotice('Content cannot be empty.', 'error');
2951 return;
2952 }
2953
2954 saveBtn.disabled = true;
2955 if (saveText) saveText.style.display = 'none';
2956 if (saveSpin) saveSpin.style.display = '';
2957 showNotice('Saving and re-embedding...', '');
2958
2959 var formData = new FormData();
2960 formData.append('action', 'mxchat_save_entry_content');
2961 formData.append('nonce', currentEntry.nonce);
2962 formData.append('source_url', currentEntry.sourceUrl);
2963 formData.append('entry_id', currentEntry.entryId);
2964 formData.append('content', textarea.value);
2965 formData.append('data_source', currentEntry.dataSource);
2966 formData.append('bot_id', currentEntry.botId);
2967 formData.append('content_type', currentEntry.contentType || 'content');
2968
2969 fetch(ajaxurl, { method: 'POST', body: formData })
2970 .then(function(r) { return r.json(); })
2971 .then(function(resp) {
2972 if (saveText) saveText.style.display = '';
2973 if (saveSpin) saveSpin.style.display = 'none';
2974 saveBtn.disabled = false;
2975
2976 if (resp.success) {
2977 if (currentEntry.dataSource === 'pinecone') {
2978 // Pinecone list reads are eventually consistent — the reloaded
2979 // table may show the old text for up to ~60 seconds.
2980 showNotice('Saved! Pinecone changes may take up to 60 seconds to appear — use "Refresh Entries" if the list still shows the old text.', 'success');
2981 setTimeout(function() {
2982 closeModal();
2983 window.location.reload();
2984 }, 2500);
2985 } else {
2986 showNotice('Saved successfully!', 'success');
2987 setTimeout(function() {
2988 closeModal();
2989 window.location.reload();
2990 }, 1000);
2991 }
2992 } else {
2993 showNotice((resp.data && resp.data.message) || 'Save failed.', 'error');
2994 }
2995 })
2996 .catch(function(err) {
2997 if (saveText) saveText.style.display = '';
2998 if (saveSpin) saveSpin.style.display = 'none';
2999 saveBtn.disabled = false;
3000 showNotice('Network error: ' + err.message, 'error');
3001 });
3002 }
3003
3004 function isDirty() {
3005 return !textarea.disabled && textarea.value !== loadedContent;
3006 }
3007
3008 function requestClose() {
3009 if (isDirty() && !window.confirm(EDIT_I18N.discard)) return;
3010 closeModal();
3011 }
3012
3013 function closeModal() {
3014 modal.classList.remove('active');
3015 }
3016
3017 function updateCharCount() {
3018 var len = textarea.value.length;
3019 charCount.textContent = len.toLocaleString() + ' characters';
3020 }
3021
3022 function showNotice(msg, type) {
3023 notice.textContent = msg;
3024 notice.className = 'mxchat-kb-edit-notice' + (type ? ' ' + type : '');
3025 }
3026
3027 function escapeHtml(str) {
3028 var div = document.createElement('div');
3029 div.textContent = str;
3030 return div.innerHTML;
3031 }
3032
3033 function truncate(str, max) {
3034 return str.length > max ? str.substring(0, max) + '...' : str;
3035 }
3036 }
3037
3038 })();
3039 </script>
3040 <?php
3041 }
3042