1// ======================================== 2// KALRAV CHATBOT - CHAT ACTIONS (Clear, Cancel, Confirm) 3// ======================================== 4 5(function($) { 6 'use strict'; 7 8 window.KALRAV = window.KALRAV || {}; 9 window.KALRAV.ACTIONS = {}; 10 11 const CONFIG = window.KALRAV.CONFIG; 12 13 // Clear Chat Handler 14 function initializeClearChat() { 15 const confirmClearBtn = document.getElementById('confirm-clear'); 16 const cancelClearBtn = document.getElementById('cancel-clear'); 17 18 if (!confirmClearBtn || !cancelClearBtn) return; 19 20 cancelClearBtn.addEventListener('click', () => { 21 document.getElementById('clear-chat-dialog').style.display = 'none'; 22 }); 23 24 confirmClearBtn.addEventListener('click', async () => { 25 // Fire-and-forget: email session history PDF to logged-in user before clearing chat 26 try { 27 const sessionId = window.currentSessionId || sessionStorage.getItem('kalrav_session_id'); 28 29 // userEmail comes from WordPress via wp_localize_script in kalravData 30 // Make sure you add 'userEmail' => wp_get_current_user()->user_email 31 const userEmail = kalravData?.userEmail || ''; 32 const isLoggedIn = kalravData?.isLoggedIn === '1' || 33 kalravData?.isLoggedIn === true || 34 !!(window.currentUserId && 35 String(window.currentUserId) !== '0' && 36 !String(window.currentUserId).includes('_guest_')); 37 38 // Capture current chat messages before clearing 39 const chatStateMessages = window.__kalravChatState?.messages || []; 40 41 if (isLoggedIn && sessionId && userEmail && chatStateMessages.length > 0) { 42 if (window.KALRAV?.API?.emailSessionHistory) { 43 window.KALRAV.API.emailSessionHistory(sessionId, userEmail, chatStateMessages) 44 .then(result => { 45 if (result.success) { 46 //console.log('â Chat history emailed to', userEmail); 47 } else { 48 console.warn('â ï¸ Chat history email failed:', result.error); 49 } 50 }) 51 .catch(err => console.warn('â ï¸ emailSessionHistory threw:', err)); 52 } 53 } 54 } catch (err) { 55 // Non-blocking â never break the clear button 56 console.warn('â ï¸ emailSessionHistory call error (non-blocking):', err); 57 } 58 // Clean up history view if it's open 59 const historyContainer = document.getElementById('chat-history-container'); 60 if (historyContainer) historyContainer.remove(); 61 62 // Restore all scroll area children hidden by history view 63 const scrollArea = document.getElementById('chat-scroll-area'); 64 if (scrollArea) { 65 Array.from(scrollArea.children).forEach(el => { 66 if (el.dataset.historyHidden === 'true') { 67 delete el.dataset.historyHidden; 68 if (el.id !== 'contact-form-wrapper') { 69 el.style.display = ''; 70 } 71 } 72 }); 73 } 74 75 // Restore input section footer 76 const inputSection = document.getElementById('chat-input-section'); 77 if (inputSection) inputSection.style.display = 'block'; 78 79 // Hide start new chat btn and reset history toggle 80 const startNewBtn = document.getElementById('start-new-chat-btn'); 81 if (startNewBtn) startNewBtn.style.display = 'none'; 82 const historyBtn = document.getElementById('history-toggle-btn'); 83 if (historyBtn) historyBtn.classList.remove('active'); 84 const chatMessages = document.getElementById('chat-messages'); 85 const allMessages = chatMessages.querySelectorAll('.chat-message'); 86 87 // Snapshot the real logged-in user ID BEFORE anything changes it 88 const realUserId = window.currentUserId || null; 89 const isRealUser = realUserId && !String(realUserId).startsWith('guest_'); 90 91 // Reset footer menus 92 if (typeof window.KALRAV.PRODUCTS !== 'undefined') { 93 const menus = document.querySelectorAll(".product-footer-menu"); 94 if (menus.length > 0) { 95 if (menus.length > 1) {
96 menus.forEach((menu, index) => { 97 if (index !== 0) menu.remove(); 98 }); 99 } 100 const singleMenu = document.querySelector(".product-footer-menu"); 101 if (singleMenu) singleMenu.style.display = "none"; 102 const secondMenu = document.getElementById("second-footer-menu"); 103 if (secondMenu) secondMenu.style.display = "flex"; 104 } 105 } 106 107 // Remove UI extras 108 chatMessages.querySelectorAll('.chat-time,.chat-help,.history-back-arrow .user-message, .bot-message, .thumbs-container, .chat-time-res, .thumbsDown, .thumbsUp, .user-header, .user-header-response, .bot-below-row, .voice-output-btn, .feedback-prompt, .bot-reply') 109 .forEach(el => el.remove()); 110 111 allMessages.forEach(msg => { 112 if (!msg.classList.contains('init-message')) { 113 msg.remove(); 114 } 115 }); 116 117 // Stop voice activity and reset states 118 if (window.kalravVoice) { 119 window.kalravVoice.stopListening(); 120 window.kalravVoice.synthesis.cancel(); 121 window.kalravVoice.voiceInputBtn.style.color = '#673de6'; 122 window.kalravVoice.voiceOutputBtn.style.color = '#673de6'; 123 window.kalravVoice.voiceOutputBtn.style.animation = ''; 124 window.kalravVoice.voiceEnabled = false; 125 } 126 127 // Create new session via API 128 try { 129 const data = await window.KALRAV.API.createNewSession(); 130 if (data) { 131 window.currentSessionId = data.session_id || ''; 132 133 // Only use the API-returned user_id for guests. 134 // For real logged-in users, keep their existing ID â never let 135 // a session reset overwrite a real authenticated user ID. 136 if (isRealUser) { 137 window.currentUserId = realUserId; 138 } else { 139 window.currentUserId = data.user_id || ''; 140 } 141 } 142 } catch (err) { 143 console.error("Failed to create new session:", err); 144 // Restore real user ID even if session creation fails 145 if (isRealUser) { 146 window.currentUserId = realUserId; 147 } 148 } 149 150 // Clear runtime chat history and sessionStorage 151 window.__kalravChatState.historyHTML = ''; 152 window.__kalravChatState.messages = []; 153 window.__kalravChatState.messageQueries = {}; 154 if (typeof window.KALRAV.updateMenuToggleState === 'function') window.KALRAV.updateMenuToggleState(); 155 156 if ( 157 window.KALRAV.FORMS && 158 typeof window.KALRAV.FORMS.resetContactForm === 'function' 159 ) { 160 window.KALRAV.FORMS.resetContactForm(); 161 } 162 163 try { 164 sessionStorage.removeItem('kalrav_chat_history'); 165 sessionStorage.removeItem('kalrav_session_id'); 166 sessionStorage.removeItem('kalrav_message_ids'); 167 localStorage.removeItem('kalrav_cart_count'); 168 localStorage.removeItem('kalrav_cart_items'); 169 170 // Only clear user_id from storage for guests. 171 // Real users keep their ID in sessionStorage so handleUserStateChange 172 // correctly identifies them on the next interaction. 173 if (!isRealUser) { 174 sessionStorage.removeItem('kalrav_user_id'); 175 } else { 176 sessionStorage.setItem('kalrav_user_id', realUserId); 177 } 178 179 for (let key in sessionStorage) { 180 if (key.startsWith('kalrav_queries_')) { 181 sessionStorage.removeItem(key); 182 } 183 } 184 185 // ð§ Clear form submission flag only if form will be shown (SHOW_LEAD_FORM is true) 186 // If Zoho/CRM is disabled (SHOW_LEAD_FORM === false), keep the flag to ensure form stays hidden 187 const contactFormWrapper = document.getElementById('contact-form-wrapper'); 188 if (contactFormWrapper) { 189 contactFormWrapper.style.display = 'none'; 190 } 191 192 // Also restore chat content visibility in case form had gated it 193 if (window.KALRAV?.FORMS?.showContentAfterForm) { 194 window.KALRAV.FORMS.showContentAfterForm(); 195 } 196 if (window.KALRAV?.SHOW_LEAD_FORM !== false) { 197 localStorage.removeItem('kalrav_contact_form_submitted'); 198 } 199 } catch (e) {} 200 201 // Remove any existing intro/menus to avoid duplicates 202 document.querySelectorAll('.footer-intro-message').forEach(el => el.remove()); 203 const existingSecond = document.getElementById('second-footer-menu'); 204 if (existingSecond) existingSecond.remove(); 205 const existingProductFooter = document.getElementById('product-footer'); 206 if (existingProductFooter) existingProductFooter.remove(); 207 208 // ð§ After clear chat, hide the form if SHOW_LEAD_FORM is false (Zoho/CR
208M disabled) 209 if (window.KALRAV?.SHOW_LEAD_FORM === false) { 210 const formWrapper = document.getElementById('contact-form-wrapper'); 211 if (formWrapper) { 212 formWrapper.style.display = 'none'; 213 } 214 } 215 216 if (typeof window.KALRAV.showDefaultSuggestions === 'function') { 217 window.KALRAV.showDefaultSuggestions(); 218 } 219 220 if (String(CONFIG.ENABLE_PRODUCT_VIEW).trim() === "1") { 221 if (typeof window.KALRAV.PRODUCTS !== 'undefined' && typeof window.KALRAV.PRODUCTS.renderFooterMenu === 'function') { 222 window.KALRAV.PRODUCTS.renderFooterMenu(); 223 } 224 } 225 226 document.getElementById('clear-chat-dialog').style.display = 'none'; 227 228 229 const chatBox = document.getElementById('chat-box'); 230 Array.from(chatBox.children).forEach(child => { 231 child.style.filter = ''; 232 child.style.pointerEvents = ''; 233 }); 234 document.getElementById('chat-input').value = ''; 235 236}); 237 } 238 239 // Initialize on DOM Ready 240 $(document).ready(function() { 241 initializeClearChat(); 242 }); 243 244 // Export public API 245 window.KALRAV.ACTIONS = { 246 initializeClearChat 247 }; 248 249})(jQuery);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.