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

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