Files
sistema_para_juego/discord/views/messages/sent.php

378 lines
13 KiB
PHP
Executable File

<?php
session_start();
// Habilitar logging para depuración
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
$userData = JWTAuth::requireAuth();
$db = getDB();
// Paginación
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;
// Obtener estado de filtro si existe
$filterStatus = $_GET['status'] ?? 'todos'; // Default a 'todos'
// Construir la cláusula WHERE para filtrar por estado
$whereClause = "WHERE m.estado != 'deshabilitado'"; // No mostrar deshabilitados por defecto en la lista principal
$params = [];
if ($filterStatus !== 'todos') {
$whereClause = "WHERE m.estado = ?";
$params[] = $filterStatus;
}
// Obtener total de mensajes (según filtro)
$stmt = $db->prepare("SELECT COUNT(*) FROM mensajes_discord m {$whereClause}");
$stmt->execute($params);
$totalMessages = $stmt->fetchColumn();
$totalPages = ceil($totalMessages / $limit);
// Obtener mensajes (según filtro)
$stmt = $db->prepare("
SELECT m.*, u.username
FROM mensajes_discord m
LEFT JOIN usuarios u ON m.usuario_id = u.id
{$whereClause}
ORDER BY m.fecha_envio DESC
LIMIT ? OFFSET ?
");
$stmt->bindValue(count($params) + 1, $limit, PDO::PARAM_INT);
$stmt->bindValue(count($params) + 2, $offset, PDO::PARAM_INT);
// Bind WHERE parameters manually
foreach ($params as $k => $v) {
$stmt->bindValue($k + 1, $v);
}
$stmt->execute();
$mensajes = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="<?php echo $userData->idioma ?? 'es'; ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mensajes - Discord</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root {
--discord-color: #5865F2;
--discord-dark: #4752C4;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, var(--discord-color) 0%, var(--discord-dark) 100%);
min-height: 100vh;
padding: 20px;
}
.header {
background: white;
border-radius: 15px;
padding: 20px 30px;
margin-bottom: 30px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}
.header h1 {
color: var(--discord-color);
font-size: 24px;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.messages-list {
display: flex;
flex-direction: column;
gap: 15px;
}
.message-card {
background: white;
border-radius: 15px;
padding: 20px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
transition: all 0.3s;
}
.message-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}
.message-header {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
font-size: 14px;
color: #666;
}
.message-dest {
font-weight: 600;
color: var(--discord-color);
background: #eef0ff;
padding: 2px 8px;
border-radius: 10px;
}
.message-status {
font-weight: 600;
padding: 2px 8px;
border-radius: 10px;
text-transform: capitalize;
color: white;
}
.status-enviado { background-color: #28a745; }
.status-pendiente { background-color: #ffc107; }
.status-fallido { background-color: #dc3545; }
.status-deshabilitado { background-color: #6c757d; }
.message-content {
background: #f8f9fa;
padding: 15px;
border-radius: 10px;
margin-bottom: 10px;
font-family: monospace;
white-space: pre-wrap;
max-height: 100px;
overflow-y: auto;
}
.message-footer {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 13px;
color: #999;
}
.btn {
padding: 8px 16px;
border-radius: 8px;
text-decoration: none;
transition: all 0.2s;
border: none;
cursor: pointer;
font-size: 14px;
font-weight: 600;
}
.btn-secondary {
background: #6c757d;
color: white;
}
.btn-primary {
background: var(--discord-color);
color: white;
}
.pagination {
display: flex;
justify-content: center;
gap: 10px;
margin-top: 30px;
}
.page-link {
background: white;
color: var(--discord-color);
padding: 8px 12px;
border-radius: 5px;
text-decoration: none;
font-weight: 600;
}
.page-link.active {
background: var(--discord-color);
color: white;
}
.empty-state {
background: white;
border-radius: 15px;
padding: 40px;
text-align: center;
color: #666;
}
.filter-buttons {
display: flex;
gap: 10px;
margin-bottom: 20px;
justify-content: center;
}
.filter-buttons .btn {
padding: 8px 15px;
font-size: 13px;
border: 1px solid #ddd;
color: #333;
background-color: #f8f9fa;
}
.filter-buttons .btn.active {
background-color: var(--discord-color);
color: white;
border-color: var(--discord-color);
}
</style>
</head>
<body>
<div class="header">
<h1><i class="fas fa-history"></i> Historial de Mensajes Discord</h1>
<div style="display: flex; gap: 10px;">
<a href="/discord/dashboard_discord.php" class="btn btn-secondary">
<i class="fas fa-arrow-left"></i> Volver
</a>
<a href="create.php" class="btn btn-primary">
<i class="fas fa-plus"></i> Nuevo Mensaje
</a>
</div>
</div>
<div class="container">
<div class="filter-buttons">
<a href="?status=todos" class="btn <?php echo $filterStatus === 'todos' ? 'active' : ''; ?>">Todos</a>
<a href="?status=enviado" class="btn <?php echo $filterStatus === 'enviado' ? 'active' : ''; ?>">Enviados</a>
<a href="?status=pendiente" class="btn <?php echo $filterStatus === 'pendiente' ? 'active' : ''; ?>">Pendientes</a>
<a href="?status=fallido" class="btn <?php echo $filterStatus === 'fallido' ? 'active' : ''; ?>">Fallidos</a>
<a href="?status=deshabilitado" class="btn <?php echo $filterStatus === 'deshabilitado' ? 'active' : ''; ?>">Deshabilitados</a>
</div>
<?php if (empty($mensajes)): ?>
<div class="empty-state">
<i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 20px; color: #ddd;"></i>
<h2>No hay mensajes en este estado</h2>
<p>Los mensajes que cumplan este criterio aparecerán aquí.</p>
</div>
<?php else: ?>
<div class="messages-list">
<?php foreach ($mensajes as $msg): ?>
<div class="message-card">
<div class="message-header">
<div>
Enviado a: <span class="message-dest"><?php echo htmlspecialchars($msg['canal_id']); ?></span>
</div>
<div>
<span class="message-status status-<?php echo htmlspecialchars($msg['estado']); ?>">
<?php echo htmlspecialchars($msg['estado']); ?>
</span>
<i class="fas fa-clock" style="margin-left: 10px;"></i> <?php echo date('d/m/Y H:i', strtotime($msg['fecha_envio'] ?? 'now')); ?>
</div>
</div>
<div class="message-content"><?php echo strip_tags($msg['contenido']); ?></div>
<div class="message-footer">
<div>
<i class="fas fa-user"></i> Por: <?php echo htmlspecialchars($msg['username'] ?? 'Sistema'); ?>
</div>
<div>
ID Discord: <?php echo htmlspecialchars($msg['mensaje_discord_id'] ?? 'N/A'); ?>
<button class="btn btn-warning btn-sm" onclick="retryMessage(<?php echo $msg['id']; ?>)" style="margin-left: 15px;">
<i class="fas fa-sync-alt"></i> Reintentar
</button>
<button class="btn btn-danger btn-sm" onclick="deleteMessage(<?php echo $msg['id']; ?>)" style="margin-left: 5px;">
<i class="fas fa-trash"></i> Eliminar
</button>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php if ($totalPages > 1): ?>
<div class="pagination">
<?php for ($i = 1; $i <= $totalPages; $i++): ?>
<a href="?page=<?php echo $i; ?>&status=<?php echo htmlspecialchars($filterStatus); ?>" class="page-link <?php echo $i === $page ? 'active' : ''; ?>">
<?php echo $i; ?>
</a>
<?php endfor; ?>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
<script>
async function retryMessage(messageId) {
if (!confirm('¿Estás seguro de que quieres volver a poner este mensaje en la cola como "pendiente"?')) {
return;
}
try {
const response = await fetch('/discord/api/messages/retry.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: messageId })
});
const result = await response.json();
if (result.success) {
alert('Mensaje marcado como pendiente.');
location.reload();
} else {
alert('Error al reintentar el mensaje: ' + (result.error || 'Error desconocido.'));
}
} catch (error) {
console.error('Error al enviar la solicitud de reintento:', error);
alert('Error de conexión al intentar reintentar el mensaje.');
}
}
async function deleteMessage(messageId) {
if (!confirm('¿Estás seguro de que quieres eliminar/deshabilitar este mensaje?')) {
return;
}
try {
const response = await fetch('/discord/api/messages/delete.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: messageId })
});
const result = await response.json();
if (result.success) {
alert('Mensaje deshabilitado correctamente.');
location.reload(); // Recargar la página para actualizar la lista
} else {
alert('Error al deshabilitar el mensaje: ' + (result.error || 'Error desconocido.'));
}
} catch (error) {
console.error('Error al enviar la solicitud de eliminación:', error);
alert('Error de conexión al intentar deshabilitar el mensaje.');
}
}
</script>
</body>
</html>