Files
whatsapp/chat_window.php
T
2026-02-03 21:30:55 -05:00

2145 lines
93 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">
<?php $asset_v = file_exists(__DIR__ . '/assets/css/styles.css') ? filemtime(__DIR__ . '/assets/css/styles.css') : time(); ?>
<link href="assets/css/styles.css?v=<?php echo $asset_v; ?>" rel="stylesheet">
<style>
/* Más compacto: reducir la escala base y espacios para interfaces pequeñas */
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 0.88rem; /* más pequeño para toda la app */
}
.chat-container {
background: white;
border-radius: 10px;
box-shadow: 0 6px 16px rgba(0,0,0,0.10);
margin: 10px auto;
max-width: 780px; /* ligeramente más estrecho */
height: calc(100vh - 36px);
display: flex;
flex-direction: column;
overflow: hidden;
}
.chat-header {
background: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
color: white;
padding: 8px 10px; /* aún más compacto */
border-radius: 10px 10px 0 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.chat-conversations {
flex: 1;
padding: 8px; /* menos padding para caber más */
overflow-y: auto;
background: #f8f9fa;
}
.chat-input {
padding: 8px; /* compacto */
background: white;
border-radius: 0 0 10px 10px;
border-top: 1px solid #eee;
}
.message-bubble {
margin: 6px 0;
padding: 6px 10px; /* menos padding */
border-radius: 18px;
max-width: 78%;
word-wrap: break-word;
font-size: 0.88rem;
position: relative; /* para posicionar timestamp */
padding-right: 60px; /* espacio para timestamp y ticks */
}
/* Estilos tipo WhatsApp: colas y timestamps dentro de burbuja */
.message-bubble.message-outgoing {
border-bottom-right-radius: 4px; /* más afilado en la esquina del tail */
}
.message-bubble.message-incoming {
border-bottom-left-radius: 4px;
}
/* Cola simple usando pseudo-elemento */
.message-bubble.message-outgoing::after {
content: '';
position: absolute;
right: -6px;
bottom: 4px;
width: 12px;
height: 12px;
background: #DCF8C6;
transform: rotate(45deg);
border-bottom-right-radius: 2px;
z-index: 0;
}
.message-bubble.message-incoming::after {
content: '';
position: absolute;
left: -6px;
bottom: 4px;
width: 12px;
height: 12px;
background: #fff;
transform: rotate(45deg);
border-bottom-left-radius: 2px;
z-index: 0;
box-shadow: 0 1px 2px rgba(0,0,0,0.03);
}
/* Timestamp dentro de la burbuja, oculto hasta hover para limpieza visual */
.message-bubble .message-time {
position: absolute;
right: 8px;
bottom: 4px;
font-size: 0.65rem;
color: #666;
opacity: 0;
transition: opacity 0.12s ease-in-out;
white-space: nowrap;
}
.message-bubble:hover .message-time,
.message-bubble:focus-within .message-time {
opacity: 1;
}
/* Agrupación de mensajes consecutivos (menor separación) */
.message-bubble.grouped { margin-top: 2px; }
.message-bubble.grouped + .message-bubble { margin-top: 2px; }
.message-bubble.grouped::after { bottom: 2px; }
.message-bubble.message-alert { padding-right: 60px; }
/* Ajuste para que texto no choque con timestamp */
.message-text { display: block; padding-right: 6px; }
/* Estilos para mensajes multimedia */
.message-bubble img {
max-width: 220px; /* más pequeño */
max-height: 280px;
width: auto;
height: auto;
border-radius: 6px;
cursor: pointer;
display: block;
margin: 4px 0;
}
.message-bubble video {
max-width: 220px;
max-height: 280px;
border-radius: 6px;
display: block;
margin: 4px 0;
}
.message-bubble audio {
width: 160px;
height: 32px;
margin: 4px 0;
display: block;
}
.message-document {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
background: rgba(0,0,0,0.04);
border-radius: 8px;
text-decoration: none;
color: inherit;
margin: 4px 0;
}
.message-document:hover {
background: rgba(0,0,0,0.08);
}
.message-document i {
font-size: 1.25rem;
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.06);
}
.message-time {
font-size: 0.7rem;
color: #999;
margin-top: 4px;
text-align: right;
}
.message-incoming .message-time {
text-align: left;
}
/* Preservar espacios y saltos de línea en el texto de mensajes */
.message-text {
white-space: pre-wrap; /* conserva saltos de línea y múltiples espacios */
word-break: break-word;
overflow-wrap: anywhere;
}
.typing-indicator {
display: none;
padding: 8px;
font-style: italic;
color: #666;
}
.input-group {
border-radius: 20px;
overflow: hidden;
}
.form-control {
border: none;
padding: 8px 14px;
font-size: 0.88rem;
}
.btn-send {
background: #25D366;
border: none;
color: white;
padding: 10px 14px;
border-radius: 0 20px 20px 0;
font-size: 0.9rem;
}
.btn-send:hover {
background: #128C7E;
color: white;
}
.user-avatar {
width: 28px; /* más pequeño */
height: 28px;
border-radius: 50%;
background: #25D366;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 600;
font-size: 0.85rem;
}
.status-indicator {
font-size: 0.65rem;
opacity: 0.85;
}
/* Mensajes que requieren atención (asesor) */
.message-alert {
background: #fff7f7 !important;
border-left: 4px solid #dc3545 !important;
color: #6b0000;
}
.header-advisor-badge {
display: inline-block;
background: #dc3545;
color: white;
padding: 2px 6px;
border-radius: 12px;
font-size: 0.75rem;
margin-left: 8px;
}
.conversation-attention {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border-radius: 50%;
background: #dc3545;
color: white;
font-size: 0.9rem;
}
/* Estilos para multimedia */
.attach-btn {
background: transparent;
border: none;
color: #666;
padding: 8px 10px;
cursor: pointer;
font-size: 1rem;
}
.attach-btn:hover {
color: #25D366;
}
.media-preview {
padding: 8px;
background: #f0f0f0;
border-radius: 8px;
margin-bottom: 8px;
display: none;
}
.media-preview.show {
display: block;
animation: slideDown 0.22s ease-out;
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.media-preview-content {
display: flex;
align-items: center;
gap: 8px;
}
.media-thumbnail {
width: 48px;
height: 48px;
object-fit: cover;
border-radius: 4px;
}
.media-info {
flex: 1;
}
.media-filename {
font-weight: 500;
font-size: 0.85rem;
color: #333;
}
.media-filesize {
font-size: 0.75rem;
color: #666;
}
.message-media {
margin-top: 6px;
}
.message-media img,
.message-media video {
max-width: 100%;
border-radius: 6px;
margin-top: 4px;
}
.message-media audio {
width: 100%;
margin-top: 4px;
}
.message-document {
display: flex;
align-items: center;
gap: 10px;
padding: 8px;
background: #f0f0f0;
border-radius: 8px;
margin-top: 5px;
text-decoration: none;
color: inherit;
}
.message-document:hover {
background: #e0e0e0;
}
.message-document i {
font-size: 1.25rem;
color: #666;
}
.mic-btn {
background: transparent;
border: none;
color: #666;
padding: 8px 10px;
cursor: pointer;
font-size: 1rem;
}
.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: 8px;
background: #fff3cd;
border-radius: 8px;
margin-bottom: 8px;
align-items: center;
gap: 8px;
}
.recording-indicator.show {
display: flex;
}
.recording-time {
font-weight: 500;
color: #dc3545;
font-size: 0.85rem;
}
</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... <span id="advisorBadge" style="display:none;" class="header-advisor-badge">¡Atención!</span></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>
<!-- FFmpeg WASM for client-side audio conversion (webm -> ogg) -->
<script src="https://unpkg.com/@ffmpeg/ffmpeg@0.11.8/dist/ffmpeg.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) {
// Incluir parte del cuerpo en el error para ayudar al diagnóstico (truncado)
console.error('apiCall parse error for', url, err);
const respText = await response.text().catch(() => '');
const snippet = (respText && respText.length > 0) ? respText.substr(0, 1000) : '<no body available>';
throw new Error('Invalid JSON response from ' + url + ': ' + err.message + ' -- response snippet: ' + snippet);
}
}
}
// Inicializar manager
whatsappManager = new WhatsAppManager();
// ===== FFmpeg in-browser conversion helpers =====
let ffmpegInstance = null;
let ffmpegLoaded = false;
// Cargar script dinámicamente
function loadScript(url) {
return new Promise((resolve, reject) => {
const s = document.createElement('script');
s.src = url;
s.onload = () => resolve();
s.onerror = () => reject(new Error('Failed to load ' + url));
document.head.appendChild(s);
});
}
async function ensureFFmpeg() {
if (ffmpegLoaded) return;
if (typeof WebAssembly === 'undefined') {
throw new Error('WebAssembly no está disponible en este navegador; no se puede convertir en cliente');
}
// Si FFmpeg no está presente, intentar cargar desde varios CDNs
if (!window.FFmpeg || !window.FFmpeg.createFFmpeg) {
const cdns = [
'https://cdn.jsdelivr.net/npm/@ffmpeg/ffmpeg@0.11.8/dist/ffmpeg.min.js',
'https://unpkg.com/@ffmpeg/ffmpeg@0.11.8/dist/ffmpeg.min.js'
];
let loaded = false;
for (const url of cdns) {
try {
await loadScript(url);
if (window.FFmpeg && window.FFmpeg.createFFmpeg) {
loaded = true;
break;
}
} catch (e) {
console.warn('No se pudo cargar ffmpeg desde', url, e);
}
}
if (!loaded) {
throw new Error('No se pudo cargar ffmpeg.wasm desde los CDNs');
}
}
const { createFFmpeg, fetchFile } = window.FFmpeg;
ffmpegInstance = createFFmpeg({ log: true });
showAlert('Cargando conversor de audio en navegador... (esto puede tardar varios segundos)', 'info');
try {
await ffmpegInstance.load();
// attach helper
ffmpegInstance._fetchFile = fetchFile;
ffmpegLoaded = true;
} catch (e) {
console.error('FFmpeg load failed:', e);
throw new Error('No se pudo inicializar ffmpeg en el navegador: ' + (e.message || e));
}
}
async function convertWebmToOgg(file) {
await ensureFFmpeg();
const inName = 'input.webm';
const outName = 'output.ogg';
try {
showAlert('Convirtiendo audio a OGG... puede tardar unos segundos', 'info');
// fetchFile helper puede fallar en algunas builds; intentar con fetch si es necesario
let data;
if (ffmpegInstance._fetchFile) {
data = await ffmpegInstance._fetchFile(file);
} else if (window.FFmpeg && window.FFmpeg.fetchFile) {
data = await window.FFmpeg.fetchFile(file);
} else {
// fallback: leer como ArrayBuffer
data = new Uint8Array(await file.arrayBuffer());
}
ffmpegInstance.FS('writeFile', inName, data);
await ffmpegInstance.run('-i', inName, '-c:a', 'libopus', '-b:a', '64k', outName);
const outData = ffmpegInstance.FS('readFile', outName);
const blob = new Blob([outData.buffer], { type: 'audio/ogg' });
const newName = (file.name || 'audio').replace(/\.[^/.]+$/, '') + '.ogg';
const outFile = new File([blob], newName, { type: 'audio/ogg' });
return outFile;
} catch (err) {
console.error('Error converting to OGG (client):', err);
throw err;
}
}
// 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';
}
// Helper: mapear URLs externas a proxy seguro cuando sea necesario
function ensureProxyUrl(u, download = false) {
if (!isValidMediaUrl(u)) return '';
// Si ya es una URL interna o una ruta proxy, devolverla tal cual
if (u.startsWith('/') || u.indexOf('/api/version/media-url.php') === 0) return u;
try {
const parsed = new URL(u);
const host = parsed.host.toLowerCase();
// Si es Facebook lookaside / graph, preferir proxy para añadir Authorization
if (host.includes('lookaside.fbsbx.com') || host.includes('facebook.com') || host.includes('graph.facebook.com')) {
return `/api/version/media-url.php?url=${encodeURIComponent(u)}${download ? '&download=1' : ''}`;
}
} catch (e) {
// Si no es URL absoluta, devolver tal cual
}
return u;
}
// 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>`;
// Mostrar badge de atención si existe
try {
const advisorBadge = document.getElementById('advisorBadge');
if (advisorBadge) {
advisorBadge.style.display = currentUser.advisor_requested ? 'inline-block' : 'none';
}
} catch (e) {
// ignore
}
// 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 = '';
for (let i = 0; i < conversations.length; i++) {
const msg = conversations[i];
const prev = conversations[i-1] || null;
const isOutgoing = msg.direction === 'outgoing';
let messageClass = isOutgoing ? 'message-outgoing' : 'message-incoming';
// Agrupar si el mensaje anterior es del mismo lado y está cerca en el tiempo (5 min)
try {
if (prev && prev.direction === msg.direction) {
const t1 = new Date(prev.created_at).getTime();
const t2 = new Date(msg.created_at).getTime();
if (!isNaN(t1) && !isNaN(t2) && (Math.abs(t2 - t1) <= (5 * 60 * 1000))) {
messageClass += ' grouped';
}
}
} catch (e) {
// ignore parsing errors
}
// 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
// Declarar variables de media aquí para evitar TDZ (referencias en otros `case`)
let thumbUrl = '';
let fullUrl = '';
switch (msg.message_type) {
case 'image':
// Determinar miniatura y URL completa (prioriza media_url_external o archivos locales)
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;
}
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
let mediaSrcVid = isValidMediaUrl(fullUrl) ? fullUrl : (isValidMediaUrl(thumbUrl) ? thumbUrl : (isValidMediaUrl(msg.media_url) ? msg.media_url : (isValidMediaUrl(msg.media_url_external) ? msg.media_url_external : '')));
// Mapear a proxy si es necesario (Facebook/media protegida)
if (isValidMediaUrl(mediaSrcVid)) {
mediaSrcVid = ensureProxyUrl(mediaSrcVid);
}
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
let mediaSrcAudio = isValidMediaUrl(fullUrl) ? fullUrl : (isValidMediaUrl(thumbUrl) ? thumbUrl : (isValidMediaUrl(msg.media_url) ? msg.media_url : (isValidMediaUrl(msg.media_url_external) ? msg.media_url_external : '')));
// Mapear a proxy si es necesario (Facebook/media protegida)
if (isValidMediaUrl(mediaSrcAudio)) {
mediaSrcAudio = ensureProxyUrl(mediaSrcAudio);
}
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
// Detectar mensajes 'system' embebidos en content (JSON)
let alertInfo = null;
try {
const parsed = JSON.parse(msg.content || '');
if (parsed && parsed.system) {
alertInfo = parsed;
}
} catch (e) {
// No es JSON, seguir
}
if (alertInfo) {
contentHtml = `<div class="message-text fw-bold">${escapeHtml(alertInfo.text || '[Atención]')}</div>`;
// Añadir clase especial a la burbuja
// marca el mensaje como requiring attention mediante messageClass
// we'll append an additional class later
messageClass += ' message-alert';
} else {
const textContent = msg.content || '';
contentHtml = textContent ? `<div class="message-text">${escapeHtml(textContent)}</div>` : '<em>Sin contenido</em>';
}
}
const messageTime = escapeHtml(msg.time || '');
// Status ticks (solo en salientes)
let statusHtml = '';
if (isOutgoing) {
const s = (msg.status || '').toLowerCase();
if (s === 'read' || s === 'seen') {
statusHtml = '<i class="fas fa-check-double text-primary" title="Leído"></i>';
} else if (s === 'delivered') {
statusHtml = '<i class="fas fa-check-double text-muted" title="Entregado"></i>';
} else if (s === 'sent') {
statusHtml = '<i class="fas fa-check text-muted" title="Enviado"></i>';
} else {
statusHtml = '';
}
}
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} ${statusHtml}
</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;
option.dataset.templateId = template.id || '';
templateSelect.appendChild(option);
});
// Valor por defecto global para la plantilla seleccionada
window.language = 'en_US';
window.currentTemplateId = null;
// 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';
window.currentTemplateId = sel && sel.dataset && sel.dataset.templateId ? sel.dataset.templateId : null;
});
// 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;
window.currentTemplateId = templateSelect.selectedOptions[0].dataset.templateId;
}
}
} 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;
}
// Verificar si la plantilla tiene variables
if (window.currentTemplateId) {
await checkTemplateVariables(window.currentTemplateId, template, language);
} else {
// Plantilla sin variables, enviar directo
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,
language,
parameters,
user: currentUser
});
// Preparar parámetros según el formato
let paramArray = [];
if (Array.isArray(parameters)) {
paramArray = parameters;
} else if (typeof parameters === 'string' && parameters) {
paramArray = parameters.split(',').map(p => p.trim());
} else {
paramArray = [];
}
const requestBody = {
recipient: currentUser.phone_number,
type: 'template',
template: template,
language: language || 'en_US',
parameters: paramArray
};
console.log('Request body:', requestBody);
const response = await whatsappManager.apiCall('send_message.php', {
body: requestBody
});
console.log('Response:', response);
hideTyping();
if (response && response.success) {
const displayMsg = paramArray.length > 0 ?
`Plantilla: ${template} (con ${paramArray.length} variable(s))` :
`Plantilla: ${template}`;
addMessageToView(displayMsg, '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"><div class="message-text">${escapeHtml(message)}</div></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 inicialmente
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
});
let uploadData = await uploadResponse.json();
if (!uploadData.success) {
throw new Error(uploadData.error || 'Error subiendo archivo');
}
// Si el servidor no pudo convertir (p. ej. shell_exec disabled), intentar conversión en navegador y re-subir
let clientConversionTried = false;
if (uploadData.conversion_error && selectedFile && selectedFile.type === 'audio/webm') {
console.debug('Server conversion failed:', uploadData.conversion_error);
showAlert('Servidor no pudo convertir el audio; intentando conversión local en el navegador...', 'info');
try {
clientConversionTried = true;
const converted = await convertWebmToOgg(selectedFile);
// Re-subir archivo convertido
const formData2 = new FormData();
formData2.append('file', converted);
formData2.append('uploaded_by', userId);
const uploadResponse2 = await fetch('api/upload_media.php', {
method: 'POST',
body: formData2
});
const uploadData2 = await uploadResponse2.json();
if (!uploadData2.success) {
throw new Error(uploadData2.error || 'Error subiendo archivo convertido');
}
uploadData = uploadData2; // usar el resultado de la re-subida
selectedFile = converted; // actualizar selectedFile a la versión convertida
showAlert('Conversión local completada y archivo subido correctamente', 'success');
console.debug('Client-side conversion and reupload succeeded');
} catch (convErr) {
console.error('Client-side conversion failed:', convErr);
showAlert('No se pudo convertir el audio en el navegador: ' + (convErr.message || convErr), 'danger');
// seguimos con el archivo original subido; avisamos al usuario
}
}
// Si aún hay conversion_error y no se intentó conversión en cliente, avisar
if (uploadData.conversion_error && !clientConversionTried) {
showAlert('Advertencia: La conversión de audio no se realizó en el servidor. El audio puede no reproducirse en algunos clientes. (' + uploadData.conversion_error + ')', 'warning');
}
// 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 class="message-text" 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();
}
// Variables globales para el modal de plantillas
let currentTemplateData = null;
// Verificar si la plantilla tiene variables
async function checkTemplateVariables(templateId, templateName, language) {
try {
const response = await whatsappManager.apiCall(`get_template_details.php?id=${templateId}`);
if (response && response.success && response.template) {
currentTemplateData = response.template;
if (response.template.has_variables) {
// Mostrar modal para llenar variables
showTemplateVariablesModal(response.template);
} else {
// Enviar directo sin variables
await sendTemplateMessage(templateName, language, []);
}
} else {
throw new Error('No se pudo obtener detalles de la plantilla');
}
} catch (error) {
console.error('Error checking template variables:', error);
showAlert('Error al cargar detalles de plantilla: ' + error.message, 'danger');
}
}
// Mostrar modal con campos para variables
function showTemplateVariablesModal(template) {
// Actualizar información del encabezado
document.getElementById('templateNameDisplay').textContent = template.name;
document.getElementById('templateLanguageDisplay').textContent = `Idioma: ${template.language_code}`;
document.getElementById('templateVariablesCount').textContent = `${template.variables_count} variable(s) requerida(s)`;
// Generar formulario de variables
const formContainer = document.getElementById('variablesForm');
formContainer.innerHTML = '';
template.variables.forEach((variable, index) => {
const fieldHtml = `
<div class="mb-3">
<label class="form-label">
<strong>${variable.label}</strong>
${variable.example ? `<small class="text-muted">(ej: ${variable.example})</small>` : ''}
</label>
<input type="text"
class="form-control template-variable-input"
data-index="${index}"
data-var-number="${variable.index}"
placeholder="${variable.example || 'Ingrese valor...'}"
required>
</div>
`;
formContainer.insertAdjacentHTML('beforeend', fieldHtml);
});
// Event listeners para actualizar preview en tiempo real
const inputs = formContainer.querySelectorAll('.template-variable-input');
inputs.forEach(input => {
input.addEventListener('input', updateTemplatePreview);
});
// Inicializar preview vacío
updateTemplatePreview();
// Mostrar modal
const modal = new bootstrap.Modal(document.getElementById('templateVariablesModal'));
modal.show();
// Event listener para botón de envío
document.getElementById('btnSendTemplateWithVariables').onclick = sendTemplateWithVariables;
}
// Actualizar vista previa de la plantilla
async function updateTemplatePreview() {
if (!currentTemplateData) return;
const inputs = document.querySelectorAll('.template-variable-input');
const parameters = [];
inputs.forEach(input => {
parameters.push(input.value || '');
});
try {
const response = await whatsappManager.apiCall('preview_template.php', {
body: {
template_id: currentTemplateData.id,
parameters: parameters
}
});
if (response && response.success && response.preview) {
const previewContainer = document.getElementById('templatePreview');
if (response.preview.is_complete) {
previewContainer.innerHTML = response.preview.html;
previewContainer.className = 'p-3 bg-light rounded border border-success';
} else {
previewContainer.innerHTML = response.preview.html +
'<div class="text-warning mt-2"><small><i class="fas fa-exclamation-triangle"></i> Faltan variables por completar</small></div>';
previewContainer.className = 'p-3 bg-light rounded border border-warning';
}
}
} catch (error) {
console.error('Error updating preview:', error);
}
}
// Enviar plantilla con variables
async function sendTemplateWithVariables() {
if (!currentTemplateData) return;
const inputs = document.querySelectorAll('.template-variable-input');
const parameters = [];
let allFilled = true;
inputs.forEach(input => {
const value = input.value.trim();
if (!value) {
allFilled = false;
input.classList.add('is-invalid');
} else {
input.classList.remove('is-invalid');
}
parameters.push(value);
});
if (!allFilled) {
showAlert('Por favor complete todas las variables requeridas', 'warning');
return;
}
// Cerrar modal
const modal = bootstrap.Modal.getInstance(document.getElementById('templateVariablesModal'));
modal.hide();
// Enviar plantilla con parámetros
await sendTemplateMessage(
currentTemplateData.template_name,
currentTemplateData.language_code,
parameters
);
// Limpiar datos
currentTemplateData = null;
}
</script>
<!-- Modal para Variables de Plantilla -->
<div class="modal fade" id="templateVariablesModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-success text-white">
<h5 class="modal-title">
<i class="fas fa-edit"></i> Completar Variables de Plantilla
</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div id="templateInfo" class="alert alert-info mb-3">
<strong id="templateNameDisplay"></strong>
<div class="small mt-1">
<span id="templateLanguageDisplay"></span> |
<span id="templateVariablesCount"></span>
</div>
</div>
<div id="variablesForm"></div>
<div class="mt-3">
<h6 class="border-bottom pb-2">
<i class="fas fa-eye"></i> Vista Previa
</h6>
<div id="templatePreview" class="p-3 bg-light rounded" style="min-height: 80px;">
<em class="text-muted">Complete los campos para ver la vista previa...</em>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
Cancelar
</button>
<button type="button" class="btn btn-success" id="btnSendTemplateWithVariables">
<i class="fas fa-paper-plane"></i> Enviar Mensaje
</button>
</div>
</div>
</div>
</div>
</body>
</html>