Files
whatsapp/chat_window.php
T
2026-01-22 10:56:15 -05:00

1600 lines
68 KiB
PHP

<?php
session_start();
// Verificar autenticación
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
// Permitir acceso en modo debug
if (!isset($_GET['debug']) || $_GET['debug'] !== 'true') {
header('Location: login.php');
exit;
}
}
$user_id = $_GET['user_id'] ?? '';
if (empty($user_id)) {
die('ID de usuario requerido');
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat WhatsApp - Usuario</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<link href="assets/css/styles.css" rel="stylesheet">
<style>
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.chat-container {
background: white;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
margin: 20px auto;
max-width: 900px;
height: calc(100vh - 40px);
display: flex;
flex-direction: column;
}
.chat-header {
background: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
color: white;
padding: 20px;
border-radius: 15px 15px 0 0;
display: flex;
align-items: center;
justify-content: space-between;
}
.chat-conversations {
flex: 1;
padding: 20px;
overflow-y: auto;
background: #f8f9fa;
}
.chat-input {
padding: 20px;
background: white;
border-radius: 0 0 15px 15px;
border-top: 1px solid #eee;
}
.message-bubble {
margin: 10px 0;
padding: 12px 16px;
border-radius: 18px;
max-width: 70%;
word-wrap: break-word;
}
/* Estilos para mensajes multimedia */
.message-bubble img {
max-width: 300px;
max-height: 400px;
width: auto;
height: auto;
border-radius: 8px;
cursor: pointer;
display: block;
margin: 4px 0;
}
.message-bubble video {
max-width: 300px;
max-height: 400px;
border-radius: 8px;
display: block;
margin: 4px 0;
}
.message-bubble audio {
width: 250px;
height: 40px;
margin: 4px 0;
display: block;
}
.message-document {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 15px;
background: rgba(0,0,0,0.05);
border-radius: 8px;
text-decoration: none;
color: inherit;
margin: 4px 0;
}
.message-document:hover {
background: rgba(0,0,0,0.1);
}
.message-document i {
font-size: 1.5rem;
color: #25D366;
}
.message-outgoing {
background: #DCF8C6;
margin-left: auto;
border-bottom-right-radius: 4px;
}
.message-incoming {
background: white;
margin-right: auto;
border-bottom-left-radius: 4px;
box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}
.message-time {
font-size: 0.75rem;
color: #999;
margin-top: 5px;
text-align: right;
}
.message-incoming .message-time {
text-align: left;
}
.typing-indicator {
display: none;
padding: 10px;
font-style: italic;
color: #666;
}
.input-group {
border-radius: 25px;
overflow: hidden;
}
.form-control {
border: none;
padding: 12px 20px;
}
.btn-send {
background: #25D366;
border: none;
color: white;
padding: 12px 20px;
border-radius: 0 25px 25px 0;
}
.btn-send:hover {
background: #128C7E;
color: white;
}
.user-avatar {
width: 45px;
height: 45px;
border-radius: 50%;
background: #25D366;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
font-size: 1.2rem;
}
.status-indicator {
font-size: 0.8rem;
opacity: 0.8;
}
/* Estilos para multimedia */
.attach-btn {
background: transparent;
border: none;
color: #666;
padding: 12px 15px;
cursor: pointer;
font-size: 1.2rem;
}
.attach-btn:hover {
color: #25D366;
}
.media-preview {
padding: 10px;
background: #f0f0f0;
border-radius: 8px;
margin-bottom: 10px;
display: none;
}
.media-preview.show {
display: block;
animation: slideDown 0.3s ease-out;
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.media-preview-content {
display: flex;
align-items: center;
gap: 10px;
}
.media-thumbnail {
width: 60px;
height: 60px;
object-fit: cover;
border-radius: 5px;
}
.media-info {
flex: 1;
}
.media-filename {
font-weight: 500;
font-size: 0.9rem;
color: #333;
}
.media-filesize {
font-size: 0.8rem;
color: #666;
}
.message-media {
margin-top: 8px;
}
.message-media img,
.message-media video {
max-width: 100%;
border-radius: 8px;
margin-top: 5px;
}
.message-media audio {
width: 100%;
margin-top: 5px;
}
.message-document {
display: flex;
align-items: center;
gap: 10px;
padding: 10px;
background: #f0f0f0;
border-radius: 8px;
margin-top: 5px;
text-decoration: none;
color: inherit;
}
.message-document:hover {
background: #e0e0e0;
}
.message-document i {
font-size: 1.5rem;
color: #666;
}
.mic-btn {
background: transparent;
border: none;
color: #666;
padding: 12px 15px;
cursor: pointer;
font-size: 1.2rem;
}
.mic-btn:hover {
color: #25D366;
}
.mic-btn.recording {
color: #dc3545;
animation: pulse 1s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.recording-indicator {
display: none;
padding: 10px;
background: #fff3cd;
border-radius: 8px;
margin-bottom: 10px;
align-items: center;
gap: 10px;
}
.recording-indicator.show {
display: flex;
}
.recording-time {
font-weight: 500;
color: #dc3545;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="chat-container">
<!-- Header del chat -->
<div class="chat-header">
<div class="d-flex align-items-center">
<div class="user-avatar me-3" id="userAvatar">
<i class="fas fa-user"></i>
</div>
<div>
<h5 class="mb-0" id="userName">Cargando...</h5>
<small class="status-indicator" id="userStatus">
<i class="fas fa-circle text-success"></i> En línea
</small>
</div>
</div>
<div class="d-flex align-items-center">
<button id="attendBtn" class="btn btn-outline-light btn-sm me-2" onclick="toggleAttend()" title="Atender/Finalizar">
<i class="fas fa-user-check"></i> Atender
</button>
<small id="attendStatus" class="text-white me-3" style="font-size:0.9rem;"></small>
<button class="btn btn-outline-light btn-sm me-2" onclick="refreshChat()">
<i class="fas fa-sync-alt"></i>
</button>
<button class="btn btn-outline-light btn-sm" onclick="window.close()">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<!-- Mensajes del chat -->
<div class="chat-conversations" id="chatconversations">
<div class="d-flex justify-content-center">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Cargando mensajes...</span>
</div>
</div>
</div>
<!-- Indicador de escritura -->
<div class="typing-indicator" id="typingIndicator">
<i class="fas fa-circle"></i>
<i class="fas fa-circle"></i>
<i class="fas fa-circle"></i>
El usuario está escribiendo...
</div>
<!-- Input de mensaje -->
<div class="chat-input">
<div class="row mb-3">
<div class="col-md-4">
<select class="form-select" id="messageType">
<option value="text">Mensaje de texto</option>
<option value="template">Plantilla</option>
</select>
</div>
<div class="col-md-4" id="templateSelectContainer" style="display: none;">
<select class="form-select" id="templateSelect">
<option value="">Seleccionar plantilla...</option>
</select>
</div>
</div>
<!-- Indicador de grabación -->
<div class="recording-indicator" id="recordingIndicator">
<i class="fas fa-microphone text-danger"></i>
<span>Grabando audio...</span>
<span class="recording-time" id="recordingTime">0:00</span>
<button type="button" class="btn btn-sm btn-success ms-auto" onclick="stopRecording()">
<i class="fas fa-stop"></i> Detener
</button>
<button type="button" class="btn btn-sm btn-danger" onclick="cancelRecording()">
<i class="fas fa-times"></i>
</button>
</div>
<!-- Preview de multimedia -->
<div class="media-preview" id="mediaPreview">
<div class="media-preview-content">
<img id="mediaThumbnail" class="media-thumbnail" style="display: none;" />
<div class="media-info">
<div class="media-filename" id="mediaFilename"></div>
<div class="media-filesize" id="mediaFilesize"></div>
</div>
<button type="button" class="btn btn-sm btn-danger" onclick="cancelMediaUpload()">
<i class="fas fa-times"></i>
</button>
</div>
<input type="text" class="form-control form-control-sm mt-2" id="mediaCaption"
placeholder="Agregar caption (opcional)...">
</div>
<!-- Quick replies (Respuestas rápidas) -->
<div id="quickRepliesContainer" style="display:none; margin-bottom:10px;">
<div class="d-flex flex-wrap" id="quickRepliesButtons" style="gap:8px;"></div>
</div>
<div class="input-group">
<input type="file" id="fileInput" style="display: none;"
accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.xls,.xlsx" />
<button type="button" class="attach-btn" id="attachBtn" title="Adjuntar archivo">
<i class="fas fa-paperclip"></i>
</button>
<button type="button" class="mic-btn" id="micBtn" title="Grabar audio">
<i class="fas fa-microphone"></i>
</button>
<input type="text" class="form-control" id="messageInput"
placeholder="Escribe un mensaje..."
onkeypress="handleEnterKey(event)">
<button class="btn btn-send" onclick="sendMessage()">
<i class="fas fa-paper-plane"></i>
</button>
</div>
<!-- Quick replies toggle -->
<div class="mt-2 d-flex align-items-center">
<button class="btn btn-sm btn-outline-secondary" id="toggleQuickRepliesBtn" onclick="toggleQuickReplies()">
<i class="fas fa-bolt"></i> Respuestas rápidas
</button>
<small class="ms-2 text-muted">Usa respuestas automáticas rápidas</small>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Variables globales
const userId = <?php echo json_encode($user_id); ?>;
let currentUser = null;
let whatsappManager = null;
// Manager para API calls
class WhatsAppManager {
constructor() {
this.isInitialized = true;
}
async apiCall(endpoint, options = {}) {
const defaultOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
};
// Configurar método y cuerpo si es POST
if (options.body) {
defaultOptions.method = 'POST';
defaultOptions.body = JSON.stringify(options.body);
}
// Combinar opciones correctamente
const finalOptions = {
...defaultOptions,
...options,
headers: {
...defaultOptions.headers,
...(options.headers || {})
}
};
// Si había un body en options, asegurar que se serializa correctamente
if (options.body && typeof options.body === 'object') {
finalOptions.body = JSON.stringify(options.body);
}
const url = endpoint.startsWith('http') ? endpoint : `api/${endpoint}`;
const response = await fetch(url, finalOptions);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Manejar respuestas que no contienen JSON válido
try {
const text = await response.text();
if (!text || text.trim() === '') {
throw new Error('Empty response body');
}
return JSON.parse(text);
} catch (err) {
console.error('apiCall parse error for', url, err);
throw new Error('Invalid JSON response from ' + url + ': ' + err.message);
}
}
}
// Inicializar manager
whatsappManager = new WhatsAppManager();
// Función para escapar HTML
function escapeHtml(text) {
if (!text) return '';
const map = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
};
return text.toString().replace(/[&<>"']/g, function(m) { return map[m]; });
}
// Helper: validar que una URL de media sea útil (no null/undefined/empty)
function isValidMediaUrl(u) {
return (typeof u === 'string') && u.trim() !== '' && u !== 'null' && u !== 'undefined';
}
// Cargar datos del usuario y mensajes
async function loadUserData() {
try {
const response = await whatsappManager.apiCall(`get_conversation_detail.php?user_id=${userId}`);
if (response && response.success) {
currentUser = response.user;
// Actualizar header
const displayName = currentUser.name || 'Usuario';
const phoneNumber = currentUser.phone_number || '';
document.getElementById('userName').innerHTML = `
<span id="userNameText">${escapeHtml(displayName)}</span>
<button id="editNameBtn" class="btn btn-sm btn-light ms-2" onclick="editUserName()" title="Editar nombre">
<i class="fas fa-edit"></i>
</button>
${phoneNumber ? `<br><small class="opacity-75">${escapeHtml(phoneNumber)}</small>` : ''}
<div id="editNameContainer" style="display:none; margin-top:6px;">
<input id="editNameInput" class="form-control form-control-sm" type="text" value="${escapeHtml(displayName)}" style="display:inline-block; width:70%;">
<button id="saveNameBtn" class="btn btn-sm btn-success ms-2" onclick="saveUserName()">Guardar</button>
<button id="cancelNameBtn" class="btn btn-sm btn-secondary ms-1" onclick="cancelEditUserName()">Cancelar</button>
</div>
`;
document.getElementById('userAvatar').innerHTML =
`<span>${(currentUser.name || 'U').charAt(0).toUpperCase()}</span>`;
// Estado de atención
renderAttendControls();
// Cargar mensajes
displayconversations(response.conversations);
// Cargar plantillas
loadTemplates();
// Cargar respuestas rápidas (quick replies)
loadQuickReplies();
} else {
showError('Error cargando datos del usuario');
}
} catch (error) {
console.error('Error:', error);
showError('Error cargando conversación: ' + error.message);
}
}
// Mostrar mensajes
function displayconversations(conversations) {
const chatconversations = document.getElementById('chatconversations');
if (!conversations || conversations.length === 0) {
chatconversations.innerHTML = `
<div class="text-center text-muted py-5">
<i class="fas fa-comments fa-3x mb-3"></i>
<br>No hay mensajes en esta conversación
<br><small>Envía el primer mensaje para comenzar</small>
</div>
`;
return;
}
let html = '';
conversations.forEach(msg => {
const isOutgoing = msg.direction === 'outgoing';
const messageClass = isOutgoing ? 'message-outgoing' : 'message-incoming';
// Debug: ver todos los datos del mensaje (prioriza media_url_external y valida URLs)
const has_media_external = isValidMediaUrl(msg.media_url_external);
const effective_media = isValidMediaUrl(msg.media_url_external) ? msg.media_url_external : (isValidMediaUrl(msg.local_file) ? msg.local_file : (isValidMediaUrl(msg.local_thumb) ? msg.local_thumb : (isValidMediaUrl(msg.media_url) ? msg.media_url : '')));
console.log('Procesando mensaje:', {
id: msg.id,
type: msg.message_type,
has_media_external: has_media_external,
effective_media: effective_media,
content: msg.content
});
// Verificar si es multimedia (validando principalmente media_url_external o archivos locales)
let contentHtml = '';
const hasMediaUrl = isValidMediaUrl(msg.media_url_external) || isValidMediaUrl(msg.local_file) || isValidMediaUrl(msg.local_thumb);
const isMultimedia = hasMediaUrl && msg.message_type && msg.message_type !== 'text';
if (isMultimedia) {
console.log('→ Renderizando como multimedia:', msg.message_type);
// Mensaje multimedia
switch (msg.message_type) {
case 'image':
// Determinar miniatura y URL completa (prioriza media_url_external o archivos locales)
let thumbUrl = '';
if (isValidMediaUrl(msg.local_thumb)) {
thumbUrl = `/${msg.local_thumb}`;
} else if (isValidMediaUrl(msg.local_file)) {
thumbUrl = `/${msg.local_file}`;
} else if (isValidMediaUrl(msg.effective_media) || isValidMediaUrl(msg.media_url_external)) {
// Priorizar effective_media si existe; usar proxy para Facebook/lookaside
const external = isValidMediaUrl(msg.effective_media) ? msg.effective_media : msg.media_url_external;
if (/lookaside\.fbsbx\.com|graph\.facebook\.com|facebook\.com/i.test(external)) {
const midMatch = external.match(/[?&]mid=([^&]+)/i);
if (midMatch && midMatch[1]) {
const mid = decodeURIComponent(midMatch[1]);
thumbUrl = `/api/version/media-url.php?id=${encodeURIComponent(mid)}`;
} else {
thumbUrl = `/api/version/media-url.php?url=${encodeURIComponent(external)}`;
}
} else {
thumbUrl = external;
}
} else if (isValidMediaUrl(msg.media_url)) {
thumbUrl = msg.media_url;
}
let fullUrl = '';
if (isValidMediaUrl(msg.local_file)) {
fullUrl = `/api/version/media-url.php?local=${encodeURIComponent(msg.local_file)}`;
} else if (isValidMediaUrl(msg.media_url_external)) {
// Si la URL externa contiene un media id (api/get_media.php?id=... o mid=...), usar id para consultar Graph API
const external = msg.media_url_external;
let mid = '';
if (external.indexOf('api/get_media.php?id=') !== -1) {
const parts = external.split('id=');
mid = parts[1] ? decodeURIComponent(parts[1]) : '';
} else {
// Buscar parámetro mid en la query string (ej: ?mid=12345&...)
const m = external.match(/[?&]mid=([^&]+)/i);
if (m && m[1]) {
mid = decodeURIComponent(m[1]);
}
}
if (mid) {
fullUrl = `/api/version/media-url.php?id=${encodeURIComponent(mid)}`;
} else if (/^https?:\/\//i.test(external)) {
fullUrl = `/api/version/media-url.php?url=${encodeURIComponent(external)}`;
} else {
fullUrl = `/api/version/media-url.php?url=${encodeURIComponent(external)}`;
}
} else {
// No usar msg.media_url como fuente principal para apertura; dejar vacío para forzar 'no disponible'
fullUrl = '';
}
if (isValidMediaUrl(fullUrl)) {
// Usar data-fullurl y dataset para evitar problemas de escapado en el onclick
contentHtml = `
<a href="#" data-fullurl="${escapeHtml(fullUrl)}" onclick="openImageModal(this.dataset.fullurl); return false;" title="Abrir imagen">
<img src="${escapeHtml(thumbUrl || fullUrl)}" alt="Imagen" class="message-media-image">
</a>`;
} else if (isValidMediaUrl(thumbUrl)) {
// Mostrar solo la miniatura si no hay URL externa/local para abrir
contentHtml = `<img src="${escapeHtml(thumbUrl)}" alt="Imagen" class="message-media-image">`;
} else {
// No hay media disponible
contentHtml = `<div class="text-muted"><em>Imagen no disponible</em></div>`;
}
break;
case 'video':
// Determinar mejor fuente de media
const mediaSrcVid = isValidMediaUrl(fullUrl) ? fullUrl : (isValidMediaUrl(thumbUrl) ? thumbUrl : (isValidMediaUrl(msg.media_url) ? msg.media_url : (isValidMediaUrl(msg.media_url_external) ? msg.media_url_external : '')));
console.debug('video media src:', mediaSrcVid, 'fullUrl:', fullUrl, 'thumbUrl:', thumbUrl, 'msg.media_url:', msg.media_url, 'msg.media_url_external:', msg.media_url_external);
if (isValidMediaUrl(mediaSrcVid)) {
contentHtml = `<video controls class="message-media-video">
<source src="${escapeHtml(mediaSrcVid)}" type="video/mp4">
Tu navegador no soporta video HTML5.
</video>`;
} else {
contentHtml = `<div class="text-muted"><em>Video no disponible</em></div>`;
}
break;
case 'audio':
// Determinar mejor fuente de media para audio
const mediaSrcAudio = isValidMediaUrl(fullUrl) ? fullUrl : (isValidMediaUrl(thumbUrl) ? thumbUrl : (isValidMediaUrl(msg.media_url) ? msg.media_url : (isValidMediaUrl(msg.media_url_external) ? msg.media_url_external : '')));
if (isValidMediaUrl(mediaSrcAudio)) {
contentHtml = `<audio controls class="message-media-audio">
<source src="${escapeHtml(mediaSrcAudio)}" type="audio/webm">
<source src="${escapeHtml(mediaSrcAudio)}" type="audio/mpeg">
<source src="${escapeHtml(mediaSrcAudio)}" type="audio/ogg">
Tu navegador no soporta audio HTML5.
</audio>`;
console.debug('audio media src:', mediaSrcAudio, 'effective_media:', msg.effective_media, 'media_url_external:', msg.media_url_external, 'local_file:', msg.local_file);
// Añadir enlace de descarga seguro / proxy si es posible
let audioDownload = null;
let candidate = isValidMediaUrl(msg.effective_media) ? msg.effective_media : (isValidMediaUrl(msg.media_url_external) ? msg.media_url_external : (isValidMediaUrl(msg.local_file) ? msg.local_file : null));
if (candidate && candidate.indexOf && candidate.indexOf('api/get_media.php?id=') !== -1) {
const parts = candidate.split('id=');
const mid = parts[1] ? decodeURIComponent(parts[1]) : '';
audioDownload = `/api/version/media-url.php?id=${encodeURIComponent(mid)}&download=1`;
} else if (candidate && /^https?:\/\//i.test(candidate)) {
audioDownload = `/api/version/media-url.php?url=${encodeURIComponent(candidate)}&download=1`;
} else if (candidate && candidate === msg.local_file) {
audioDownload = `/api/version/media-url.php?local=${encodeURIComponent(candidate)}&download=1`;
}
if (audioDownload) {
contentHtml += `<div class="mt-2"><a href="${audioDownload}" class="btn btn-sm btn-outline-secondary" target="_blank" rel="noopener noreferrer">Descargar audio</a></div>`;
}
} else {
contentHtml = `<div class="text-muted"><em>Audio no disponible</em></div>`;
}
break;
case 'document':
const filename = msg.filename || msg.content || 'Documento';
const fileIcon = getFileIcon(filename);
// Construir URL de descarga usando effective_media o archivo local (validar fuentes)
let docSource = isValidMediaUrl(msg.effective_media) ? msg.effective_media : (isValidMediaUrl(msg.media_url_external) ? msg.media_url_external : (isValidMediaUrl(msg.local_file) ? msg.local_file : null));
let docUrl = null;
if (docSource && docSource.indexOf && docSource.indexOf('api/get_media.php?id=') !== -1) {
const parts = docSource.split('id=');
const mid = parts[1] ? decodeURIComponent(parts[1]) : '';
docUrl = `/api/version/media-url.php?id=${encodeURIComponent(mid)}&download=1`;
} else if (docSource && /^https?:\/\//i.test(docSource)) {
docUrl = `/api/version/media-url.php?url=${encodeURIComponent(docSource)}&download=1`;
} else if (docSource && docSource === msg.local_file) {
docUrl = `/api/version/media-url.php?local=${encodeURIComponent(docSource)}&download=1`;
}
if (docUrl) {
contentHtml = `<a href="${docUrl}" class="message-document" rel="noopener noreferrer" target="_blank">
<i class="${fileIcon}"></i>
<span>${escapeHtml(filename)}</span>
</a>`;
} else {
// Mostrar estado no disponible en vez de enlace vacío
contentHtml = `<div class="message-document" style="opacity:0.6;">
<i class="${fileIcon}"></i>
<span>${escapeHtml(filename)} (No disponible)</span>
</div>`;
}
break;
default:
console.warn('Tipo multimedia desconocido:', msg.message_type);
contentHtml = `<a href="${msg.media_url}" target="_blank" class="message-document">
<i class="fas fa-file"></i>
<span>${escapeHtml(msg.content || 'Archivo adjunto')}</span>
</a>`;
}
if (msg.caption) {
contentHtml += `<div style="margin-top: 5px;">${escapeHtml(msg.caption)}</div>`;
}
} else {
// Mensaje de texto normal
contentHtml = escapeHtml(msg.content) || '<em>Sin contenido</em>';
}
const messageTime = escapeHtml(msg.time || '');
html += `
<div class="d-flex ${isOutgoing ? 'justify-content-end' : 'justify-content-start'}">
<div class="message-bubble ${messageClass}">
<div class="message-content">${contentHtml}</div>
<div class="message-time">
${messageTime} ${isOutgoing ? '<i class="fas fa-check-double text-primary"></i>' : ''}
</div>
</div>
</div>
`;
});
chatconversations.innerHTML = html;
scrollToBottom();
}
// Cargar plantillas
async function loadTemplates() {
try {
const response = await whatsappManager.apiCall('check_templates.php');
const templateSelect = document.getElementById('templateSelect');
if (response && response.templates) {
templateSelect.innerHTML = '<option value="">Seleccionar plantilla...</option>';
response.templates.forEach(template => {
// Esperamos que la API devuelva "language_code" (fallback a en_US)
const lang = template.language_code || template.language || 'en_US';
const display = template.display_name || template.name;
const option = document.createElement('option');
option.value = template.name;
option.textContent = `${display} (${lang})`;
option.dataset.language = lang;
templateSelect.appendChild(option);
});
// Valor por defecto global para la plantilla seleccionada
window.language = 'en_US';
// Actualizar el language global cuando cambie la plantilla seleccionada
templateSelect.addEventListener('change', function() {
const sel = this.selectedOptions[0];
window.language = sel && sel.dataset && sel.dataset.language ? sel.dataset.language : 'en_US';
});
// Si hay una plantilla seleccionada por defecto, establecer language acorde
if (templateSelect.selectedOptions.length && templateSelect.selectedOptions[0].dataset.language) {
window.language = templateSelect.selectedOptions[0].dataset.language;
}
}
} catch (error) {
console.error('Error cargando plantillas:', error);
}
}
// Enviar mensaje
async function sendMessage() {
// Si hay un archivo seleccionado, enviar multimedia
if (selectedFile) {
await sendMediaMessage();
return;
}
const messageType = document.getElementById('messageType').value;
const messageInput = document.getElementById('messageInput');
const message = messageInput.value.trim();
if (!message && messageType === 'text') {
alert('Por favor escribe un mensaje');
return;
}
if (messageType === 'template') {
const templateSelect = document.getElementById('templateSelect');
const template = templateSelect.value;
if (!template) {
alert('Por favor selecciona una plantilla');
return;
}
await sendTemplateMessage(template,language, message);
} else {
await sendTextMessage(message);
}
messageInput.value = '';
}
// Enviar mensaje de texto
async function sendTextMessage(message) {
try {
showTyping();
console.log('Enviando mensaje de texto:', {
message,
user: currentUser
});
const requestBody = {
recipient: currentUser.phone_number,
type: 'text',
message: message
};
console.log('Request body:', requestBody);
const response = await whatsappManager.apiCall('send_message.php', {
body: requestBody
});
console.log('Response:', response);
hideTyping();
if (response && response.success) {
// Agregar mensaje a la vista inmediatamente
addMessageToView(message, 'outgoing');
showAlert('Mensaje enviado correctamente', 'success');
} else {
throw new Error(response.error || 'Error enviando mensaje');
}
} catch (error) {
hideTyping();
console.error('Error enviando mensaje:', error);
showAlert('Error enviando mensaje: ' + error.message, 'danger');
}
}
// Enviar mensaje de plantilla
async function sendTemplateMessage(template,language, parameters) {
try {
showTyping();
console.log('Enviando plantilla:', {
template,
parameters,
user: currentUser
});
const requestBody = {
recipient: currentUser.phone_number,
type: 'template',
template: template,
language: language || 'en_US',
parameters: parameters ? parameters.split(',') : []
};
console.log('Request body:', requestBody);
const response = await whatsappManager.apiCall('send_message.php', {
body: requestBody
});
console.log('Response:', response);
hideTyping();
if (response && response.success) {
addMessageToView(`Plantilla: ${template}`, 'outgoing');
showAlert('Mensaje de plantilla enviado correctamente', 'success');
} else {
throw new Error(response.error || 'Error enviando plantilla');
}
} catch (error) {
hideTyping();
console.error('Error enviando plantilla:', error);
showAlert('Error enviando plantilla: ' + error.message, 'danger');
}
}
// Agregar mensaje a la vista
function addMessageToView(message, direction) {
const chatconversations = document.getElementById('chatconversations');
const isOutgoing = direction === 'outgoing';
const messageClass = isOutgoing ? 'message-outgoing' : 'message-incoming';
const now = new Date().toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
const messageHtml = `
<div class="d-flex ${isOutgoing ? 'justify-content-end' : 'justify-content-start'}">
<div class="message-bubble ${messageClass}">
<div class="message-content">${escapeHtml(message)}</div>
<div class="message-time">
${now} ${isOutgoing ? '<i class="fas fa-check text-muted"></i>' : ''}
</div>
</div>
</div>
`;
chatconversations.insertAdjacentHTML('beforeend', messageHtml);
scrollToBottom();
}
// Mostrar indicador de escritura
function showTyping() {
document.getElementById('typingIndicator').style.display = 'block';
}
function hideTyping() {
document.getElementById('typingIndicator').style.display = 'none';
}
// Scroll al final
function scrollToBottom() {
const chatconversations = document.getElementById('chatconversations');
chatconversations.scrollTop = chatconversations.scrollHeight;
}
// Refrescar chat
async function refreshChat() {
await loadUserData();
}
// Manejar Enter para enviar
function handleEnterKey(event) {
if (event.key === 'Enter') {
sendMessage();
}
}
// Mostrar/ocultar selector de plantillas
document.getElementById('messageType').addEventListener('change', function() {
const templateContainer = document.getElementById('templateSelectContainer');
if (this.value === 'template') {
templateContainer.style.display = 'block';
} else {
templateContainer.style.display = 'none';
}
});
// Mostrar alertas
function showAlert(message, type = 'info') {
const alertHtml = `
<div class="alert alert-${type} alert-dismissible fade show position-fixed"
style="top: 20px; right: 20px; z-index: 9999;" role="alert">
${message}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
`;
document.body.insertAdjacentHTML('beforeend', alertHtml);
setTimeout(() => {
const alert = document.querySelector('.alert');
if (alert) {
alert.remove();
}
}, 5000);
}
// ===== Quick replies (Respuestas rápidas) =====
async function loadQuickReplies() {
try {
const resp = await whatsappManager.apiCall('get_autoresponses.php');
const container = document.getElementById('quickRepliesButtons');
const wrapper = document.getElementById('quickRepliesContainer');
container.innerHTML = '';
if (resp && resp.success && Array.isArray(resp.data)) {
const responses = resp.data;
// Filtrar solo respuestas tipo text y activas
responses.forEach(r => {
if (r.is_active && (r.response_type === 'text' || !r.response_type)) {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'btn btn-sm btn-outline-primary';
btn.textContent = r.response_text.length > 40 ? r.response_text.substr(0, 40) + '…' : r.response_text;
btn.title = r.response_text;
btn.onclick = function() {
// enviar la respuesta rápida
sendTextMessage(r.response_text);
// Registrar en UI
showAlert('Respuesta rápida enviada', 'success');
};
container.appendChild(btn);
}
});
// No mostrar automáticamente el contenedor al cargar la conversación.
// Dejamos que el usuario lo abra con el botón toggle. Si no hay respuestas, mantener oculto.
if (!container.children.length) {
wrapper.style.display = 'none';
}
} else {
wrapper.style.display = 'none';
}
} catch (err) {
console.error('Error cargando respuestas rápidas:', err);
}
}
function toggleQuickReplies() {
const wrapper = document.getElementById('quickRepliesContainer');
const container = document.getElementById('quickRepliesButtons');
if (!wrapper) return;
// Si no hay botones cargados, intentar cargarlos y luego mostrar
if (container && container.children.length === 0) {
loadQuickReplies().then(() => {
wrapper.style.display = (wrapper.style.display === 'block') ? 'none' : 'block';
}).catch(() => {
// on error, mantener oculto
wrapper.style.display = 'none';
});
} else {
wrapper.style.display = (wrapper.style.display === 'block') ? 'none' : 'block';
}
}
// ===== Controles de atención (Atender / Finalizar) =====
function renderAttendControls() {
const btn = document.getElementById('attendBtn');
const status = document.getElementById('attendStatus');
if (!btn || !status || !currentUser) return;
if (currentUser.in_service) {
btn.innerHTML = '<i class="fas fa-user-times"></i> Finalizar';
btn.classList.remove('btn-outline-light');
btn.classList.add('btn-light','text-dark');
status.innerHTML = `Atendido por ${currentUser.in_service_by_name || 'un asesor'}`;
} else {
btn.innerHTML = '<i class="fas fa-user-check"></i> Atender';
btn.classList.remove('btn-light','text-dark');
btn.classList.add('btn-outline-light');
status.innerHTML = '';
}
}
async function toggleAttend() {
if (!currentUser) return;
try {
if (currentUser.in_service) {
const resp = await whatsappManager.apiCall('finish_attend.php', { body: { user_id: userId } });
if (resp && resp.success) {
showAlert('Finalizada la atención', 'success');
await loadUserData();
} else {
throw new Error(resp.error || 'Error finalizando');
}
} else {
const resp = await whatsappManager.apiCall('attend.php', { body: { user_id: userId } });
if (resp && resp.success) {
showAlert('Atención iniciada', 'success');
await loadUserData();
} else {
throw new Error(resp.error || 'Error iniciando atención');
}
}
} catch (err) {
console.error('Error toggling attend:', err);
showAlert('Error al cambiar estado de atención: ' + err.message, 'danger');
}
}
// ===== Edición de nombre de usuario =====
function editUserName() {
const container = document.getElementById('editNameContainer');
const input = document.getElementById('editNameInput');
if (!container || !input) return;
input.value = currentUser.name || '';
container.style.display = 'block';
document.getElementById('editNameBtn').style.display = 'none';
input.focus();
}
function cancelEditUserName() {
const container = document.getElementById('editNameContainer');
if (!container) return;
container.style.display = 'none';
document.getElementById('editNameBtn').style.display = 'inline-block';
}
async function saveUserName() {
const input = document.getElementById('editNameInput');
const saveBtn = document.getElementById('saveNameBtn');
if (!input || !saveBtn) return;
const newName = input.value.trim();
if (newName.length === 0) {
showAlert('El nombre no puede estar vacío', 'warning');
return;
}
saveBtn.disabled = true;
try {
const resp = await whatsappManager.apiCall('update_user.php', { body: { user_id: userId, name: newName } });
if (resp && resp.success) {
currentUser.name = newName;
document.getElementById('userNameText').innerHTML = escapeHtml(newName);
document.getElementById('userAvatar').innerHTML = `<span>${escapeHtml(newName.charAt(0).toUpperCase() || 'U')}</span>`;
cancelEditUserName();
showAlert('Nombre actualizado', 'success');
} else {
throw new Error(resp.error || 'Error actualizando nombre');
}
} catch (err) {
console.error('Error saving user name:', err);
showAlert('Error al actualizar nombre: ' + err.message, 'danger');
} finally {
saveBtn.disabled = false;
}
}
function showError(message) {
showAlert(message, 'danger');
}
// ===== FUNCIONES MULTIMEDIA =====
let selectedFile = null;
let mediaRecorder = null;
let audioChunks = [];
let recordingStartTime = null;
let recordingInterval = null;
// ===== GRABACIÓN DE AUDIO =====
// Iniciar grabación de audio
async function startRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
audioChunks.push(event.data);
}
};
mediaRecorder.onstop = async () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
// Convertir a File object
const audioFile = new File([audioBlob], `audio_${Date.now()}.webm`, {
type: 'audio/webm'
});
selectedFile = audioFile;
showMediaPreview(audioFile);
// Detener el stream
stream.getTracks().forEach(track => track.stop());
};
mediaRecorder.start();
recordingStartTime = Date.now();
// Mostrar indicador de grabación
document.getElementById('recordingIndicator').classList.add('show');
document.getElementById('micBtn').classList.add('recording');
// Actualizar tiempo de grabación
updateRecordingTime();
recordingInterval = setInterval(updateRecordingTime, 1000);
} catch (error) {
console.error('Error al acceder al micrófono:', error);
showAlert('No se pudo acceder al micrófono. Verifica los permisos.', 'danger');
}
}
// Detener grabación
function stopRecording() {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
clearInterval(recordingInterval);
document.getElementById('recordingIndicator').classList.remove('show');
document.getElementById('micBtn').classList.remove('recording');
}
}
// Cancelar grabación
function cancelRecording() {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
audioChunks = [];
selectedFile = null;
clearInterval(recordingInterval);
document.getElementById('recordingIndicator').classList.remove('show');
document.getElementById('micBtn').classList.remove('recording');
}
}
// Actualizar tiempo de grabación
function updateRecordingTime() {
if (!recordingStartTime) return;
const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000);
const minutes = Math.floor(elapsed / 60);
const seconds = elapsed % 60;
document.getElementById('recordingTime').textContent =
`${minutes}:${seconds.toString().padStart(2, '0')}`;
}
// ===== FUNCIONES DE ARCHIVOS =====
// Manejar selección de archivo
function handleFileSelect(event) {
const file = event.target.files[0];
if (!file) return;
// Validar tipo de archivo
const allowedTypes = {
image: ['image/jpeg', 'image/png', 'image/jpg'],
video: ['video/mp4', 'video/3gpp'],
audio: ['audio/mpeg', 'audio/mp3', 'audio/aac', 'audio/ogg'],
document: ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
};
let mediaType = null;
for (const [type, mimes] of Object.entries(allowedTypes)) {
if (mimes.includes(file.type)) {
mediaType = type;
break;
}
}
if (!mediaType) {
showAlert('Tipo de archivo no soportado', 'danger');
event.target.value = '';
return;
}
// Validar tamaño
const maxSizes = {
image: 5 * 1024 * 1024, // 5MB
video: 16 * 1024 * 1024, // 16MB
audio: 16 * 1024 * 1024, // 16MB
document: 100 * 1024 * 1024 // 100MB
};
if (file.size > maxSizes[mediaType]) {
showAlert(`Archivo muy grande. Máximo: ${formatFileSize(maxSizes[mediaType])}`, 'danger');
event.target.value = '';
return;
}
selectedFile = file;
showMediaPreview(file);
}
// Mostrar preview del archivo
function showMediaPreview(file) {
const preview = document.getElementById('mediaPreview');
const thumbnail = document.getElementById('mediaThumbnail');
const filename = document.getElementById('mediaFilename');
const filesize = document.getElementById('mediaFilesize');
filename.textContent = file.name;
filesize.textContent = formatFileSize(file.size);
// Mostrar thumbnail si es imagen
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = function(e) {
thumbnail.src = e.target.result;
thumbnail.style.display = 'block';
};
reader.readAsDataURL(file);
} else if (file.type.startsWith('audio/')) {
// Mostrar reproductor para audio
const reader = new FileReader();
reader.onload = function(e) {
thumbnail.outerHTML = `<audio controls style="width: 100%; margin-bottom: 10px;" id="mediaThumbnail">
<source src="${e.target.result}" type="${file.type}">
</audio>`;
};
reader.readAsDataURL(file);
} else {
thumbnail.style.display = 'none';
}
preview.classList.add('show');
}
// Formatear tamaño de archivo
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
// Cancelar subida de multimedia
function cancelMediaUpload() {
selectedFile = null;
document.getElementById('fileInput').value = '';
// Restaurar thumbnail si se cambió por audio
const thumbnailElement = document.getElementById('mediaThumbnail');
if (thumbnailElement && thumbnailElement.tagName === 'AUDIO') {
thumbnailElement.outerHTML = '<img id="mediaThumbnail" class="media-thumbnail" style="display: none;" />';
}
document.getElementById('mediaPreview').classList.remove('show');
document.getElementById('mediaCaption').value = '';
}
// Enviar mensaje multimedia
async function sendMediaMessage() {
if (!selectedFile) return;
try {
showTyping();
// Subir archivo
const formData = new FormData();
formData.append('file', selectedFile);
formData.append('uploaded_by', userId);
const uploadResponse = await fetch('api/upload_media.php', {
method: 'POST',
body: formData
});
const uploadData = await uploadResponse.json();
if (!uploadData.success) {
throw new Error(uploadData.error || 'Error subiendo archivo');
}
// Enviar mensaje con el archivo
const caption = document.getElementById('mediaCaption').value.trim();
const sendResponse = await whatsappManager.apiCall('send_media_message.php', {
body: {
recipient: currentUser.phone_number,
media_url: uploadData.public_url,
media_type: uploadData.media_type,
caption: caption || null,
filename: uploadData.filename
}
});
hideTyping();
if (sendResponse && sendResponse.success) {
cancelMediaUpload();
showAlert('Multimedia enviado correctamente', 'success');
await loadUserData(); // Recargar mensajes
} else {
throw new Error(sendResponse.error || 'Error enviando multimedia');
}
} catch (error) {
hideTyping();
console.error('Error enviando multimedia:', error);
showAlert('Error enviando multimedia: ' + error.message, 'danger');
}
}
// Modificar renderMessage para soportar multimedia
const originalAddMessageToView = addMessageToView;
addMessageToView = function(content, type, timestamp = null) {
if (typeof content === 'object' && content.media_url) {
// Es un mensaje multimedia
return renderMediaMessage(content, type, timestamp);
}
return originalAddMessageToView(content, type, timestamp);
};
// Renderizar mensaje multimedia
function renderMediaMessage(message, type, timestamp = null) {
const chatconversations = document.getElementById('chatconversations');
const messageDiv = document.createElement('div');
messageDiv.className = `message-bubble message-${type}`;
let mediaHtml = '';
const mediaUrl = message.media_url || message.content;
switch (message.media_type) {
case 'image':
mediaHtml = `<img src="${mediaUrl}" alt="Imagen" style="max-width: 100%; border-radius: 8px;">`;
break;
case 'video':
mediaHtml = `<video controls style="max-width: 100%; border-radius: 8px;"><source src="${mediaUrl}"></video>`;
break;
case 'audio':
mediaHtml = `<audio controls style="width: 100%;"><source src="${mediaUrl}"></audio>`;
break;
case 'document':
const filename = message.filename || 'Documento';
mediaHtml = `<a href="${mediaUrl}" target="_blank" class="message-document">
<i class="fas fa-file-alt"></i>
<span>${filename}</span>
</a>`;
break;
}
let html = `<div class="message-media">${mediaHtml}</div>`;
if (message.caption) {
html += `<div style="margin-top: 5px;">${escapeHtml(message.caption)}</div>`;
}
if (timestamp) {
html += `<div class="message-time">${formatTimestamp(timestamp)}</div>`;
}
messageDiv.innerHTML = html;
chatconversations.appendChild(messageDiv);
scrollToBottom();
}
// Escape HTML
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Formatear timestamp
function formatTimestamp(timestamp) {
if (!timestamp) return '';
const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${hours}:${minutes}`;
}
// Inicializar cuando la página se carga
document.addEventListener('DOMContentLoaded', function() {
loadUserData();
// Event listeners para multimedia
document.getElementById('attachBtn').addEventListener('click', function() {
document.getElementById('fileInput').click();
});
document.getElementById('fileInput').addEventListener('change', handleFileSelect);
// Event listener para micrófono
document.getElementById('micBtn').addEventListener('click', function() {
if (mediaRecorder && mediaRecorder.state === 'recording') {
stopRecording();
} else {
startRecording();
}
});
// Auto-refresh cada 30 segundos para nuevos mensajes
setInterval(refreshChat, 30000);
});
// Función para obtener icono según tipo de archivo
function getFileIcon(filename) {
const ext = filename.split('.').pop().toLowerCase();
const iconMap = {
'pdf': 'fas fa-file-pdf text-danger',
'doc': 'fas fa-file-word text-primary',
'docx': 'fas fa-file-word text-primary',
'xls': 'fas fa-file-excel text-success',
'xlsx': 'fas fa-file-excel text-success',
'ppt': 'fas fa-file-powerpoint text-warning',
'pptx': 'fas fa-file-powerpoint text-warning',
'zip': 'fas fa-file-archive text-secondary',
'rar': 'fas fa-file-archive text-secondary',
'txt': 'fas fa-file-alt text-muted',
};
return iconMap[ext] || 'fas fa-file text-muted';
}
// Modal para ver imágenes en grande
function openImageModal(imageUrl) {
if (!isValidMediaUrl(imageUrl)) {
showAlert('Media no disponible', 'warning');
return;
}
// Crear modal si no existe
let modal = document.getElementById('imageModal');
if (!modal) {
modal = document.createElement('div');
modal.id = 'imageModal';
modal.className = 'modal fade';
modal.innerHTML = `
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content bg-transparent border-0">
<div class="modal-body p-0 position-relative">
<button type="button" class="btn-close btn-close-white position-absolute top-0 end-0 m-3"
data-bs-dismiss="modal" style="z-index: 10;"></button>
<img id="modalImage" src="" class="img-fluid w-100" style="border-radius: 10px;">
</div>
</div>
</div>
`;
document.body.appendChild(modal);
}
// Actualizar imagen y mostrar
document.getElementById('modalImage').src = imageUrl;
const bsModal = new bootstrap.Modal(modal);
bsModal.show();
}
</script>
</body>
</html>