funcional
This commit is contained in:
+575
@@ -0,0 +1,575 @@
|
||||
<?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;
|
||||
}
|
||||
</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>
|
||||
|
||||
<div class="input-group">
|
||||
<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
|
||||
document.getElementById('userName').textContent = currentUser.name || 'Usuario';
|
||||
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';
|
||||
const messageContent = 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">${messageContent}</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() {
|
||||
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');
|
||||
}
|
||||
|
||||
// Inicializar cuando la página se carga
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
loadUserData();
|
||||
|
||||
// Auto-refresh cada 30 segundos para nuevos mensajes
|
||||
setInterval(refreshChat, 30000);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user