`;
chatMessages.style.display = 'block';
document.getElementById('user-form').style.display = 'block';
}
} else {
chatbotWindow.style.display = 'none';
overlay.style.display = 'none';
chatbotIcon.style.width = '50px';
chatbotIcon.style.height = '50px';
// resetChat();
}
}
async function startChat() {
const firstName = document.getElementById('user-first-name').value.trim();
const lastName = document.getElementById('user-last-name').value.trim();
const userPhone = document.getElementById('user-phone').value.trim();
const userEmail = document.getElementById('user-email').value.trim();
// Validate mandatory fields
if (!firstName || !lastName || !userPhone) {
alert('Please fill in all required fields (First Name, Last Name, and Phone Number)');
return;
}
// Validate phone number format
const phoneRegex = /^\d{10}$/;
if (!phoneRegex.test(userPhone.replace(/[-\s]/g, ''))) {
alert('Please enter a valid phone number');
return;
}
// Store user info
currentUserInfo = { firstName, lastName, userPhone, userEmail };
document.getElementById('user-form').style.display = 'none';
document.getElementById('chat-messages').style.display = 'block';
document.getElementById('chatbot-footer').style.display = 'block';
// Enable the message input box
document.getElementById('chatbot-input').disabled = false;
// Add the "How can I assist you today?" message
const chatMessages = document.getElementById('chat-messages');
sendMessage("Hi",currentUserInfo);
//chatMessages.innerHTML = `
//
How can I assist you today?
//`;
}
async function sendMessage(message, userInfo = null) {
const chatMessages = document.getElementById('chat-messages');
if (currentSessionId === null){
chatMessages.innerHTML = '';
}
else{
// Add user message to chat
chatMessages.innerHTML += `
${message}
`;
}
// Scroll the last message into view
const messages = chatMessages.getElementsByClassName('message');
if (messages.length > 0) {
messages[messages.length - 1].scrollIntoView({ behavior: 'smooth' });
}
const requestBody = {
session_id: currentSessionId,
topic_id: topic_id,
message: message,
user_id: user_id,
first_name: userInfo?.firstName || '',
last_name: userInfo?.lastName || '',
phone: userInfo?.userPhone || '',
email: userInfo?.userEmail || ''
};
try {
const response = await fetch('https://api.datalytique.com/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
const data = await response.json();
currentSessionId = data.session_id;
// Add bot response to chat
chatMessages.innerHTML += `
${data.message}
`;
// Scroll the bot message into view
const updatedMessages = chatMessages.getElementsByClassName('message');
if (updatedMessages.length > 0) {
updatedMessages[updatedMessages.length - 1].scrollIntoView({ behavior: 'smooth' });
}
} catch (error) {
console.error('Error sending message:', error);
}
}
function handleKeyPress(event) {
if (event.key === 'Enter') {
const input = document.getElementById('chatbot-input');
const message = input.value.trim();
if (message) {
if (currentSessionId === null)
{
sendMessage(message,currentUserInfo);
}
else{
sendMessage(message);
}
input.value = '';
}
}
}
function resetChat() {
// Reset chat-specific variables
currentSessionId = null;
selectedTopic = null;
// Reset UI elements
document.getElementById('user-form').style.display = 'none';
document.getElementById('chat-messages').style.display = 'none';
document.getElementById('chatbot-footer').style.display = 'none';
document.getElementById('chat-messages').innerHTML = '';
document.getElementById('chatbot-input').disabled = true;
document.getElementById('chatbot-input').value = '';
// If we have stored user info, populate the form
if (currentUserInfo) {
document.getElementById('user-first-name').value = currentUserInfo.firstName;
document.getElementById('user-last-name').value = currentUserInfo.lastName;
document.getElementById('user-phone').value = currentUserInfo.userPhone;
document.getElementById('user-email').value = currentUserInfo.userEmail;
const chatMessages = document.getElementById('chat-messages');
sendMessage("Hi",currentUserInfo);
//chatMessages.innerHTML = `
//
How can I assist you today?
//`;
}
}
async function closeChatbot() {
const chatbotWindow = document.getElementById('chatbot-window');
const chatbotIcon = document.getElementById('chatbot-icon');
const overlay = document.getElementById('chatbot-overlay');
// Only make the API call if there was an active session
if (currentSessionId) {
try {
const response = await fetch(`https://api.datalytique.com/api/chat/close`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
session_id: currentSessionId
})
});
if (!response.ok) {
console.error('Failed to close chat session');
}
} catch (error) {
console.error('Error closing chat session:', error);
}
}
chatbotWindow.style.display = 'none';
overlay.style.display = 'none';
chatbotIcon.style.width = '50px';
chatbotIcon.style.height = '50px';
resetChat();
}
async function initiateCall() {
if (currentUserInfo && currentUserInfo.userPhone) {
const requestBody = {
user_id: user_id,
topic_id: topic_id,
first_name: currentUserInfo?.firstName || '',
last_name: currentUserInfo?.lastName || '',
phone_number: currentUserInfo?.userPhone || '',
email: currentUserInfo?.userEmail || '',
topic_name: "PCS VOIP",
description:"PCS VOIP"
};
try {
const response = await fetch('https://api.datalytique.com/calls/single', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
console.error('Failed to close chat session');
}
} catch (error) {
console.error('Error sending message:', error);
}
console.log('Initiating call with:', currentUserInfo.userPhone);
} else {
alert('Please provide your information first to initiate a call.');
}
}
async function loadTopic() {
try {
const response = await fetch(`https://api.datalytique.com/api/chattelebot/persona/${chat_id}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to load topic');
}
const data = await response.json();
topic_id = data; // Set the global topic_id variable
console.log('Topic ID loaded:', topic_id);
} catch (error) {
console.error('Error loading topic:', error);
}
}