Finished messenger

This commit is contained in:
2026-01-12 10:41:05 +01:00
parent 674fabb715
commit a4d386f2c5
11 changed files with 2069 additions and 426 deletions

View File

@@ -2,98 +2,82 @@
<h1>Messenger</h1>
<?php $this->renderFeedbackMessages(); ?>
<!-- Add user ID for JavaScript -->
<meta name="user-id" content="<?= Session::get('user_id') ?>">
<script src="<?= Config::get('URL') ?>public/js/messaging.js"></script>
<div style="display: flex; gap: 20px; margin-top: 20px;">
<!-- Left Sidebar -->
<div class="messenger-container">
<div style="width: 300px;" class="messaging-sidebar">
<div style="margin-bottom: 20px; padding: 15px; background: #f5f5f5; border: 1px solid #ddd;">
<h3 style="margin: 0 0 15px 0;">Channels</h3>
<div onclick="loadGlobalChat()" style="display: block; padding: 10px; margin-bottom: 8px; background: white; border: 1px solid #ddd; text-decoration: none; color: #333; cursor: pointer; transition: background-color 0.2s;" onmouseover="this.style.backgroundColor='#f0f0f0'" onmouseout="this.style.backgroundColor='white'" id="global-chat-link">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="color: #2196F3;">#</span>
<div class="sidebar-section">
<h3>Channels</h3>
<div onclick="loadGlobalChat()" class="chat-item" id="global-chat-link">
<div class="chat-item-title">
<span class="chat-item-icon" style="color: #2196F3;">#</span>
<strong>Global Chat</strong>
</div>
<small style="color: #666; font-size: 11px;">Public chatroom</small>
<div class="chat-item-meta">Public chatroom</div>
</div>
</div>
<div style="margin-bottom: 20px; padding: 15px; background: #f5f5f5; border: 1px solid #ddd;">
<h3 style="margin: 0 0 15px 0;">Direct Messages</h3>
<div class="sidebar-section">
<h3>Direct Messages</h3>
<?php if (empty($this->conversations)): ?>
<p style="text-align: center; padding: 20px; background: white; border: 1px solid #ddd;">No conversations yet</p>
<p class="chat-item" style="text-align: center; cursor: default;">No conversations yet</p>
<?php else: ?>
<?php foreach ($this->conversations as $conv): ?>
<div onclick="loadConversation(<?= $conv->other_user_id ?>, '<?= htmlspecialchars(addslashes($conv->user_name)) ?>')"
style="display: block; padding: 10px; margin-bottom: 8px; background: white; border: 1px solid #ddd; text-decoration: none; color: #333; cursor: pointer; transition: background-color 0.2s;"
onmouseover="this.style.backgroundColor='#f0f0f0'"
onmouseout="this.style.backgroundColor='white'"
<div onclick="loadConversation(<?= $conv->other_user_id ?>, '<?= htmlspecialchars(addslashes($conv->user_name)) ?>')"
class="chat-item"
id="conversation-<?= $conv->other_user_id ?>">
<div style="display: flex; justify-content: space-between; align-items: center;">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="color: #4CAF50;">@</span>
<div class="chat-item-header">
<div class="chat-item-title">
<span class="chat-item-icon" style="color: #4CAF50;">@</span>
<strong><?= htmlspecialchars($conv->user_name) ?></strong>
</div>
<?php if ($conv->unread_count > 0): ?>
<span style="background: #f44336; color: white; padding: 2px 6px; border-radius: 10px; font-size: 11px;">
<?= $conv->unread_count ?>
</span>
<span class="unread-badge"><?= $conv->unread_count ?></span>
<?php endif; ?>
</div>
<small style="color: #666; font-size: 11px;"><?= date('M j, H:i', strtotime($conv->last_message_time)) ?></small>
<div class="chat-item-meta"><?= date('M j, H:i', strtotime($conv->last_message_time)) ?></div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<div style="padding: 15px; background: #f5f5f5; border: 1px solid #ddd;">
<h3 style="margin: 0 0 15px 0;">New Message</h3>
<form action="<?= Config::get('URL') ?>message/send" method="post" id="message-form">
<select name="receiver_id" style="width: 100%; padding: 8px; margin-bottom: 8px; border: 1px solid #ddd;" required>
<div class="sidebar-section">
<h3>New Message</h3>
<form action="<?= Config::get('URL') ?>message/send" method="post" id="message-form" class="new-message-form">
<select name="receiver_id" required>
<option value="">Select user</option>
<?php foreach ($this->all_users as $user): ?>
<option value="<?= $user->user_id ?>"><?= htmlspecialchars($user->user_name) ?></option>
<?php endforeach; ?>
</select>
<input type="text" name="subject" placeholder="Subject" style="width: 100%; padding: 8px; margin-bottom: 8px; border: 1px solid #ddd; max-width: 250px;" required>
<textarea name="message" placeholder="Message" style="width: 100%; padding: 8px; margin-bottom: 8px; border: 1px solid #ddd; height: 60px; resize: vertical; max-width: 250px;" required></textarea>
<button type="submit" class="button">Send Message</button>
<input type="hidden" name="subject" value="Direct Message">
<textarea name="message" placeholder="Type your message..." required></textarea>
<button type="submit" class="button" style="width: 100%;">Send Message</button>
</form>
</div>
</div>
<!-- Main Chat Area -->
<div style="flex: 1; border: 1px solid #ddd; background: white;" class="chat-main-area">
<div id="chat-content" style="height: 700px; min-height: 700px; display: flex; flex-direction: column;">
<!-- Default state -->
<div id="default-state" style="flex: 1; display: flex; align-items: center; justify-content: center; background: #f9f9f9;">
<div style="text-align: center; padding: 60px 20px; color: #666;">
<h3 style="margin: 0 0 10px 0;">Welcome to Messenger</h3>
<div style="flex: 1;" class="chat-main-area">
<div id="chat-content">
<div id="default-state">
<div class="default-welcome">
<h3>Welcome to Messenger</h3>
<p>Select Global Chat or a conversation to start messaging</p>
<small style="color: #999;">Click on any channel or conversation in the sidebar</small>
<small>Click on any channel or conversation in the sidebar</small>
</div>
</div>
<!-- Chat interface (hidden by default) -->
<div id="chat-interface" style="display: none; flex: 1; flex-direction: column;">
<!-- Chat header -->
<div id="chat-header" style="padding: 15px; border-bottom: 1px solid #ddd; background: #f5f5f5; display: flex; justify-content: space-between; align-items: center;">
<div id="chat-interface">
<div id="chat-header">
<div id="chat-title"></div>
<div id="chat-actions"></div>
</div>
<!-- Messages container -->
<div id="messages-container" style="flex: 1; padding: 20px; overflow-y: auto;">
<!-- Messages will be loaded here -->
</div>
<!-- Message input -->
<div id="message-input-area" style="padding: 15px; border-top: 1px solid #ddd; background: #f5f5f5;">
<!-- Message input will be loaded here -->
</div>
<div id="messages-container"></div>
<div id="message-input-area"></div>
</div>
</div>
</div>
@@ -101,40 +85,168 @@
</div>
<style>
.messenger-container {
display: flex;
gap: 20px;
margin-top: 20px;
align-items: flex-start;
}
.messaging-sidebar {
height: fit-content;
width: 300px;
flex-shrink: 0;
}
.sidebar-section {
margin-bottom: 20px;
padding: 15px;
background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
border: 1px solid #e0e0e0;
border-radius: 8px;
}
.sidebar-section h3 {
margin: 0 0 15px 0;
font-size: 14px;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #555;
}
.chat-main-area {
height: auto;
flex: 1;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
border: 1px solid #e0e0e0;
background: white;
}
#chat-content {
height: 600px;
display: flex;
flex-direction: column;
}
#default-state {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(180deg, #f5f7fa 0%, #fafbfc 100%);
}
#chat-interface {
display: none;
flex-direction: column;
height: 100%;
}
#chat-header {
padding: 15px;
border-bottom: 1px solid #e0e0e0;
background: linear-gradient(135deg, #f8f9fa 0%, #fff 100%);
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
#message-input-area {
padding: 15px;
border-top: 1px solid #e0e0e0;
background: linear-gradient(180deg, #fff 0%, #f8f9fa 100%);
flex-shrink: 0;
}
#messages-container {
background: #fafafa;
flex: 1;
overflow-y: auto;
padding: 20px;
background: linear-gradient(180deg, #f5f7fa 0%, #fafbfc 100%);
scroll-behavior: smooth;
}
.chat-item {
display: block;
padding: 12px;
margin-bottom: 8px;
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
text-decoration: none;
color: #333;
cursor: pointer;
transition: all 0.2s ease;
}
.chat-item:hover {
background: #f5f8ff;
border-color: #2196F3;
transform: translateX(3px);
}
.chat-item.active {
background: #e3f2fd;
border-color: #2196F3;
box-shadow: 0 2px 4px rgba(33,150,243,0.2);
}
.chat-item-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.chat-item-title {
display: flex;
align-items: center;
gap: 8px;
}
.chat-item-icon {
font-size: 16px;
width: 24px;
text-align: center;
}
.unread-badge {
background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
color: white;
padding: 2px 8px;
border-radius: 12px;
font-size: 11px;
font-weight: 600;
}
.chat-item-meta {
font-size: 11px;
color: #888;
margin-top: 4px;
}
.message-bubble {
display: inline-block;
max-width: 70%;
padding: 10px 15px;
padding: 12px 16px;
border-radius: 18px;
margin-bottom: 8px;
margin-bottom: 4px;
word-wrap: break-word;
line-height: 1.4;
line-height: 1.5;
box-shadow: 0 1px 2px rgba(0,0,0,0.08);
}
.message-bubble.sent {
background: #2196F3;
background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);
color: white;
border-bottom-right-radius: 4px;
border-bottom-right-radius: 6px;
}
.message-bubble.received {
background: white;
color: #333;
border: 1px solid #e0e0e0;
border-bottom-left-radius: 4px;
border: 1px solid #e8e8e8;
border-bottom-left-radius: 6px;
}
.message-time {
@@ -144,7 +256,7 @@
}
.message-row {
margin-bottom: 15px;
margin-bottom: 16px;
display: flex;
}
@@ -157,11 +269,18 @@
}
.global-message {
margin-bottom: 20px;
padding: 15px;
margin-bottom: 16px;
padding: 16px;
background: white;
border-radius: 12px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
border: 1px solid #eee;
transition: transform 0.2s ease;
}
.global-message:hover {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.global-message-header {
@@ -169,20 +288,118 @@
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
padding-bottom: 8px;
border-bottom: 1px solid #f0f0f0;
}
.global-message-sender {
display: flex;
align-items: center;
gap: 8px;
}
.sender-avatar {
width: 32px;
height: 32px;
border-radius: 50%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 600;
font-size: 14px;
}
.global-message-bubble {
color: #333;
line-height: 1.5;
color: #444;
line-height: 1.6;
word-wrap: break-word;
}
.message-input {
flex: 1;
padding: 12px 18px;
border: 2px solid #e0e0e0;
border-radius: 25px;
font-size: 14px;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
.message-input:focus {
outline: none;
border-color: #2196F3;
box-shadow: 0 0 0 3px rgba(33,150,243,0.1);
}
.send-button {
border-radius: 25px;
padding: 12px 24px;
font-weight: 600;
transition: all 0.2s ease;
}
.send-button:hover {
transform: scale(1.02);
}
.default-welcome {
text-align: center;
padding: 80px 20px;
color: #666;
}
.default-welcome h3 {
margin: 0 0 12px 0;
color: #333;
font-size: 20px;
}
.default-welcome p {
margin: 0 0 8px 0;
color: #666;
}
.default-welcome small {
color: #999;
}
.new-message-form select,
.new-message-form textarea {
width: 100%;
padding: 10px 12px;
margin-bottom: 10px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 14px;
box-sizing: border-box;
transition: border-color 0.2s ease;
}
.new-message-form select:focus,
.new-message-form textarea:focus {
outline: none;
border-color: #2196F3;
}
.new-message-form textarea {
height: 80px;
resize: vertical;
}
@media (max-width: 768px) {
.chat-main-area {
height: 500px;
margin-top: 20px;
.messenger-container {
flex-direction: column;
}
.messaging-sidebar {
width: 100% !important;
}
#chat-content {
height: 500px;
}
.message-bubble {
max-width: 85%;
}
@@ -193,32 +410,26 @@
let currentChatType = null;
let currentChatId = null;
let messagePollingInterval = null;
let isFirstLoad = true;
// Function to scroll messages container to bottom
function scrollToBottom() {
const container = document.getElementById('messages-container');
if (container) {
// Small timeout to ensure content is rendered
setTimeout(() => {
container.scrollTop = container.scrollHeight;
}, 100);
}
}
// Handle DOM ready event
document.addEventListener('DOMContentLoaded', function() {
// Check URL hash for auto-loading chats
const hash = window.location.hash.substring(1);
if (hash === 'load-global') {
// Load global chat
setTimeout(() => loadGlobalChat(), 100);
} else if (hash.startsWith('load-conversation-')) {
// Load conversation
const userId = hash.split('-')[2];
if (userId) {
setTimeout(() => {
// Get user name from the conversation list
const conversationEl = document.querySelector('#conversation-' + userId);
if (conversationEl) {
const userName = conversationEl.querySelector('strong').textContent;
@@ -232,12 +443,11 @@ document.addEventListener('DOMContentLoaded', function() {
function loadGlobalChat() {
currentChatType = 'global';
currentChatId = 'global';
// Hide default state, show chat interface
isFirstLoad = true;
document.getElementById('default-state').style.display = 'none';
document.getElementById('chat-interface').style.display = 'flex';
// Update header
document.getElementById('chat-title').innerHTML = `
<div style="display: flex; align-items: center; gap: 8px;">
<span style="color: #2196F3; font-size: 18px;">#</span>
@@ -245,40 +455,28 @@ function loadGlobalChat() {
</div>
<small style="color: #666;">Public chatroom</small>
`;
document.getElementById('chat-actions').innerHTML = `
<span style="font-size: 12px; color: #666;">
<i class="fa fa-users"></i> Public
</span>
`;
// Highlight active chat
highlightActiveChat('global');
// Load messages
loadGlobalMessages();
// Scroll to bottom after loading
setTimeout(() => {
scrollToBottom();
}, 300);
// Setup message input
setTimeout(scrollToBottom, 300);
setupGlobalMessageInput();
// Start polling for new messages
startMessagePolling();
}
function loadConversation(userId, userName) {
currentChatType = 'conversation';
currentChatId = userId;
// Hide default state, show chat interface
isFirstLoad = true;
document.getElementById('default-state').style.display = 'none';
document.getElementById('chat-interface').style.display = 'flex';
// Update header
document.getElementById('chat-title').innerHTML = `
<div style="display: flex; align-items: center; gap: 8px;">
<span style="color: #4CAF50; font-size: 18px;">@</span>
@@ -286,111 +484,103 @@ function loadConversation(userId, userName) {
</div>
<small style="color: #666;">Direct message</small>
`;
document.getElementById('chat-actions').innerHTML = `
<span style="font-size: 12px; color: #666;">
<i class="fa fa-user"></i> Private
</span>
`;
// Highlight active chat
highlightActiveChat(userId);
// Load messages
loadConversationMessages(userId);
// Scroll to bottom after loading
setTimeout(() => {
scrollToBottom();
}, 300);
// Setup message input
setTimeout(scrollToBottom, 300);
setupConversationMessageInput(userId);
// Start polling for new messages
startMessagePolling();
}
function highlightActiveChat(chatId) {
// Remove active class from all chats
document.querySelectorAll('[id^="conversation-"], [id="global-chat-link"]').forEach(el => {
el.style.backgroundColor = 'white';
el.style.borderColor = '#ddd';
});
// Add active class to current chat
const activeEl = chatId === 'global' ?
document.getElementById('global-chat-link') :
document.querySelectorAll('.chat-item').forEach(el => el.classList.remove('active'));
const activeEl = chatId === 'global' ?
document.getElementById('global-chat-link') :
document.getElementById('conversation-' + chatId);
if (activeEl) {
activeEl.style.backgroundColor = '#e8f4fd';
activeEl.style.borderColor = '#2196F3';
}
if (activeEl) activeEl.classList.add('active');
}
function loadGlobalMessages() {
function loadGlobalMessages(silent = false) {
const container = document.getElementById('messages-container');
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #666;">Loading messages...</div>';
if (isFirstLoad && !silent) {
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #666;">Loading messages...</div>';
}
fetch('<?= Config::get('URL') ?>message/getGlobalMessages')
.then(response => {
console.log('Global messages response status:', response.status);
console.log('Global messages response headers:', response.headers);
if (!response.ok) {
return response.text().then(text => {
console.error('Server returned non-JSON response for global messages:', text);
throw new Error(`HTTP error! status: ${response.status}, response: ${text.substring(0, 200)}`);
});
}
if (!response.ok) throw new Error('HTTP error: ' + response.status);
return response.json();
})
.then(data => {
if (data.success && data.messages) {
const wasAtBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 50;
displayGlobalMessages(data.messages);
} else {
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Error loading messages: ' + (data.message || 'Unknown error') + '</div>';
if (wasAtBottom) scrollToBottom();
isFirstLoad = false;
} else if (isFirstLoad) {
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Error loading messages</div>';
}
})
.catch(error => {
console.error('Error loading global messages:', error);
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Network error: ' + error.message + '</div>';
if (isFirstLoad) {
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Network error</div>';
}
});
}
function loadConversationMessages(userId) {
function loadConversationMessages(userId, silent = false) {
const container = document.getElementById('messages-container');
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #666;">Loading messages...</div>';
if (isFirstLoad && !silent) {
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #666;">Loading messages...</div>';
}
fetch(`<?= Config::get('URL') ?>message/getConversationMessages/${userId}`)
.then(response => response.json())
.then(response => {
if (!response.ok) throw new Error('HTTP error: ' + response.status);
return response.json();
})
.then(data => {
if (data.success && data.messages) {
const wasAtBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 50;
displayConversationMessages(data.messages);
} else {
if (wasAtBottom) scrollToBottom();
isFirstLoad = false;
} else if (isFirstLoad) {
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Error loading messages</div>';
}
})
.catch(error => {
console.error('Error loading conversation messages:', error);
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Network error</div>';
if (isFirstLoad) {
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Network error</div>';
}
});
}
function displayGlobalMessages(messages) {
const container = document.getElementById('messages-container');
if (messages.length === 0) {
container.innerHTML = `
<div style="text-align: center; padding: 60px 20px;">
<h4 style="color: #666;">No messages yet</h4>
<p style="color: #999;">Start the conversation!</p>
<div class="default-welcome">
<h3>No messages yet</h3>
<p>Start the conversation!</p>
</div>
`;
return;
}
container.innerHTML = messages.map(message => {
const timeString = new Date(message.created_at).toLocaleString('en-US', {
month: 'short',
@@ -398,17 +588,19 @@ function displayGlobalMessages(messages) {
hour: '2-digit',
minute: '2-digit'
});
const isOwn = message.sender_id == document.querySelector('meta[name="user-id"]').content;
const initial = message.sender_name.charAt(0).toUpperCase();
return `
<div class="global-message">
<div class="global-message-header">
<div style="display: flex; align-items: center; gap: 8px;">
<div class="global-message-sender">
<div class="sender-avatar" style="${isOwn ? 'background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);' : ''}">${initial}</div>
<strong style="color: ${isOwn ? '#2196F3' : '#333'}">
${escapeHtml(message.sender_name)}
</strong>
${isOwn ? '<span style="font-size: 10px; background: #2196F3; color: white; padding: 2px 4px; border-radius: 3px;">You</span>' : ''}
${isOwn ? '<span style="font-size: 10px; background: #2196F3; color: white; padding: 2px 6px; border-radius: 4px;">You</span>' : ''}
</div>
<span class="message-time">${timeString}</span>
</div>
@@ -418,25 +610,24 @@ function displayGlobalMessages(messages) {
</div>
`;
}).join('');
// Scroll to bottom
container.scrollTop = container.scrollHeight;
}
function displayConversationMessages(messages) {
const container = document.getElementById('messages-container');
const currentUserId = document.querySelector('meta[name="user-id"]').content;
if (messages.length === 0) {
container.innerHTML = `
<div style="text-align: center; padding: 60px 20px;">
<h4 style="color: #666;">No messages yet</h4>
<p style="color: #999;">Send a message to start the conversation!</p>
<div class="default-welcome">
<h3>No messages yet</h3>
<p>Send a message to start the conversation!</p>
</div>
`;
return;
}
container.innerHTML = messages.map(message => {
const isSent = message.sender_id == currentUserId;
const timeString = new Date(message.created_at).toLocaleString('en-US', {
@@ -445,7 +636,7 @@ function displayConversationMessages(messages) {
hour: '2-digit',
minute: '2-digit'
});
return `
<div class="message-row ${isSent ? 'sent' : 'received'}">
<div>
@@ -459,8 +650,7 @@ function displayConversationMessages(messages) {
</div>
`;
}).join('');
// Scroll to bottom
container.scrollTop = container.scrollHeight;
}
@@ -469,12 +659,12 @@ function setupGlobalMessageInput() {
inputArea.innerHTML = `
<form id="global-message-form" onsubmit="sendGlobalMessage(event)">
<div style="display: flex; gap: 10px;">
<input type="text"
name="message"
placeholder="Type your global message..."
style="flex: 1; padding: 12px; border: 1px solid #ddd; border-radius: 25px;"
<input type="text"
name="message"
placeholder="Type your global message..."
class="message-input"
required>
<button type="submit" class="button" style="border-radius: 25px; padding: 12px 20px;">Send</button>
<button type="submit" class="button send-button">Send</button>
</div>
</form>
`;
@@ -485,12 +675,12 @@ function setupConversationMessageInput(userId) {
inputArea.innerHTML = `
<form id="conversation-message-form" onsubmit="sendConversationMessage(event, ${userId})">
<div style="display: flex; gap: 10px;">
<input type="text"
name="message"
placeholder="Type your message..."
style="flex: 1; padding: 12px; border: 1px solid #ddd; border-radius: 25px;"
<input type="text"
name="message"
placeholder="Type your message..."
class="message-input"
required>
<button type="submit" class="button" style="border-radius: 25px; padding: 12px 20px;">Send</button>
<button type="submit" class="button send-button">Send</button>
</div>
</form>
`;
@@ -502,10 +692,10 @@ function sendGlobalMessage(event) {
const message = form.message.value;
const submitButton = form.querySelector('button[type="submit"]');
const originalText = submitButton.textContent;
submitButton.textContent = 'Sending...';
submitButton.disabled = true;
fetch('<?= Config::get('URL') ?>message/sendToGlobal', {
method: 'POST',
headers: {
@@ -515,32 +705,20 @@ function sendGlobalMessage(event) {
body: 'message=' + encodeURIComponent(message)
})
.then(response => {
console.log('Global message response status:', response.status);
console.log('Global message response headers:', response.headers);
if (!response.ok) {
return response.text().then(text => {
console.error('Server returned non-JSON response for global message:', text);
throw new Error(`HTTP error! status: ${response.status}, response: ${text.substring(0, 200)}`);
});
}
if (!response.ok) throw new Error('HTTP error: ' + response.status);
return response.json();
})
.then(data => {
if (data.success) {
form.reset();
loadGlobalMessages(); // Refresh messages
// Scroll to bottom after sending
setTimeout(() => {
scrollToBottom();
}, 500);
loadGlobalMessages(true);
setTimeout(scrollToBottom, 300);
} else {
alert('Failed to send message: ' + (data.message || 'Unknown error'));
}
})
.catch(error => {
console.error('Error sending global message:', error);
alert('Network error. Please try again. (' + error.message + ')');
alert('Network error. Please try again.');
})
.finally(() => {
submitButton.textContent = originalText;
@@ -554,10 +732,10 @@ function sendConversationMessage(event, userId) {
const message = form.message.value;
const submitButton = form.querySelector('button[type="submit"]');
const originalText = submitButton.textContent;
submitButton.textContent = 'Sending...';
submitButton.disabled = true;
fetch('<?= Config::get('URL') ?>message/reply', {
method: 'POST',
headers: {
@@ -567,32 +745,20 @@ function sendConversationMessage(event, userId) {
body: 'receiver_id=' + userId + '&message=' + encodeURIComponent(message)
})
.then(response => {
console.log('Response status:', response.status);
console.log('Response headers:', response.headers);
if (!response.ok) {
return response.text().then(text => {
console.error('Server returned non-JSON response:', text);
throw new Error(`HTTP error! status: ${response.status}, response: ${text.substring(0, 200)}`);
});
}
if (!response.ok) throw new Error('HTTP error: ' + response.status);
return response.json();
})
.then(data => {
if (data.success) {
form.reset();
loadConversationMessages(userId); // Refresh messages
// Scroll to bottom after sending
setTimeout(() => {
scrollToBottom();
}, 500);
loadConversationMessages(userId, true);
setTimeout(scrollToBottom, 300);
} else {
alert('Failed to send message: ' + (data.message || 'Unknown error'));
}
})
.catch(error => {
console.error('Error sending conversation message:', error);
alert('Network error. Please try again. (' + error.message + ')');
alert('Network error. Please try again.');
})
.finally(() => {
submitButton.textContent = originalText;
@@ -601,19 +767,15 @@ function sendConversationMessage(event, userId) {
}
function startMessagePolling() {
// Clear existing polling
if (messagePollingInterval) {
clearInterval(messagePollingInterval);
}
// Start new polling
if (messagePollingInterval) clearInterval(messagePollingInterval);
messagePollingInterval = setInterval(() => {
if (currentChatType === 'global') {
loadGlobalMessages();
loadGlobalMessages(true);
} else if (currentChatType === 'conversation') {
loadConversationMessages(currentChatId);
loadConversationMessages(currentChatId, true);
}
}, 3000); // Poll every 3 seconds
}, 3000);
}
function escapeHtml(text) {
@@ -622,17 +784,16 @@ function escapeHtml(text) {
return div.innerHTML;
}
// Handle new message form submission
document.getElementById('message-form').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const submitButton = this.querySelector('button[type="submit"]');
const originalText = submitButton.textContent;
submitButton.textContent = 'Sending...';
submitButton.disabled = true;
fetch(this.action, {
method: 'POST',
body: formData
@@ -642,13 +803,11 @@ document.getElementById('message-form').addEventListener('submit', function(e) {
if (data.success) {
this.reset();
showFeedback('Message sent successfully!', 'success');
// Could refresh conversation list here
} else {
showFeedback(data.message || 'Failed to send message', 'error');
}
})
.catch(error => {
console.error('Error sending message:', error);
showFeedback('Network error. Please try again.', 'error');
})
.finally(() => {
@@ -659,7 +818,6 @@ document.getElementById('message-form').addEventListener('submit', function(e) {
function showFeedback(message, type) {
const feedback = document.createElement('div');
feedback.className = `feedback-${type}`;
feedback.textContent = message;
feedback.style.cssText = `
position: fixed;
@@ -682,14 +840,12 @@ function showFeedback(message, type) {
}, 3000);
}
// Add CSS for animations
const animationStyle = document.createElement('style');
animationStyle.textContent = `
@keyframes slideIn {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slideOut {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(100%); opacity: 0; }