1133 lines
42 KiB
PHP
1133 lines
42 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-messages {
|
|
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;
|
|
}
|
|
|
|
.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 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-messages" id="chatMessages">
|
|
<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>
|
|
|
|
<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>
|
|
</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}`);
|
|
}
|
|
|
|
return await response.json();
|
|
}
|
|
}
|
|
|
|
// Inicializar manager
|
|
whatsappManager = new WhatsAppManager();
|
|
|
|
// Función para escapar HTML
|
|
function escapeHtml(text) {
|
|
if (!text) return '';
|
|
const map = {
|
|
'&': '&',
|
|
'<': '<',
|
|
'>': '>',
|
|
'"': '"',
|
|
"'": '''
|
|
};
|
|
return text.toString().replace(/[&<>"']/g, function(m) { return map[m]; });
|
|
}
|
|
|
|
// 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 = `
|
|
${escapeHtml(displayName)}
|
|
${phoneNumber ? `<br><small class="opacity-75">${escapeHtml(phoneNumber)}</small>` : ''}
|
|
`;
|
|
document.getElementById('userAvatar').innerHTML =
|
|
`<span>${(currentUser.name || 'U').charAt(0).toUpperCase()}</span>`;
|
|
|
|
// Cargar mensajes
|
|
displayMessages(response.messages);
|
|
|
|
// Cargar plantillas
|
|
loadTemplates();
|
|
|
|
} else {
|
|
showError('Error cargando datos del usuario');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error:', error);
|
|
showError('Error cargando conversación: ' + error.message);
|
|
}
|
|
}
|
|
|
|
// Mostrar mensajes
|
|
function displayMessages(messages) {
|
|
const chatMessages = document.getElementById('chatMessages');
|
|
|
|
if (!messages || messages.length === 0) {
|
|
chatMessages.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 = '';
|
|
messages.forEach(msg => {
|
|
const isOutgoing = msg.direction === 'outgoing';
|
|
const messageClass = isOutgoing ? 'message-outgoing' : 'message-incoming';
|
|
|
|
// Verificar si es multimedia
|
|
let contentHtml = '';
|
|
if (msg.media_url) {
|
|
// Mensaje multimedia
|
|
switch (msg.media_type) {
|
|
case 'image':
|
|
contentHtml = `<img src="${msg.media_url}" alt="Imagen" style="max-width: 100%; border-radius: 8px;">`;
|
|
break;
|
|
case 'video':
|
|
contentHtml = `<video controls style="max-width: 100%; border-radius: 8px;"><source src="${msg.media_url}"></video>`;
|
|
break;
|
|
case 'audio':
|
|
contentHtml = `<audio controls style="width: 100%;"><source src="${msg.media_url}"></audio>`;
|
|
break;
|
|
case 'document':
|
|
const filename = msg.filename || 'Documento';
|
|
contentHtml = `<a href="${msg.media_url}" target="_blank" class="message-document">
|
|
<i class="fas fa-file-alt"></i>
|
|
<span>${filename}</span>
|
|
</a>`;
|
|
break;
|
|
}
|
|
|
|
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>
|
|
`;
|
|
});
|
|
|
|
chatMessages.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 => {
|
|
templateSelect.innerHTML += `<option value="${template.name}">${template.display_name || template.name}</option>`;
|
|
});
|
|
}
|
|
} 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, 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, parameters) {
|
|
try {
|
|
showTyping();
|
|
|
|
console.log('Enviando plantilla:', {
|
|
template,
|
|
parameters,
|
|
user: currentUser
|
|
});
|
|
|
|
const requestBody = {
|
|
recipient: currentUser.phone_number,
|
|
type: 'template',
|
|
template: template,
|
|
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 chatMessages = document.getElementById('chatMessages');
|
|
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>
|
|
`;
|
|
|
|
chatMessages.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 chatMessages = document.getElementById('chatMessages');
|
|
chatMessages.scrollTop = chatMessages.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);
|
|
}
|
|
|
|
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 chatMessages = document.getElementById('chatMessages');
|
|
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;
|
|
chatMessages.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);
|
|
});
|
|
</script>
|
|
</body>
|
|
</html>
|