717 lines
25 KiB
PHP
717 lines
25 KiB
PHP
<!DOCTYPE html>
|
|
<html lang="es">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>💬 Conversaciones - WhatsApp Bot</title>
|
|
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
|
|
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
|
|
<style>
|
|
:root {
|
|
--whatsapp-green: #25d366;
|
|
--whatsapp-green-dark: #128c7e;
|
|
--whatsapp-light: #dcf8c6;
|
|
--whatsapp-dark: #075e54;
|
|
--message-bg: #f0f0f0;
|
|
--sidebar-bg: #f8f9fa;
|
|
}
|
|
|
|
body {
|
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
|
|
background: #e5ddd5;
|
|
margin: 0;
|
|
height: 100vh;
|
|
overflow: hidden;
|
|
}
|
|
|
|
.chat-container {
|
|
display: flex;
|
|
height: 100vh;
|
|
background: white;
|
|
}
|
|
|
|
.chat-sidebar {
|
|
width: 350px;
|
|
background: var(--sidebar-bg);
|
|
border-right: 1px solid #e1e5e9;
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
|
|
.sidebar-header {
|
|
padding: 20px;
|
|
background: var(--whatsapp-dark);
|
|
color: white;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: space-between;
|
|
}
|
|
|
|
.sidebar-search {
|
|
padding: 10px 20px;
|
|
background: white;
|
|
border-bottom: 1px solid #e1e5e9;
|
|
}
|
|
|
|
.conversation-list {
|
|
flex: 1;
|
|
overflow-y: auto;
|
|
}
|
|
|
|
.conversation-item {
|
|
padding: 15px 20px;
|
|
border-bottom: 1px solid #f1f1f1;
|
|
cursor: pointer;
|
|
transition: background-color 0.2s;
|
|
display: flex;
|
|
align-items: center;
|
|
}
|
|
|
|
.conversation-item:hover {
|
|
background: #f5f5f5;
|
|
}
|
|
|
|
.conversation-item.active {
|
|
background: #e3f2fd;
|
|
border-right: 3px solid var(--whatsapp-green);
|
|
}
|
|
|
|
.conversation-avatar {
|
|
width: 50px;
|
|
height: 50px;
|
|
border-radius: 50%;
|
|
background: var(--whatsapp-green);
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
color: white;
|
|
font-weight: bold;
|
|
margin-right: 15px;
|
|
flex-shrink: 0;
|
|
}
|
|
|
|
.conversation-info {
|
|
flex: 1;
|
|
min-width: 0;
|
|
}
|
|
|
|
.conversation-name {
|
|
font-weight: 600;
|
|
font-size: 16px;
|
|
color: #333;
|
|
margin-bottom: 5px;
|
|
}
|
|
|
|
.conversation-preview {
|
|
color: #666;
|
|
font-size: 14px;
|
|
white-space: nowrap;
|
|
overflow: hidden;
|
|
text-overflow: ellipsis;
|
|
}
|
|
|
|
.conversation-time {
|
|
color: #999;
|
|
font-size: 12px;
|
|
text-align: right;
|
|
flex-shrink: 0;
|
|
margin-left: 10px;
|
|
}
|
|
|
|
.chat-main {
|
|
flex: 1;
|
|
display: flex;
|
|
flex-direction: column;
|
|
background: #e5ddd5;
|
|
}
|
|
|
|
.chat-header {
|
|
padding: 15px 20px;
|
|
background: var(--whatsapp-dark);
|
|
color: white;
|
|
border-bottom: 1px solid #ddd;
|
|
display: flex;
|
|
align-items: center;
|
|
}
|
|
|
|
.chat-header-avatar {
|
|
width: 40px;
|
|
height: 40px;
|
|
border-radius: 50%;
|
|
background: var(--whatsapp-green);
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
color: white;
|
|
font-weight: bold;
|
|
margin-right: 15px;
|
|
}
|
|
|
|
.chat-header-info h6 {
|
|
margin: 0;
|
|
font-size: 16px;
|
|
}
|
|
|
|
.chat-header-info small {
|
|
color: #ccc;
|
|
}
|
|
|
|
.chat-messages {
|
|
flex: 1;
|
|
overflow-y: auto;
|
|
padding: 20px;
|
|
background: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGRlZnM+CjxwYXR0ZXJuIGlkPSJ3aGF0c2FwcC1iZyIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiPgo8cG9seWdvbiBmaWxsPSJyZ2JhKDIyOSwyMjEsMjEzLDAuMSkiIHBvaW50cz0iMCwwIDEwMCwwIDEwMCwxMDAgMCwxMDAiLz4KPGV+';
|
|
}
|
|
|
|
.message {
|
|
max-width: 70%;
|
|
margin-bottom: 10px;
|
|
display: flex;
|
|
}
|
|
|
|
.message.outgoing {
|
|
justify-content: flex-end;
|
|
}
|
|
|
|
.message.incoming {
|
|
justify-content: flex-start;
|
|
}
|
|
|
|
.message-bubble {
|
|
padding: 8px 12px;
|
|
border-radius: 18px;
|
|
position: relative;
|
|
word-wrap: break-word;
|
|
box-shadow: 0 1px 1px rgba(0,0,0,0.1);
|
|
}
|
|
|
|
.message.outgoing .message-bubble {
|
|
background: var(--whatsapp-light);
|
|
color: #333;
|
|
border-bottom-right-radius: 4px;
|
|
}
|
|
|
|
.message.incoming .message-bubble {
|
|
background: white;
|
|
color: #333;
|
|
border-bottom-left-radius: 4px;
|
|
}
|
|
|
|
.message-time {
|
|
font-size: 11px;
|
|
color: #999;
|
|
text-align: right;
|
|
margin-top: 5px;
|
|
}
|
|
|
|
.message-status {
|
|
display: inline-block;
|
|
margin-left: 5px;
|
|
font-size: 12px;
|
|
}
|
|
|
|
.status-sent { color: #999; }
|
|
.status-delivered { color: #999; }
|
|
.status-read { color: var(--whatsapp-green); }
|
|
|
|
.chat-input {
|
|
padding: 15px 20px;
|
|
background: #f0f0f0;
|
|
border-top: 1px solid #ddd;
|
|
display: flex;
|
|
align-items: center;
|
|
gap: 10px;
|
|
}
|
|
|
|
.chat-input input {
|
|
flex: 1;
|
|
padding: 10px 15px;
|
|
border: 1px solid #ddd;
|
|
border-radius: 25px;
|
|
outline: none;
|
|
font-size: 14px;
|
|
}
|
|
|
|
.chat-input input:focus {
|
|
border-color: var(--whatsapp-green);
|
|
}
|
|
|
|
.chat-input .btn {
|
|
border-radius: 50%;
|
|
width: 45px;
|
|
height: 45px;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
background: var(--whatsapp-green);
|
|
border: none;
|
|
color: white;
|
|
}
|
|
|
|
.chat-input .btn:hover {
|
|
background: var(--whatsapp-green-dark);
|
|
}
|
|
|
|
.no-conversation {
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: center;
|
|
justify-content: center;
|
|
height: 100%;
|
|
color: #999;
|
|
text-align: center;
|
|
}
|
|
|
|
.no-conversation i {
|
|
font-size: 64px;
|
|
margin-bottom: 20px;
|
|
opacity: 0.3;
|
|
}
|
|
|
|
.loading {
|
|
text-align: center;
|
|
padding: 20px;
|
|
color: #666;
|
|
}
|
|
|
|
.message-template {
|
|
background: #fffacd;
|
|
border: 1px solid #f0e68c;
|
|
padding: 10px;
|
|
border-radius: 8px;
|
|
margin-bottom: 10px;
|
|
font-size: 13px;
|
|
}
|
|
|
|
.unread-count {
|
|
background: var(--whatsapp-green);
|
|
color: white;
|
|
border-radius: 50%;
|
|
font-size: 12px;
|
|
min-width: 20px;
|
|
height: 20px;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
margin-left: auto;
|
|
}
|
|
|
|
@media (max-width: 768px) {
|
|
.chat-sidebar {
|
|
width: 100%;
|
|
position: absolute;
|
|
z-index: 1000;
|
|
height: 100vh;
|
|
}
|
|
|
|
.chat-main {
|
|
width: 100%;
|
|
}
|
|
|
|
.chat-sidebar.show-chat {
|
|
transform: translateX(-100%);
|
|
}
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="chat-container">
|
|
<!-- Sidebar con lista de conversaciones -->
|
|
<div class="chat-sidebar">
|
|
<div class="sidebar-header">
|
|
<div>
|
|
<h5 class="mb-0">💬 Conversaciones</h5>
|
|
</div>
|
|
<div>
|
|
<a href="index.php" class="text-white text-decoration-none">
|
|
<i class="fas fa-arrow-left"></i>
|
|
</a>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="sidebar-search">
|
|
<div class="input-group">
|
|
<span class="input-group-text bg-transparent border-0">
|
|
<i class="fas fa-search text-muted"></i>
|
|
</span>
|
|
<input type="text" class="form-control border-0" placeholder="Buscar conversaciones..." id="search-input">
|
|
</div>
|
|
</div>
|
|
|
|
<div class="conversation-list" id="conversation-list">
|
|
<div class="loading">
|
|
<i class="fas fa-spinner fa-spin"></i>
|
|
<div>Cargando conversaciones...</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Área principal del chat -->
|
|
<div class="chat-main">
|
|
<div id="no-conversation" class="no-conversation">
|
|
<i class="fab fa-whatsapp"></i>
|
|
<h4>WhatsApp Bot Manager</h4>
|
|
<p>Selecciona una conversación para comenzar a chatear</p>
|
|
</div>
|
|
|
|
<div id="chat-area" style="display: none; height: 100%; flex-direction: column;">
|
|
<div class="chat-header">
|
|
<div class="chat-header-avatar" id="chat-avatar">
|
|
<i class="fas fa-user"></i>
|
|
</div>
|
|
<div class="chat-header-info">
|
|
<h6 id="chat-name">Usuario</h6>
|
|
<small id="chat-phone">+1234567890</small>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="chat-messages" id="chat-messages">
|
|
<!-- Los mensajes se cargan aquí -->
|
|
</div>
|
|
|
|
<div class="chat-input">
|
|
<input type="text" placeholder="Escribe un mensaje..." id="message-input" maxlength="4096">
|
|
<button class="btn" id="send-btn">
|
|
<i class="fas fa-paper-plane"></i>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
|
|
<script>
|
|
class WhatsAppChat {
|
|
constructor() {
|
|
this.currentConversationId = null;
|
|
this.currentUserId = null;
|
|
this.conversations = [];
|
|
this.messages = [];
|
|
|
|
this.init();
|
|
}
|
|
|
|
init() {
|
|
this.loadConversations();
|
|
this.setupEventListeners();
|
|
this.setupAutoRefresh();
|
|
}
|
|
|
|
setupEventListeners() {
|
|
// Búsqueda de conversaciones
|
|
document.getElementById('search-input').addEventListener('input', (e) => {
|
|
this.searchConversations(e.target.value);
|
|
});
|
|
|
|
// Envío de mensajes
|
|
document.getElementById('send-btn').addEventListener('click', () => {
|
|
this.sendMessage();
|
|
});
|
|
|
|
document.getElementById('message-input').addEventListener('keypress', (e) => {
|
|
if (e.key === 'Enter') {
|
|
this.sendMessage();
|
|
}
|
|
});
|
|
}
|
|
|
|
setupAutoRefresh() {
|
|
// Actualizar conversaciones cada 30 segundos
|
|
setInterval(() => {
|
|
this.loadConversations();
|
|
}, 30000);
|
|
|
|
// Actualizar mensajes del chat activo cada 10 segundos
|
|
setInterval(() => {
|
|
if (this.currentUserId) {
|
|
this.loadMessages(this.currentUserId, false);
|
|
}
|
|
}, 10000);
|
|
}
|
|
|
|
async loadConversations() {
|
|
try {
|
|
const response = await fetch('api/get_conversations.php');
|
|
const data = await response.json();
|
|
console.log('Respuesta get_conversations:', data); // Debug
|
|
|
|
// Manejar nuevo formato de respuesta de API
|
|
if (data && data.success && Array.isArray(data.data)) {
|
|
this.conversations = data.data;
|
|
this.renderConversations();
|
|
} else if (Array.isArray(data)) {
|
|
// Retrocompatibilidad con formato anterior
|
|
this.conversations = data;
|
|
this.renderConversations();
|
|
} else {
|
|
console.error('Error cargando conversaciones: formato de datos inválido', data);
|
|
alert('Error cargando conversaciones: ' + (data.error || 'formato de datos inválido'));
|
|
}
|
|
} catch (error) {
|
|
console.error('Error loading conversations:', error);
|
|
alert('Error cargando conversaciones: ' + error.message);
|
|
}
|
|
}
|
|
|
|
renderConversations() {
|
|
const container = document.getElementById('conversation-list');
|
|
|
|
if (this.conversations.length === 0) {
|
|
container.innerHTML = `
|
|
<div class="text-center p-4">
|
|
<i class="fas fa-comments fa-3x text-muted mb-3"></i>
|
|
<p class="text-muted">No hay conversaciones aún</p>
|
|
</div>
|
|
`;
|
|
return;
|
|
}
|
|
|
|
// Agrupar por usuario
|
|
const userConversations = {};
|
|
this.conversations.forEach(conv => {
|
|
const key = conv.user_id;
|
|
if (!userConversations[key]) {
|
|
userConversations[key] = {
|
|
user_id: conv.user_id,
|
|
name: conv.name || conv.phone_number,
|
|
phone_number: conv.phone_number,
|
|
last_message: conv.content,
|
|
last_time: conv.created_at,
|
|
direction: conv.direction,
|
|
unread: 0
|
|
};
|
|
}
|
|
|
|
// Mantener el mensaje más reciente
|
|
if (new Date(conv.created_at) > new Date(userConversations[key].last_time)) {
|
|
userConversations[key].last_message = conv.content;
|
|
userConversations[key].last_time = conv.created_at;
|
|
userConversations[key].direction = conv.direction;
|
|
}
|
|
});
|
|
|
|
const html = Object.values(userConversations).map(conv => {
|
|
const initials = this.getInitials(conv.name);
|
|
const time = this.formatTime(conv.last_time);
|
|
const preview = this.truncateText(conv.last_message || 'Sin mensajes', 50);
|
|
const isActive = conv.user_id == this.currentUserId ? 'active' : '';
|
|
|
|
return `
|
|
<div class="conversation-item ${isActive}" data-user-id="${conv.user_id}" onclick="chat.openConversation(${conv.user_id}, '${conv.name}', '${conv.phone_number}')">
|
|
<div class="conversation-avatar">
|
|
${initials}
|
|
</div>
|
|
<div class="conversation-info">
|
|
<div class="conversation-name">${conv.name}</div>
|
|
<div class="conversation-preview">
|
|
${conv.direction === 'outgoing' ? '✓ ' : ''}${preview}
|
|
</div>
|
|
</div>
|
|
<div class="conversation-time">
|
|
${time}
|
|
</div>
|
|
</div>
|
|
`;
|
|
}).join('');
|
|
|
|
container.innerHTML = html;
|
|
}
|
|
|
|
getInitials(name) {
|
|
if (!name) return '?';
|
|
const parts = name.split(' ');
|
|
if (parts.length >= 2) {
|
|
return (parts[0][0] + parts[1][0]).toUpperCase();
|
|
}
|
|
return name.substring(0, 2).toUpperCase();
|
|
}
|
|
|
|
formatTime(dateString) {
|
|
const date = new Date(dateString);
|
|
const now = new Date();
|
|
const diffInHours = (now - date) / (1000 * 60 * 60);
|
|
|
|
if (diffInHours < 24) {
|
|
return date.toLocaleTimeString('es-ES', {
|
|
hour: '2-digit',
|
|
minute: '2-digit'
|
|
});
|
|
} else if (diffInHours < 48) {
|
|
return 'Ayer';
|
|
} else {
|
|
return date.toLocaleDateString('es-ES', {
|
|
day: '2-digit',
|
|
month: '2-digit'
|
|
});
|
|
}
|
|
}
|
|
|
|
truncateText(text, maxLength) {
|
|
if (text.length <= maxLength) return text;
|
|
return text.substring(0, maxLength) + '...';
|
|
}
|
|
|
|
async openConversation(userId, userName, phoneNumber) {
|
|
this.currentUserId = userId;
|
|
|
|
// Actualizar UI
|
|
document.getElementById('no-conversation').style.display = 'none';
|
|
document.getElementById('chat-area').style.display = 'flex';
|
|
|
|
// Actualizar header
|
|
document.getElementById('chat-name').textContent = userName;
|
|
document.getElementById('chat-phone').textContent = phoneNumber;
|
|
document.getElementById('chat-avatar').textContent = this.getInitials(userName);
|
|
|
|
// Marcar conversación como activa
|
|
document.querySelectorAll('.conversation-item').forEach(item => {
|
|
item.classList.remove('active');
|
|
});
|
|
document.querySelector(`[data-user-id="${userId}"]`)?.classList.add('active');
|
|
|
|
// Cargar mensajes
|
|
await this.loadMessages(userId);
|
|
}
|
|
|
|
async loadMessages(userId, showLoading = true) {
|
|
if (showLoading) {
|
|
document.getElementById('chat-messages').innerHTML = `
|
|
<div class="loading">
|
|
<i class="fas fa-spinner fa-spin"></i> Cargando mensajes...
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`api/get_user_messages.php?user_id=${userId}`);
|
|
const data = await response.json();
|
|
|
|
if (Array.isArray(data)) {
|
|
this.messages = data;
|
|
this.renderMessages();
|
|
this.scrollToBottom();
|
|
}
|
|
} catch (error) {
|
|
console.error('Error loading messages:', error);
|
|
document.getElementById('chat-messages').innerHTML = `
|
|
<div class="text-center p-4">
|
|
<i class="fas fa-exclamation-triangle text-warning"></i>
|
|
<p>Error al cargar los mensajes</p>
|
|
</div>
|
|
`;
|
|
}
|
|
}
|
|
|
|
renderMessages() {
|
|
const container = document.getElementById('chat-messages');
|
|
|
|
if (this.messages.length === 0) {
|
|
container.innerHTML = `
|
|
<div class="text-center p-4">
|
|
<i class="far fa-comment fa-3x text-muted mb-3"></i>
|
|
<p class="text-muted">No hay mensajes en esta conversación</p>
|
|
</div>
|
|
`;
|
|
return;
|
|
}
|
|
|
|
const html = this.messages.map(msg => {
|
|
const time = new Date(msg.created_at).toLocaleTimeString('es-ES', {
|
|
hour: '2-digit',
|
|
minute: '2-digit'
|
|
});
|
|
|
|
const statusIcon = this.getStatusIcon(msg.status);
|
|
|
|
return `
|
|
<div class="message ${msg.direction}">
|
|
<div class="message-bubble">
|
|
${msg.content || msg.message_text || '[Mensaje vacío]'}
|
|
<div class="message-time">
|
|
${time}
|
|
${msg.direction === 'outgoing' ? `<span class="message-status">${statusIcon}</span>` : ''}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}).join('');
|
|
|
|
container.innerHTML = html;
|
|
}
|
|
|
|
getStatusIcon(status) {
|
|
switch (status) {
|
|
case 'sent': return '<i class="fas fa-check status-sent"></i>';
|
|
case 'delivered': return '<i class="fas fa-check-double status-delivered"></i>';
|
|
case 'read': return '<i class="fas fa-check-double status-read"></i>';
|
|
default: return '<i class="fas fa-clock status-sent"></i>';
|
|
}
|
|
}
|
|
|
|
scrollToBottom() {
|
|
const container = document.getElementById('chat-messages');
|
|
container.scrollTop = container.scrollHeight;
|
|
}
|
|
|
|
async sendMessage() {
|
|
const input = document.getElementById('message-input');
|
|
const message = input.value.trim();
|
|
|
|
if (!message || !this.currentUserId) return;
|
|
|
|
// Deshabilitar input
|
|
input.disabled = true;
|
|
document.getElementById('send-btn').disabled = true;
|
|
|
|
try {
|
|
const response = await fetch('api/send_message.php', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
user_id: this.currentUserId,
|
|
message: message
|
|
})
|
|
});
|
|
|
|
const result = await response.json();
|
|
|
|
if (result.success) {
|
|
input.value = '';
|
|
// Recargar mensajes
|
|
await this.loadMessages(this.currentUserId, false);
|
|
// Actualizar lista de conversaciones
|
|
this.loadConversations();
|
|
} else {
|
|
alert('Error al enviar mensaje: ' + (result.error || 'Error desconocido'));
|
|
}
|
|
} catch (error) {
|
|
console.error('Error sending message:', error);
|
|
alert('Error al enviar mensaje');
|
|
} finally {
|
|
input.disabled = false;
|
|
document.getElementById('send-btn').disabled = false;
|
|
input.focus();
|
|
}
|
|
}
|
|
|
|
searchConversations(query) {
|
|
const items = document.querySelectorAll('.conversation-item');
|
|
items.forEach(item => {
|
|
const name = item.querySelector('.conversation-name').textContent.toLowerCase();
|
|
const preview = item.querySelector('.conversation-preview').textContent.toLowerCase();
|
|
const matches = name.includes(query.toLowerCase()) || preview.includes(query.toLowerCase());
|
|
item.style.display = matches ? 'flex' : 'none';
|
|
});
|
|
}
|
|
}
|
|
|
|
// Inicializar cuando la página cargue
|
|
let chat;
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
chat = new WhatsAppChat();
|
|
});
|
|
</script>
|
|
</body>
|
|
</html> |