905 lines
31 KiB
PHP
905 lines
31 KiB
PHP
<?php $this->load->view('chat/components/message_input'); ?>
|
|
<?php $this->load->view('chat/components/attachment_modal'); ?>
|
|
|
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
|
<script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
|
|
|
|
|
|
|
|
|
|
<script>
|
|
document.addEventListener('DOMContentLoaded', function () {
|
|
const list = document.getElementById('chatList');
|
|
const chatContainer = document.querySelector('.chat-list');
|
|
const searchInput = document.querySelector('input[placeholder="Cari atau mulai chat baru..."]');
|
|
const filterBtns = document.querySelectorAll('.filter-btn');
|
|
|
|
let offset = 0;
|
|
const limit = 15;
|
|
let isLoading = false;
|
|
let hasMore = true;
|
|
let currentSearch = '';
|
|
let currentFilter = 'all';
|
|
|
|
// Fungsi bantu ambil cookie berdasarkan nama
|
|
function getCookie(name) {
|
|
const cookies = document.cookie.split('; ');
|
|
for (let c of cookies) {
|
|
const [key, value] = c.split('=');
|
|
if (key === name) return value;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function formatWhatsAppBody(text) {
|
|
if (!text) return '';
|
|
|
|
// Bold: *Text* → <b>Text</b>
|
|
text = text.replace(/\*(.*?)\*/g, '<b>$1</b>');
|
|
|
|
// Italic: _Text_ → <i>Text</i>
|
|
text = text.replace(/_(.*?)_/g, '<i>$1</i>');
|
|
|
|
// Strikethrough: ~Text~ → <s>Text</s>
|
|
text = text.replace(/~(.*?)~/g, '<s>$1</s>');
|
|
|
|
// Bisa ditambahkan formatting lain jika perlu
|
|
return text;
|
|
}
|
|
|
|
|
|
async function renderChatMessage(msg, lastDateRef, statusDate = true) {
|
|
let html = '';
|
|
|
|
const align = msg.direction === 'in' ? 'text-start' : 'text-end';
|
|
const widthMessageBox = msg.message_type === 'text' ? 'min-width: 416px; max-width: 55%' : 'width: 416px;';
|
|
const captName = msg.name === null ? 'system' : msg.name.toLowerCase();
|
|
const captMessage = msg.direction === 'in' ? 'read by ' + captName : 'send by ' + captName;
|
|
|
|
|
|
// Format waktu
|
|
const rawTime = msg.timestamp || msg.time || null;
|
|
let messageTime = '--:--';
|
|
let messageDate = '';
|
|
|
|
if (rawTime) {
|
|
const dateObj = new Date(isNaN(rawTime) ? rawTime : rawTime * 1000);
|
|
const hours = dateObj.getHours().toString().padStart(2, '0');
|
|
const minutes = dateObj.getMinutes().toString().padStart(2, '0');
|
|
messageTime = `${hours}:${minutes}`;
|
|
|
|
const options = { day: '2-digit', month: 'short', year: 'numeric' };
|
|
const formattedDate = dateObj.toLocaleDateString('id-ID', options);
|
|
|
|
if (statusDate === true) {
|
|
// Tampilkan tanggal hanya jika beda
|
|
if (formattedDate !== lastDateRef.value) {
|
|
messageDate = `<div class="text-center text-muted my-2">${formattedDate}</div>`;
|
|
lastDateRef.value = formattedDate;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Status ikon
|
|
const messageStatus = (msg.status || '').toLowerCase();
|
|
let statusIcon = '';
|
|
switch (messageStatus) {
|
|
case 'pending': statusIcon = '<i class="fa-regular fa-clock text-muted"></i>'; break;
|
|
case 'sent': statusIcon = '<i class="fa-solid fa-check text-muted"></i>'; break;
|
|
case 'delivered': statusIcon = '<i class="fa-solid fa-check-double text-muted"></i>'; break;
|
|
case 'read': statusIcon = '<i class="fa-solid fa-check-double text-primary"></i>'; break;
|
|
case 'failed': statusIcon = '<i class="fa-solid fa-circle-exclamation text-danger"></i>'; break;
|
|
case 'canceled': statusIcon = '<i class="fa-solid fa-ban text-danger"></i>'; break;
|
|
default: statusIcon = ''; break;
|
|
}
|
|
|
|
let content = '';
|
|
|
|
// === Template Message ===
|
|
if (msg.message_type === 'template') {
|
|
const payload = JSON.parse(msg.content || '{}');
|
|
|
|
|
|
try {
|
|
const res = await fetch(`<?= base_url('chat/getMessagesTemplate') ?>`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(payload)
|
|
});
|
|
const templateData = await res.json();
|
|
|
|
if (templateData.success && templateData.data) {
|
|
const t = templateData.data;
|
|
|
|
if (t.header) {
|
|
if (typeof t.header === 'string') {
|
|
// Header teks biasa
|
|
content += `<div class="template-header mb-1"><strong>${t.header}</strong></div>`;
|
|
} else if (typeof t.header === 'object' && t.header.type) {
|
|
// Header media (IMAGE, VIDEO, DOCUMENT)
|
|
switch (t.header.type) {
|
|
case 'IMAGE':
|
|
content += `
|
|
<div class="template-header mb-1">
|
|
<img src="${t.header.link}" alt="Header Image" class="img-fluid rounded">
|
|
</div>`;
|
|
break;
|
|
|
|
case 'VIDEO':
|
|
content += `
|
|
<div class="template-header mb-1">
|
|
<video src="${t.header.link}" controls class="w-100 rounded"></video>
|
|
</div>`;
|
|
break;
|
|
|
|
case 'DOCUMENT':
|
|
content += `
|
|
<div class="template-header mb-1">
|
|
<a href="${t.header.link}" target="_blank" class="btn btn-sm btn-outline-secondary">
|
|
📄 Lihat Dokumen
|
|
</a>
|
|
</div>`;
|
|
break;
|
|
|
|
default:
|
|
content += `<div class="template-header mb-1 text-muted">[Unsupported header type]</div>`;
|
|
}
|
|
}
|
|
}
|
|
|
|
content += t.body?.trim()
|
|
? `<div class="template-body mb-1">${t.body}</div>`
|
|
: `<div class="template-body text-muted mb-1">[Body kosong]</div>`;
|
|
|
|
content += `
|
|
<div class="template-footer small text-muted d-flex justify-content-between align-items-center mt-1">
|
|
<span>${t.footer || ''}</span>
|
|
<span class="d-flex align-items-center">
|
|
<small class="me-1">${messageTime}</small>
|
|
${statusIcon}
|
|
</span>
|
|
</div>`;
|
|
|
|
if (t.buttons && t.buttons.length > 0) {
|
|
content += `<div class="template-buttons mt-2">`;
|
|
t.buttons.forEach(btn => {
|
|
if (btn.type === 'URL' && btn.url) {
|
|
content += `<a href="${btn.url}" target="_blank" class="btn btn-sm btn-outline-success me-1 w-100">${btn.text}</a>`;
|
|
} else if (btn.type === 'CALL' && btn.phone_number) {
|
|
content += `<a href="tel:${btn.phone_number}" class="btn btn-sm btn-outline-success me-1">${btn.text}</a>`;
|
|
} else if (btn.type === 'quick_reply') {
|
|
content += `<button class="btn btn-sm btn-outline-secondary me-1">${btn.text}</button>`;
|
|
}
|
|
});
|
|
content += `</div>`;
|
|
}
|
|
} else {
|
|
content = `[Template tidak ditemukan]`;
|
|
}
|
|
} catch {
|
|
content = `[Gagal memuat template]`;
|
|
}
|
|
|
|
html += `
|
|
<div class="${align} mb-2" data-msg-id="${msg.id}">
|
|
<span class="d-inline-block rounded p-2 bg-light text-dark" style="${widthMessageBox}">
|
|
${content}
|
|
</span>
|
|
<p><i class="text-secondary" style="margin-left: 5px; margin-rigth: 5px; font-size: 14px">${captMessage}</i></p>
|
|
</div>`;
|
|
|
|
return messageDate + html;
|
|
}
|
|
|
|
const BASE_URL = "<?= base_url() ?>";
|
|
|
|
// === Regular Message ===
|
|
// Parse content JSON dari msg.content
|
|
let msgContent = {};
|
|
try {
|
|
msgContent = msg.content ? JSON.parse(msg.content) : {};
|
|
} catch (e) {
|
|
console.error('Gagal decode content JSON:', e);
|
|
msgContent = {};
|
|
}
|
|
|
|
// === Regular Message ===
|
|
switch (msg.message_type) {
|
|
case 'image':
|
|
content = msg.file_url
|
|
? `<img src="${BASE_URL + msg.file_url}" alt="image" class="img-fluid rounded" width="400px">
|
|
${msgContent.caption ? `<div class="template-body mb-1">${msgContent.caption}</div>` : ''}`
|
|
: `[Gambar belum diunduh]`;
|
|
break;
|
|
|
|
case 'video':
|
|
content = msg.file_url
|
|
? `<video controls class="rounded" style="width:400px;">
|
|
<source src="${BASE_URL + msg.file_url}" type="video/mp4">
|
|
Browser Anda tidak mendukung video.
|
|
</video>
|
|
${msgContent.caption ? `<div class="template-body mb-1">${msgContent.caption}</div>` : ''}`
|
|
: `[Video belum diunduh]`;
|
|
break;
|
|
|
|
case 'audio':
|
|
content = msg.file_url
|
|
? `<audio controls style="width:400px;">
|
|
<source src="${BASE_URL + msg.file_url}" type="audio/mpeg">
|
|
Browser Anda tidak mendukung audio.
|
|
</audio>`
|
|
: `[Audio belum diunduh]`;
|
|
break;
|
|
|
|
case 'document':
|
|
const filename = msgContent.filename || msg.file_name || 'Unduh Dokumen';
|
|
content = msg.file_url
|
|
? `<a href="${BASE_URL + msg.file_url}" target="_blank" class="text-decoration-none text-dark d-inline-block" style="width: 100%; max-width: 400px;">
|
|
<div style="
|
|
display: flex;
|
|
align-items: center;
|
|
border: 1px solid #ececec;
|
|
border-radius: 10px;
|
|
padding: 10px;
|
|
background-color: #f9f9f9;
|
|
width: 100%;
|
|
">
|
|
<i class="fa fa-file fa-2x me-3 text-secondary"></i>
|
|
<div style="flex-grow: 1; font-size: 14px; word-break: break-word;">
|
|
${filename}
|
|
</div>
|
|
<i class="fa fa-download ms-3 text-muted"></i>
|
|
</div>
|
|
</a>`
|
|
: `[Dokumen belum diunduh]`;
|
|
break;
|
|
|
|
case 'sticker':
|
|
content = msg.file_url
|
|
? `<img src="${BASE_URL + msg.file_url}" alt="sticker" class="rounded" width="200px" style="margin-left: 100px">`
|
|
: `[Stiker belum diunduh]`;
|
|
break;
|
|
|
|
case 'location':
|
|
content = msgContent.latitude && msgContent.longitude
|
|
? `<a href="https://www.google.com/maps?q=${msgContent.latitude},${msgContent.longitude}" target="_blank">
|
|
📍 ${msgContent.name || 'Lokasi'}<br>
|
|
${msgContent.address || ''}
|
|
</a>`
|
|
: `[Lokasi kosong]`;
|
|
break;
|
|
|
|
case 'contacts':
|
|
content = Array.isArray(msgContent)
|
|
? msgContent.map(c => `<div>👤 ${c.name || ''} - ${c.phone || ''}</div>`).join('')
|
|
: `[Kontak kosong]`;
|
|
break;
|
|
|
|
case 'button':
|
|
content = msgContent.button
|
|
? `<button class="btn btn-sm btn-primary">${msgContent.button}</button>`
|
|
: `[Tombol kosong]`;
|
|
break;
|
|
|
|
case 'interactive':
|
|
if (msgContent.button_reply) {
|
|
content = `✅ Tombol dipilih: ${msgContent.button_reply.title || ''}`;
|
|
} else if (msgContent.list_reply) {
|
|
content = `✅ List dipilih: ${msgContent.list_reply.title || ''}`;
|
|
} else {
|
|
content = `[Interaksi kosong]`;
|
|
}
|
|
break;
|
|
|
|
default:
|
|
content = msg.message_body || '[Pesan kosong]';
|
|
}
|
|
|
|
|
|
html += `
|
|
<div class="${align} mb-2" data-msg-id="${msg.id}">
|
|
<span class="d-inline-block ${msg.message_type === 'sticker' ? '' : 'rounded p-2 bg-light text-dark'}" style="${widthMessageBox}">
|
|
<span class="bubble-content text-start d-block">${formatWhatsAppBody(content)}</span>
|
|
<div class="template-footer small text-muted d-flex justify-content-between align-items-center mt-1">
|
|
<span></span>
|
|
<span class="d-flex align-items-center ${msg.message_type === 'sticker' ? 'p-2 bg-white rounded' : ''}">
|
|
<small class="me-1">${messageTime}</small>
|
|
${statusIcon}
|
|
</span>
|
|
</div>
|
|
</span>
|
|
<p><i class="text-secondary" style="margin-left: 5px; margin-rigth: 5px; font-size: 14px">${captMessage}</i></p>
|
|
</div>
|
|
`;
|
|
|
|
|
|
|
|
return messageDate + html;
|
|
}
|
|
|
|
|
|
// 🔹 Fungsi untuk ambil daftar sesi chat (20 per batch)
|
|
function fetchSessions(reset = false) {
|
|
if (isLoading || (!hasMore && !reset)) return;
|
|
isLoading = true;
|
|
|
|
if (reset) {
|
|
list.innerHTML = `
|
|
<li class="list-group-item text-center text-muted">
|
|
<div class="spinner-border spinner-border-sm"></div> Memuat chat...
|
|
</li>`;
|
|
offset = 0;
|
|
hasMore = true;
|
|
}
|
|
|
|
const params = new URLSearchParams({
|
|
whatsapp_id: `<?= $_SESSION['whatsapp_id']; ?>`,
|
|
limit,
|
|
offset,
|
|
search: currentSearch,
|
|
filter: currentFilter
|
|
});
|
|
|
|
fetch(`<?= base_url("chat/getSessions") ?>?${params}`)
|
|
.then(res => res.json())
|
|
.then(data => {
|
|
if (reset) list.innerHTML = '';
|
|
|
|
if (!data.data || data.data.length === 0) {
|
|
if (reset)
|
|
list.innerHTML = `<li class="list-group-item text-center text-muted">Tidak ada sesi aktif</li>`;
|
|
document.getElementById('btnTambahSession').style.display = 'block';
|
|
hasMore = false;
|
|
return;
|
|
}
|
|
|
|
data.data.forEach(item => {
|
|
const avatar = `https://ui-avatars.com/api/?name=${encodeURIComponent(item.customer_name || item.customer_number)}&background=random`;
|
|
const lastMessage = (item.last_message?.length > 30)
|
|
? item.last_message.substring(0, 30) + '...'
|
|
: (item.last_message || '(belum ada pesan)');
|
|
const time = item.last_message_at
|
|
? new Date(item.last_message_at).toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })
|
|
: '';
|
|
const unread = (item.status === 'open');
|
|
const unreadBadge = unread ? `<span class="badge unread"></span><br>` : '';
|
|
|
|
list.innerHTML += `
|
|
<li class="list-group-item d-flex align-items-center justify-content-between hover-item chat-item"
|
|
data-id="${item.id}"
|
|
data-name="${item.customer_name || 'Tanpa Nama'}"
|
|
data-number="${item.customer_number || '+62'}"
|
|
style="cursor:pointer;">
|
|
<div class="d-flex align-items-center">
|
|
<img src="${avatar}" class="rounded-circle me-3" width="40" height="40" alt="${item.customer_name || 'User'}">
|
|
<div>
|
|
|
|
<strong>${phoneFormat(item.customer_number)}</strong><br>
|
|
<small class="text-muted">${item.customer_name || 'Tanpa Nama'}</small>
|
|
</div>
|
|
</div>
|
|
<div style="text-align:right;">
|
|
${unreadBadge}
|
|
<small class="text-muted">${time}</small>
|
|
</div>
|
|
</li>`;
|
|
});
|
|
|
|
|
|
document.getElementById('btnTambahSession').style.display = 'none';
|
|
|
|
offset += limit;
|
|
hasMore = offset < (data.total || offset);
|
|
attachClickEvents();
|
|
})
|
|
.catch(() => {
|
|
if (reset)
|
|
list.innerHTML = `<li class="list-group-item text-danger text-center">Gagal memuat data</li>`;
|
|
document.getElementById('btnTambahSession').style.display = 'block';
|
|
})
|
|
.finally(() => isLoading = false);
|
|
}
|
|
|
|
// 🔹 Lazy load saat scroll
|
|
chatContainer.addEventListener('scroll', function () {
|
|
if (chatContainer.scrollTop + chatContainer.clientHeight >= chatContainer.scrollHeight - 50) {
|
|
fetchSessions();
|
|
}
|
|
});
|
|
|
|
// 🔹 Pencarian
|
|
// let searchTimeout;
|
|
// searchInput.addEventListener('input', function () {
|
|
// clearTimeout(searchTimeout);
|
|
// searchTimeout = setTimeout(() => {
|
|
// currentSearch = this.value.trim();
|
|
// fetchSessions(true);
|
|
// }, 400);
|
|
// });
|
|
|
|
let searchTimeout;
|
|
|
|
searchInput.addEventListener('input', function () {
|
|
clearTimeout(searchTimeout);
|
|
|
|
// 🔹 Hapus karakter non-angka
|
|
let value = this.value.replace(/\D/g, '');
|
|
|
|
// 🔹 Jika dimulai dengan 0, ubah ke format +62
|
|
if (value.startsWith('0')) {
|
|
value = '62' + value.substring(1);
|
|
}
|
|
|
|
// 🔹 Format tampilan: +62 812-3456-7890
|
|
let formatted = value;
|
|
if (formatted.startsWith('62')) {
|
|
formatted = '+62 ';
|
|
const numberPart = value.substring(2);
|
|
if (numberPart.length > 0) {
|
|
formatted += numberPart
|
|
.replace(/^(\d{3})(\d{0,4})(\d{0,4}).*/, function (_, a, b, c) {
|
|
let res = a;
|
|
if (b) res += '-' + b;
|
|
if (c) res += '-' + c;
|
|
return res;
|
|
});
|
|
}
|
|
}
|
|
|
|
this.value = formatted.trim();
|
|
|
|
// 🔹 Delay fetch agar tidak terlalu sering dipanggil
|
|
searchTimeout = setTimeout(() => {
|
|
// Ambil angka murni untuk pencarian (tanpa + dan strip)
|
|
currentSearch = value;
|
|
fetchSessions(true);
|
|
}, 400);
|
|
});
|
|
|
|
|
|
|
|
// 🔹 Filter tombol ==============================================================
|
|
filterBtns.forEach(btn => {
|
|
btn.addEventListener('click', function () {
|
|
filterBtns.forEach(b => b.classList.remove('active'));
|
|
this.classList.add('active');
|
|
currentFilter = this.textContent.includes('Belum') ? 'unread' : 'all';
|
|
fetchSessions(true);
|
|
});
|
|
});
|
|
|
|
function selectSession(sessionId) {
|
|
const sendBtn = document.getElementById('sendBtn');
|
|
const chatInputUI = document.getElementById('chatInputUI');
|
|
sendBtn.dataset.id = sessionId; // set sessionId
|
|
sendBtn.style.display = 'none'; // tampilkan tombol
|
|
chatInputUI.style.display = 'inline-flex'; // tampilkan tombol
|
|
document.getElementById('chatInput').value = ''; // reset input
|
|
}
|
|
|
|
// 🔹 Pasang ulang event klik tiap chat item (pakai style & logika asli)
|
|
function attachClickEvents() {
|
|
document.querySelectorAll('.chat-item').forEach(el => {
|
|
el.addEventListener('click', () => {
|
|
|
|
const sessionId = el.getAttribute('data-id');
|
|
const nameId = el.getAttribute('data-name');
|
|
const nameNumber = el.getAttribute('data-number');
|
|
const avatarUser = `https://ui-avatars.com/api/?name=${encodeURIComponent(nameId || nameNumber)}&background=random`;
|
|
|
|
selectSession(sessionId);
|
|
|
|
// console.log("Klik session:", sessionId);
|
|
|
|
// Cek apakah nilai sebelumnya beda
|
|
const oldSessionId = getCookie('sessionId');
|
|
|
|
if (oldSessionId !== sessionId) {
|
|
document.cookie = `sessionId=${sessionId}; path=/; max-age=${7 * 24 * 60 * 60}; SameSite=Lax`;
|
|
// console.log(`[Cookie] sessionId ${oldSessionId ? 'updated' : 'created'}: ${sessionId}`);
|
|
} else {
|
|
// console.log('[Cookie] sessionId unchanged:', sessionId);
|
|
}
|
|
|
|
// --- Semua kode kamu untuk tampilkan pesan tetap sama di sini ---
|
|
const chatWindow = document.getElementById('chatWindow');
|
|
chatWindow.innerHTML = ``;
|
|
|
|
document.getElementById('chatName').innerHTML = nameId;
|
|
document.getElementById('lastChat').innerHTML = phoneFormat(nameNumber);
|
|
document.getElementById('imageTopbar').innerHTML = `
|
|
<img src="${avatarUser}" class="rounded-circle me-3" width="40" height="40" alt="${nameId || nameNumber}">`;
|
|
|
|
function scrollToBottom() {
|
|
if (chatWindow) {
|
|
chatWindow.scrollTo({ top: chatWindow.scrollHeight, behavior: 'smooth' });
|
|
}
|
|
}
|
|
|
|
// Ambil pesan berdasarkan session
|
|
fetch(`<?= base_url('chat/getMessages/') ?>${sessionId}`)
|
|
.then(res => res.json())
|
|
.then(async data => {
|
|
if (!data.status || !data.data) {
|
|
chatWindow.innerHTML = `
|
|
<div class="text-center text-muted p-4">
|
|
Tidak ada pesan dalam sesi ini.
|
|
</div>`;
|
|
return;
|
|
}
|
|
|
|
// saat di klik load lagi sidebar nya
|
|
fetchSessions(true);
|
|
|
|
// Urutkan pesan berdasarkan timestamp (jika ada)
|
|
const sortedMessages = [...data.data].sort((a, b) => {
|
|
const t1 = new Date(isNaN(a.timestamp) ? a.timestamp : a.timestamp * 1000);
|
|
const t2 = new Date(isNaN(b.timestamp) ? b.timestamp : b.timestamp * 1000);
|
|
return t1 - t2;
|
|
});
|
|
|
|
let html = '';
|
|
let lastDate = '27 April 1996'; // catat tanggal terakhir yang sudah ditampilkan
|
|
|
|
const lastDateRef = { value: null };
|
|
|
|
for (const msg of sortedMessages) {
|
|
|
|
const htmlOutput = await renderChatMessage(msg, lastDateRef);
|
|
// console.log(msg);
|
|
chatWindow.innerHTML += htmlOutput;
|
|
}
|
|
setTimeout(scrollToBottom, 100);
|
|
})
|
|
.catch(err => {
|
|
console.error(err);
|
|
chatWindow.innerHTML = `
|
|
<div class="text-danger text-center p-4">
|
|
Gagal memuat pesan.
|
|
</div>`;
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
// === WebSocket listener ===
|
|
fetchSessions(true);
|
|
|
|
// === INIT SOCKET PALING ATAS ===
|
|
const socket = io('https://wacloud.manjapro.net', {
|
|
path: '/node-chat/socket.io/',
|
|
transports: ['websocket', 'polling']
|
|
});
|
|
|
|
socket.on('connect', () => {
|
|
socket.emit('user_login', <?= $_SESSION['whatsapp_id']; ?>);
|
|
// console.log('Wesocket connected..!');
|
|
});
|
|
|
|
const oldSessionId = getCookie('sessionId');
|
|
|
|
const notifAudio = new Audio('<?= base_url("assets/sounds/notif_1.mp3") ?>');
|
|
let audioAllowed = false;
|
|
|
|
document.addEventListener('click', () => { audioAllowed = true; });
|
|
|
|
socket.on('new_message', async (data) => {
|
|
if (!audioAllowed) return;
|
|
notifAudio.currentTime = 0;
|
|
notifAudio.play();
|
|
|
|
const oldSessionId = getCookie('sessionId');
|
|
if (data.session_id == oldSessionId) {
|
|
const chatWindow = document.getElementById('chatWindow');
|
|
const lastDateRef = { value: null };
|
|
|
|
// Parse message JSON
|
|
let msgData;
|
|
try {
|
|
msgData = typeof data.message === 'string' ? JSON.parse(data.message) : data.message;
|
|
} catch (e) {
|
|
console.error('Gagal parse JSON:', e);
|
|
msgData = data;
|
|
}
|
|
|
|
// 🧩 Tambahkan fallback: kalau name masih null, isi pakai session_id atau nilai lain
|
|
if (!msgData.name || msgData.name === null) {
|
|
msgData.name = `<?= $_SESSION['name']; ?>` || 'System';
|
|
// console.log(msgData.name);
|
|
}
|
|
|
|
// console.log(msgData);
|
|
|
|
// ✅ Tunggu hasil dari renderChatMessage
|
|
const contentNew = await renderChatMessage(msgData, lastDateRef, false);
|
|
|
|
chatWindow.innerHTML += contentNew;
|
|
|
|
setTimeout(() => {
|
|
chatWindow.scrollTo({ top: chatWindow.scrollHeight, behavior: 'smooth' });
|
|
}, 100);
|
|
|
|
fetch(`<?= base_url('chat/updateSession/') ?>${oldSessionId}`)
|
|
.then(res => res.json())
|
|
.then(data => {
|
|
if (data.status === 'success') {
|
|
fetchSessions(true);
|
|
}
|
|
// console.log(data);
|
|
});
|
|
|
|
}
|
|
else {
|
|
fetchSessions(true);
|
|
}
|
|
});
|
|
|
|
|
|
function phoneFormat(number) {
|
|
// ubah ke string dulu
|
|
let str = number.toString();
|
|
|
|
// pastikan dia mulai dengan "62"
|
|
if (!str.startsWith('62')) return number;
|
|
|
|
// hapus 62 di depan untuk diproses
|
|
str = str.slice(2);
|
|
|
|
// ambil bagian sesuai format: 3-4-4 (contoh: 858-7230-8826)
|
|
const part1 = str.slice(0, 3);
|
|
const part2 = str.slice(3, 7);
|
|
const part3 = str.slice(7);
|
|
|
|
return `+62 ${part1}-${part2}-${part3}`;
|
|
}
|
|
|
|
function playNotif() {
|
|
if (audioAllowed) {
|
|
notifAudio.play();
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
// const chatInput = document.getElementById('chatInput');
|
|
// const sendBtn = document.getElementById('sendBtn');
|
|
const emojiButtons = document.querySelectorAll('.dropdown2-menu button');
|
|
const dropdown = document.querySelector('.dropdown2');
|
|
const emojiMenu = document.querySelector('.dropdown2-menu');
|
|
const emojiToggle = document.getElementById('emojiToggle');
|
|
|
|
// Tombol Kirim muncul jika ada isi
|
|
chatInput.addEventListener('input', () => {
|
|
sendBtn.style.display = chatInput.value.trim() !== '' ? 'inline-flex' : 'none';
|
|
});
|
|
|
|
// Toggle dropdown emoji
|
|
emojiToggle.addEventListener('click', (e) => {
|
|
e.stopPropagation(); // supaya klik tombol tidak menutup dropdown
|
|
dropdown.classList.toggle('show');
|
|
});
|
|
|
|
// Klik emoji menambahkan ke textarea
|
|
emojiButtons.forEach(btn => {
|
|
btn.addEventListener('click', (e) => {
|
|
e.stopPropagation(); // penting supaya dropdown tidak hilang
|
|
const startPos = chatInput.selectionStart;
|
|
const endPos = chatInput.selectionEnd;
|
|
const textBefore = chatInput.value.substring(0, startPos);
|
|
const textAfter = chatInput.value.substring(endPos);
|
|
chatInput.value = textBefore + btn.textContent + textAfter;
|
|
|
|
const cursorPos = startPos + btn.textContent.length;
|
|
chatInput.setSelectionRange(cursorPos, cursorPos);
|
|
chatInput.focus();
|
|
|
|
chatInput.dispatchEvent(new Event('input'));
|
|
});
|
|
});
|
|
|
|
// Klik di luar dropdown menutupnya
|
|
document.addEventListener('click', (e) => {
|
|
if (!dropdown.contains(e.target)) {
|
|
dropdown.classList.remove('show');
|
|
}
|
|
});
|
|
|
|
// Auto-expand textarea
|
|
const textarea = document.querySelector('.chat-input textarea');
|
|
textarea.addEventListener('input', function() {
|
|
this.style.height = 'auto';
|
|
this.style.height = Math.min(this.scrollHeight, 1.5*10*16) + 'px';
|
|
});
|
|
|
|
// File handler
|
|
function handleFile(input) {
|
|
if (input.files.length > 0) {
|
|
alert('File terpilih: ' + input.files[0].name);
|
|
}
|
|
}
|
|
|
|
// Dropdown toggle hanya saat klik tombol
|
|
document.querySelectorAll('.dropdown2').forEach(drop => {
|
|
const btn = drop.querySelector('.chat-btn');
|
|
btn.addEventListener('click', (e) => {
|
|
e.stopPropagation();
|
|
document.querySelectorAll('.dropdown2').forEach(d => {
|
|
if(d !== drop) d.classList.remove('show');
|
|
});
|
|
drop.classList.toggle('show');
|
|
});
|
|
});
|
|
|
|
// Klik di luar menutup semua dropdown
|
|
document.addEventListener('click', () => {
|
|
document.querySelectorAll('.dropdown2').forEach(drop => drop.classList.remove('show'));
|
|
});
|
|
|
|
// Hover dropdown tetap terbuka saat mouse masuk
|
|
document.querySelectorAll('.dropdown2-menu').forEach(menu => {
|
|
menu.addEventListener('mouseenter', () => {
|
|
menu.parentElement.classList.add('show');
|
|
});
|
|
menu.addEventListener('mouseleave', () => {
|
|
menu.parentElement.classList.remove('show');
|
|
});
|
|
});
|
|
|
|
document.querySelectorAll('.dropdown2-files').forEach(menu => {
|
|
menu.addEventListener('mouseenter', () => {
|
|
menu.parentElement.classList.add('show');
|
|
});
|
|
menu.addEventListener('mouseleave', () => {
|
|
menu.parentElement.classList.remove('show');
|
|
});
|
|
});
|
|
|
|
|
|
sendBtn.addEventListener('click', sendMessageOut);
|
|
chatInput.addEventListener('keydown', function(e) {
|
|
if (e.key === 'Enter' && !e.shiftKey) {
|
|
e.preventDefault(); // cegah newline
|
|
sendMessageOut();
|
|
}
|
|
});
|
|
|
|
async function sendMessageOut() {
|
|
const sessionId = sendBtn.dataset.id;
|
|
const messageText = chatInput.value.trim();
|
|
|
|
if (!sessionId) {
|
|
alert('Session belum dipilih!');
|
|
return;
|
|
}
|
|
|
|
if (!messageText) {
|
|
alert('Pesan kosong!');
|
|
return;
|
|
}
|
|
|
|
// Data tambahan untuk log
|
|
const extraData = { user_id: 1 };
|
|
|
|
// Buat object pesan sementara untuk render awal
|
|
const tempMsg = {
|
|
id: 'temp-' + Date.now(), // id sementara unik
|
|
direction: 'out',
|
|
message_type: 'text',
|
|
message_body: messageText,
|
|
status: 'pending',
|
|
timestamp: Math.floor(Date.now() / 1000),
|
|
name: `<?= $_SESSION['name']; ?>`
|
|
};
|
|
|
|
// Render awal ke UI
|
|
appendMessageToChat(tempMsg, { value: null });
|
|
|
|
// Scroll otomatis
|
|
const chatWindow = document.getElementById('chatWindow');
|
|
chatWindow.scrollTop = chatWindow.scrollHeight;
|
|
|
|
// Reset Chat Input
|
|
document.getElementById('chatInput').value = '';
|
|
document.getElementById('sendBtn').style.display = 'none';
|
|
|
|
// Payload untuk server
|
|
const payload = { session_id: sessionId, message: messageText, ...extraData };
|
|
|
|
try {
|
|
const res = await fetch('<?= base_url(); ?>chat/sendMessageOut', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(payload)
|
|
});
|
|
const response = await res.json();
|
|
|
|
if (response.success && response.data) {
|
|
// Update pesan sementara dengan data dari server (id asli, status sent/delivered)
|
|
const msgEl = document.querySelector(`[data-msg-id="${tempMsg.id}"]`);
|
|
if (msgEl) {
|
|
msgEl.outerHTML = await renderChatMessage(response.data, { value: null }, false);
|
|
}
|
|
|
|
// Mulai polling untuk cek status read/failed
|
|
pollMessageStatus(response.data.id,sessionId);
|
|
} else {
|
|
console.error('Gagal kirim pesan:', response.message);
|
|
alert('Gagal kirim pesan: ' + response.message);
|
|
}
|
|
} catch (err) {
|
|
console.error('Error:', err);
|
|
alert('Terjadi kesalahan saat mengirim pesan.');
|
|
}
|
|
}
|
|
|
|
// Polling status pesan
|
|
async function pollMessageStatus(msgId, sessionId) {
|
|
const interval = 3000; // tiap 3 detik
|
|
|
|
const check = async () => {
|
|
const cookiesSessionId = getCookie('sessionId');
|
|
|
|
// Hentikan polling jika sessionId di cookie berbeda
|
|
if (sessionId !== cookiesSessionId) {
|
|
// console.log('Polling dihentikan karena sessionId berubah.');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const res = await fetch(`<?= base_url(); ?>chat/getMessageStatus/${msgId}`);
|
|
const json = await res.json();
|
|
|
|
if (json.status && json.data && json.data.length > 0) {
|
|
const msgData = json.data[0];
|
|
|
|
// Ubah timestamp string ke UNIX timestamp (detik)
|
|
if (msgData.timestamp && isNaN(msgData.timestamp)) {
|
|
msgData.timestamp = Math.floor(new Date(msgData.timestamp).getTime() / 1000);
|
|
}
|
|
|
|
const msgEl = document.querySelector(`[data-msg-id="${msgId}"]`);
|
|
if (msgEl) {
|
|
msgEl.outerHTML = await renderChatMessage(msgData, { value: null }, false);
|
|
}
|
|
|
|
// Stop polling jika status sudah final
|
|
const status = (msgData.status || '').toLowerCase();
|
|
if (status === 'read' || status === 'failed' || status === 'canceled') {
|
|
// console.log('Polling dihentikan karena status final:', status);
|
|
return;
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.error('Polling error:', err);
|
|
}
|
|
|
|
// Jadwalkan polling berikutnya
|
|
setTimeout(check, interval);
|
|
};
|
|
|
|
check();
|
|
}
|
|
|
|
|
|
|
|
// Fungsi render pesan ke chat window
|
|
async function appendMessageToChat(msg, lastDateRef = null) {
|
|
const chatWindow = document.getElementById('chatWindow');
|
|
|
|
// Render konten pesan
|
|
const contentNew = await renderChatMessage(msg, lastDateRef, false);
|
|
|
|
// Tambahkan ke chat window
|
|
chatWindow.innerHTML += contentNew;
|
|
|
|
// Scroll ke bawah
|
|
chatWindow.scrollTop = chatWindow.scrollHeight;
|
|
}
|
|
|
|
|
|
});
|
|
|
|
|
|
</script>
|