document.addEventListener('DOMContentLoaded', function() {
// Check if CloudPrimeChat object exists
if (typeof CloudPrimeChat === 'undefined') {
console.error('Chatbot config not loaded.');
return;
}
const chatbot = document.getElementById('cloudprime-chatbot');
const toggle = document.getElementById('chatbot-toggle');
const minimize = document.getElementById('chatbot-minimize');
const messagesContainer = document.getElementById('chatbot-messages');
const input = document.getElementById('chatbot-input');
const sendBtn = document.getElementById('chatbot-send');
const contactForm = document.getElementById('chatbot-contact-form');
const predefinedContainer = document.getElementById('chatbot-predefined');
let isOpen = false;
let sessionId = localStorage.getItem('cloudprime_chat_session') || 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
localStorage.setItem('cloudprime_chat_session', sessionId);
let contactInfo = JSON.parse(localStorage.getItem('cloudprime_contact_info')) || null;
// --- Event Listeners ---
toggle.addEventListener('click', toggleChat);
minimize.addEventListener('click', toggleChat);
sendBtn.addEventListener('click', handleSendMessage);
input.addEventListener('keypress', e => { if (e.key === 'Enter') handleSendMessage(); });
document.querySelectorAll('.predefined-question').forEach(btn => {
btn.addEventListener('click', function() {
input.value = this.getAttribute('data-question');
handleSendMessage();
});
});
document.getElementById('save-contact').addEventListener('click', handleSaveContact);
// --- Main Functions ---
function toggleChat() {
isOpen = !isOpen;
if (isOpen) {
chatbot.style.display = 'flex';
setTimeout(() => chatbot.classList.add('open'), 10); // For transition
if (messagesContainer.children.length === 0) {
initializeChat();
}
} else {
chatbot.classList.remove('open');
setTimeout(() => chatbot.style.display = 'none', 300); // Wait for transition
}
}
function initializeChat() {
if (contactInfo && contactInfo.name && contactInfo.email) {
addMessage('System', `Welcome back, ${contactInfo.name}! I'm ready to help.`, 'system');
predefinedContainer.style.display = 'flex';
} else {
addMessage(CloudPrimeChat.ai_name, 'Hello! To get started, please provide your contact details.', 'bot');
contactForm.style.display = 'block';
}
}
function handleSendMessage() {
const message = input.value.trim();
if (!message) return;
addMessage('You', message, 'user');
input.value = '';
predefinedContainer.style.display = 'none';
showTypingIndicator(true);
fetch(CloudPrimeChat.ajax_url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
action: 'cloudprime_chat',
message: message,
session_id: sessionId,
email: contactInfo ? contactInfo.email : '',
nonce: CloudPrimeChat.nonce
})
})
.then(response => response.json())
.then(data => {
showTypingIndicator(false);
if (data.success) {
addMessage(CloudPrimeChat.ai_name, data.data.message, 'bot');
if (data.data.show_whatsapp && CloudPrimeChat.whatsapp_number) {
addWhatsAppButton();
}
} else {
addMessage('System', 'Sorry, I encountered an error: ' + data.data, 'error');
}
})
.catch(error => {
showTypingIndicator(false);
addMessage('System', 'Connection error. Please check your network and try again.', 'error');
console.error('Fetch Error:', error);
});
}
function handleSaveContact() {
const name = document.getElementById('contact-name').value.trim();
const email = document.getElementById('contact-email').value.trim();
const phone = document.getElementById('contact-phone').value.trim();
if (!name || !phone || !email) {
alert('Please fill in all required fields.');
return;
}
contactInfo = { name, email, phone };
localStorage.setItem('cloudprime_contact_info', JSON.stringify(contactInfo));
fetch(CloudPrimeChat.ajax_url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
action: 'cloudprime_save_contact',
name: name,
phone: phone,
email: email,
session_id: sessionId,
nonce: CloudPrimeChat.nonce
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
addMessage('System', 'Thank you! Your details are saved. How can I help you today?', 'system');
contactForm.style.display = 'none';
predefinedContainer.style.display = 'flex';
} else {
addMessage('System', 'Sorry, there was an error saving your contact info.', 'error');
}
});
}
// --- Helper Functions ---
function addMessage(sender, message, type) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}`;
const senderDiv = document.createElement('div');
senderDiv.className = 'message-sender';
senderDiv.textContent = sender;
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
contentDiv.innerHTML = message.replace(/\n/g, '
');
messageDiv.appendChild(senderDiv);
messageDiv.appendChild(contentDiv);
messagesContainer.appendChild(messageDiv);
scrollToBottom();
}
function showTypingIndicator(show) {
const typingDiv = document.querySelector('.message.typing');
if (show && !typingDiv) {
addMessage(CloudPrimeChat.ai_name, 'Typing...', 'bot typing');
} else if (!show && typingDiv) {
typingDiv.remove();
}
}
function addWhatsAppButton() {
const whatsappDiv = document.createElement('div');
whatsappDiv.className = 'whatsapp-button-container';
whatsappDiv.innerHTML = `📱 Chat on WhatsApp`;
messagesContainer.appendChild(whatsappDiv);
scrollToBottom();
}
function scrollToBottom() {
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
});