File size: 8,972 Bytes
8dacb57
3e3ce33
8dacb57
e359df9
3e3ce33
6b531ce
 
 
 
 
 
 
 
 
 
 
 
 
8dacb57
 
 
 
 
 
 
 
 
 
 
e1282d8
6b531ce
8dacb57
 
 
 
 
 
 
 
 
 
 
 
 
711afdf
 
 
 
 
 
 
 
8dacb57
 
 
 
 
e1282d8
6a0e04d
 
 
 
 
e1282d8
6a0e04d
 
 
e1282d8
 
6a0e04d
 
 
e359df9
 
86b1d0e
e359df9
 
 
e1282d8
3d12795
e1282d8
3d12795
 
e359df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c26dd14
e359df9
 
 
 
 
 
e1282d8
3e3ce33
 
219a309
 
e1282d8
e359df9
 
 
 
 
 
e1282d8
e359df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e4c20d
 
 
 
c26dd14
0e4c20d
 
 
 
 
6b531ce
 
0e4c20d
 
3e3ce33
e359df9
 
 
 
 
e1282d8
0e4c20d
 
 
6b531ce
c26dd14
e359df9
 
 
e1282d8
 
 
711afdf
c26dd14
e1282d8
 
711afdf
 
 
 
 
 
 
 
 
e1282d8
219a309
 
c26dd14
219a309
e1282d8
219a309
6b531ce
 
219a309
 
 
 
 
e1282d8
03096b4
e1282d8
 
 
 
 
 
 
 
 
 
 
 
 
03096b4
38031da
e1282d8
219a309
 
 
e1282d8
 
03096b4
e1282d8
 
03096b4
3e3ce33
6e72a31
03096b4
 
8dacb57
03096b4
 
0e4c20d
8dacb57
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
let conversation = [
    { role: 'bot', message: "Hi there! I'm Chat Bot! May I know your name?" }
];
let userName = ''; // To store the user's name

// Reset conversation on page load
document.addEventListener('DOMContentLoaded', () => {
    conversation = [
        { role: 'bot', message: "Hi there! I'm Chat Bot! May I know your name?" }
    ];
    const chatMessages = document.getElementById('chatMessages');
    if (chatMessages) {
        chatMessages.innerHTML = '';
        addMessage('bot', "Hi there! I'm Chat Bot! May I know your name?");
    }
    console.log('Page loaded, conversation reset:', conversation);
});

function addMessage(role, message) {
    const chatMessages = document.getElementById('chatMessages');
    if (!chatMessages) {
        console.error('Chat messages container not found!');
        return;
    }
    const messageDiv = document.createElement('div');
    messageDiv.className = role === 'bot' ? 'bot-message' : 'user-message';
    messageDiv.textContent = message;
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    console.log(`Added ${role} message: ${message}`);
    console.log('Current conversation:', conversation);
}

function sendMessage() {
    const userInput = document.getElementById('userInput');
    if (!userInput) {
        console.error('User input field not found!');
        return;
    }
    const message = userInput.value.trim();
    if (message) {
        addMessage('user', message);
        conversation.push({ role: 'user', message: message });
        userInput.value = '';
        setTimeout(() => {
            try {
                handleResponse(message);
            } catch (error) {
                console.error('Error in handleResponse:', error);
                addMessage('bot', 'Sorry, something went wrong. Please try again.');
            }
        }, 500);
    } else {
        console.warn('Empty message!');
    }
}

// Add Enter key event listener for the input field
document.addEventListener('DOMContentLoaded', () => {
    const userInput = document.getElementById('userInput');
    if (userInput) {
        userInput.addEventListener('keydown', (event) => {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault(); // Prevent default behavior (e.g., form submission)
                sendMessage();
            }
        });
    } else {
        console.error('User input field not found during initialization!');
    }
});

function displayForm() {
    const chatMessages = document.getElementById('chatMessages');
    if (!chatMessages) {
        console.error('Chat messages container not found for form!');
        return;
    }
    // Prevent duplicate forms
    if (chatMessages.querySelector('.registration-form')) {
        console.log('Form already exists, skipping display.');
        return;
    }
    const formDiv = document.createElement('div');
    formDiv.className = 'bot-message';
    formDiv.innerHTML = `
        <p>Please register here with these details. Our service agent will get back to you soon.</p>
        <div class="registration-form">
            <label for="mobileNumber">Mobile Number:</label>
            <input type="text" id="mobileNumber" placeholder="Enter your mobile number" /><br/>
            <label for="email">Email:</label>
            <input type="email" id="email" placeholder="Enter your email" /><br/>
            <label for="issueDescription">Issue Description:</label>
            <textarea id="issueDescription" placeholder="Describe your issue"></textarea><br/>
            <button onclick="submitForm()">Submit</button>
        </div>
    `;
    chatMessages.appendChild(formDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    console.log('Form displayed successfully.');
}

function submitForm() {
    const mobileNumber = document.getElementById('mobileNumber').value.trim();
    const email = document.getElementById('email').value.trim();
    const issueDescription = document.getElementById('issueDescription').value.trim();

    if (!mobileNumber || !email || !issueDescription) {
        addMessage('bot', 'Please fill in all fields before submitting.');
        return;
    }

    const formData = {
        name: userName,
        mobileNumber: mobileNumber,
        email: email,
        issueDescription: issueDescription
    };

    fetch('/submit-case', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            addMessage('bot', 'Thank you! Your case has been submitted. Our service agent will get back to you soon.');
        } else {
            addMessage('bot', 'There was an error submitting your case. Please try again later.');
        }
    })
    .catch(error => {
        console.error('Error submitting form:', error);
        addMessage('bot', 'There was an error submitting your case. Please try again later.');
    });
}

function clearOptions() {
    const chatMessages = document.getElementById('chatMessages');
    if (!chatMessages) return;
    const optionButtons = chatMessages.querySelectorAll('.bot-message .option-button');
    console.log(`Clearing ${optionButtons.length} existing option buttons.`);
    optionButtons.forEach(button => {
        if (button.parentElement) {
            button.parentElement.remove();
        }
    });
    // Log the current DOM state after clearing
    console.log('DOM after clearing options:', chatMessages.innerHTML);
}

function displayOptions(options, isCategory = false) {
    const chatMessages = document.getElementById('chatMessages');
    if (!chatMessages) {
        console.error('Chat messages container not found for options!');
        return;
    }

    // Clear existing options before displaying new ones
    clearOptions();

    console.log(`Displaying ${options.length} options:`, options);
    options.forEach((opt, index) => {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'bot-message';
        const button = document.createElement('button');
        button.textContent = opt.text;
        button.className = `option-button ${opt.class}`;

        button.addEventListener('click', () => {
            console.log(`Button clicked: ${opt.text}`);
            addMessage('user', opt.text);
            conversation.push({ role: 'user', message: opt.text });
            setTimeout(() => {
                try {
                    handleResponse(opt.text);
                } catch (error) {
                    console.error('Error in handleResponse after button click:', error);
                    addMessage('bot', 'Sorry, something went wrong. Please try again.');
                }
            }, 500);
        });

        messageDiv.appendChild(button);
        chatMessages.appendChild(messageDiv);
        console.log(`Added button ${index + 1}: ${opt.text}`);
    });

    chatMessages.scrollTop = chatMessages.scrollHeight;
    // Log the DOM state after adding options
    console.log('DOM after adding options:', chatMessages.innerHTML);
}

function handleResponse(userInput) {
    const lastMessage = conversation[conversation.length - 1].message.toLowerCase();
    let botResponse = '';

    // Define categories
    const categories = [
        { text: 'About TioNat and Account Setup', class: 'blue' },
        { text: 'Nutritional Supplements', class: 'blue' },
        { text: 'Health Care Products', class: 'blue' },
        { text: 'Personal Care and Skincare', class: 'blue' },
        { text: 'Returns and Customer Support', class: 'blue' },
        { text: 'Security and Account Management', class: 'blue' },
        { text: 'Other', class: 'green' }
    ];

    // Handle name input (first user response after bot's greeting)
    if (conversation.length === 2 && conversation[0].role === 'bot' && conversation[0].message.includes('May I know your name?')) {
        userName = userInput; // Store the user's name
        botResponse = `Nice to meet you, ${userInput}! 😊 Please select a category for your query:`;
        addMessage('bot', botResponse);
        displayOptions(categories, true); // Display category buttons
        return;
    }

    // Handle category selection
    if (categories.some(cat => cat.text.toLowerCase() === lastMessage)) {
        botResponse = `Thank you for selecting "${userInput}". Please provide more details about your query so our service agent can assist you.`;
        addMessage('bot', botResponse);
        displayForm();
        return;
    }

    // Handle unrecognized input
    botResponse = "I'm sorry, I don't understand your query. Please select a category for your query:";
    addMessage('bot', botResponse);
    if (!document.querySelector('.option-button')) {
        displayOptions(categories, true);
    }
}