function cleanWordEncoding(text) { if (!text) return ''; return text .replace(/•|•|\u2022/g, '*') // bullet symbols .replace(/–|—|–|—/g, '-') // dashes .replace(/’|‘|’|‘/g, "'") // single quotes .replace(/“|”|“|”/g, '"') // double quotes .replace(/[^\x00-\x7F]/g, ''); // remove other weird characters if needed } (function () { function getUserId() { let userId = localStorage.getItem('opulent_user_id'); if (!userId) { userId = 'user_' + Date.now() + '_' + Math.floor(Math.random() * 10000); localStorage.setItem('opulent_user_id', userId); } return userId; } function validateEmail(email) { const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return re.test(email); } function validatePhone(phone) { const re = /^[0-9]{10,15}$/; return re.test(phone); } function appendMessage(role, htmlContent) { const chatBody = document.getElementById("chat-body"); const bubble = document.createElement("div"); bubble.style.margin = "10px 0"; bubble.style.padding = "12px 16px"; bubble.style.maxWidth = "80%"; bubble.style.borderRadius = "12px"; bubble.style.lineHeight = "1.5"; bubble.style.wordWrap = "break-word"; bubble.style.backgroundColor = role === "user" ? "#e0f7ff" : "#f0f0f0"; bubble.style.alignSelf = role === "user" ? "flex-end" : "flex-start"; bubble.style.color = "#111"; bubble.style.fontSize = "14px"; bubble.style.marginLeft = role === "user" ? "auto" : "0"; bubble.innerHTML = htmlContent; chatBody.appendChild(bubble); // Instead of scrolling to bottom, scroll to the new message if it's from bot if (role === "bot") { bubble.scrollIntoView({ behavior: "smooth", block: "start" }); } } function formatBotResponse(text) { if (text.includes('* ')) { let paragraphs = text.split(/\n\n|\r\n\r\n/); let formattedText = ''; paragraphs.forEach((paragraph, index) => { if (!paragraph.trim()) return; if (!paragraph.trim().startsWith('*') && index === 0) { formattedText += `

${paragraph}

`; } else if (cleanWordEncoding(paragraph).includes('* ')) { let cleanedParagraph = cleanWordEncoding(paragraph); let lines = cleanedParagraph.split(/\n|\r\n/); formattedText += ''; } else { formattedText += `

${paragraph}

`; } }); return formattedText; } if (text.includes('•') || text.includes('
  • ')) { return text; } let paragraphs = text.split(/\n\n|\r\n\r\n/); let formattedText = ''; paragraphs.forEach((paragraph, index) => { if (!paragraph.trim()) return; if (paragraph.length < 80 && !paragraph.endsWith('.') && paragraphs.length > 1) { formattedText += `

    ${paragraph}

    `; } else if (paragraph.length < 40) { formattedText += `

    ${paragraph}

    `; } else { let sentences = paragraph.split(/(?<=\.|\?|\!) (?=[A-Z])/); if (sentences.length > 1) { formattedText += ''; } else { formattedText += `

    ${paragraph}

    `; } } }); return formattedText; } function sendChatMessage(message) { const userId = getUserId(); // Retrieve the user ID from localStorage const clientId = localStorage.getItem('client_id'); // Retrieve the client ID from localStorage (or wherever it's stored) const chatBody = document.getElementById("chat-body"); appendMessage("user", message); appendMessage("bot", `
    Typing...
    `); fetch("https://chat.pyot.co.in/api/askdocsopulent/", { method: "POST", headers: { "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify({ query: message, user_id: userId, client_id: clientId }) }) .then(response => { if (!response.ok) throw new Error("Network response was not ok"); return response.json(); }) .then(data => { console.log("Success:", data); chatBody.removeChild(chatBody.lastChild); const formattedAnswer = formatBotResponse(data.answer || "No response found."); appendMessage("bot", formattedAnswer); saveToDatabase(userId, clientId, message, data.answer); document.getElementById("chat-input").value = ''; }) .catch(error => { chatBody.removeChild(chatBody.lastChild); appendMessage("bot", "Error connecting to server."); console.error("[Chat Widget Error]", error); }); } function saveToDatabase(userId, clientId, question, answer) { fetch("https://opulent-foundation.com/chatbot/api/bot-chat-save", { method: "POST", headers: { "Content-Type": "application/json", "accept": "application/json" }, body: JSON.stringify({ user_id: userId, client_id: clientId, question: question, answer: answer, }) }) .then(response => response.json()) .then(data => { console.log("Data saved to database:", data); }) .catch(error => { console.error("[Database Save Error]", error); }); } function initChatWidget() { const widgetHTML = `
    Opulent Fountain Group
    Please enter your name
    Please enter a valid email
    Please enter a valid phone number (10-15 digits)
    `; document.body.insertAdjacentHTML("beforeend", widgetHTML); const toggleButton = document.getElementById("chat-toggle-button-bot"); const chatBox = document.getElementById("chat-widget-box"); const loginForm = document.getElementById("login-form"); const chatResponse = document.getElementById("chat-response"); const chatFooter = document.getElementById("chat-footer"); const loginFormContainer = document.getElementById("login-form-container"); const toggleIcon = document.getElementById("toggle-icon"); toggleButton.addEventListener("click", function () { const isHidden = window.getComputedStyle(chatBox).display === "none"; chatBox.style.display = isHidden ? "flex" : "none"; // Toggle class that controls which icon is shown toggleButton.classList.toggle("open", isHidden); }); loginForm.addEventListener("submit", function(e) { e.preventDefault(); document.querySelectorAll('.error-message').forEach(el => el.style.display = 'none'); const name = document.getElementById("userName").value.trim(); const email = document.getElementById("userEmail").value.trim(); const phone = document.getElementById("userPhone").value.trim(); const countryCode = document.getElementById('countryCode'); let isValid = true; if (!name) { document.getElementById("name-error").style.display = 'block'; isValid = false; } if (!validateEmail(email)) { document.getElementById("email-error").style.display = 'block'; isValid = false; } if (!validatePhone(phone)) { document.getElementById("phone-error").style.display = 'block'; isValid = false; } if (isValid) { localStorage.setItem('opulent_user_name', name); localStorage.setItem('opulent_user_email', email); localStorage.setItem('opulent_user_phone', phone); localStorage.setItem('opulent_user_countryCode', countryCode); // $username = localStorage.getItem('opulent_user_name'); //$("#WelcomeUserName").text($username); const userName = localStorage.getItem('opulent_user_name'); if (userName) { document.getElementById("WelcomeUserName").textContent = userName; } const formData = new FormData(); formData.append('name', name); formData.append('email', email); formData.append('phone', phone); formData.append('countryCode', document.getElementById('countryCode').value); fetch('https://opulent-foundation.com/chatbot/api/bot-save-data', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { if (data.user) { localStorage.setItem('opulent_user_id', data.user.id); localStorage.setItem('opulent_user_name', data.user.name); } console.log('Saved successfully:', data); loginFormContainer.style.display = 'none'; chatResponse.style.display = 'block'; chatFooter.style.display = 'flex'; }) .catch(error => { console.error('Error:', error); alert('Something went wrong while saving your data.'); }); } }); function validateEmail(email) { const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return re.test(email); } function validatePhone(phone) { const re = /^[0-9]{10,15}$/; return re.test(phone); } document.getElementById("chat-send-button").addEventListener("click", function () { const input = document.getElementById("chat-input"); const message = input.value.trim(); if (message) { sendChatMessage(message); input.value = ""; // Clear input immediately after sending } }); document.getElementById("chat-input").addEventListener("keypress", function(event) { if (event.key === "Enter") { const message = this.value.trim(); if (message) { sendChatMessage(message); this.value = ""; // Clear input on Enter } } }); } window.addEventListener("load", initChatWidget); })();