This commit is contained in:
2026-01-10 17:22:49 +01:00
parent edcc1b5403
commit 674fabb715
21 changed files with 2135 additions and 489 deletions

View File

@@ -1,115 +1,17 @@
<div class="container">
<div class="row">
<!-- Back to Messenger -->
<div class="col-md-12">
<a href="<?= Config::get('URL') ?>message" class="btn btn-default">
<span class="glyphicon glyphicon-arrow-left"></span> Back to Messenger
</a>
<hr>
</div>
</div>
<?php $this->render('_templates/header'); ?>
<div class="row">
<!-- Chat Area -->
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
Conversation with <?= htmlspecialchars($this->other_user->user_name) ?>
</div>
<div class="panel-body message-container">
<?php if (empty($this->messages)): ?>
<div class="text-center">
<em>No messages yet. Start a conversation!</em>
</div>
<?php else: ?>
<?php foreach ($this->messages as $msg): ?>
<div class="message <?= $msg->message_type ?>">
<div class="message-bubble">
<?= htmlspecialchars($msg->message) ?>
</div>
<div class="message-time">
<?= date('M j, Y H:i', strtotime($msg->created_at)) ?>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<!-- Reply Form -->
<div class="panel-footer">
<form action="<?= Config::get('URL') ?>message/send" method="post" id="reply-form">
<input type="hidden" name="receiver_id" value="<?= $this->other_user->user_id ?>">
<div class="input-group">
<input type="text" name="message" class="form-control" placeholder="Type your message..." required>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary">Send</button>
</span>
</div>
</form>
</div>
</div>
<div class="box">
<?php $this->renderFeedbackMessages(); ?>
<script>
// Redirect to main messages page and load conversation
window.location.href = '<?= Config::get('URL') ?>message' + '#load-conversation-<?= isset($this->other_user) ? $this->other_user->user_id : '' ?>';
</script>
<div style="text-align: center; padding: 60px;">
<h3>Redirecting to Conversation...</h3>
<p>If you're not redirected automatically, <a href="<?= Config::get('URL') ?>message">click here</a>.</p>
</div>
</div>
</div>
<style>
.message-container {
height: 400px;
overflow-y: auto;
background-color: #f5f5f5;
padding: 15px;
}
.message {
margin-bottom: 15px;
clear: both;
}
.message.sent {
text-align: right;
}
.message.received {
text-align: left;
}
.message-bubble {
display: inline-block;
max-width: 70%;
padding: 10px 15px;
border-radius: 18px;
position: relative;
word-wrap: break-word;
}
.message.sent .message-bubble {
background-color: #007bff;
color: white;
}
.message.received .message-bubble {
background-color: #e5e5ea;
color: black;
}
.message-time {
font-size: 0.8em;
color: #666;
margin-top: 5px;
}
/* Scroll to bottom of messages on load */
.message-container {
scroll-behavior: smooth;
}
</style>
<script>
// Scroll to bottom of messages
document.addEventListener('DOMContentLoaded', function() {
const container = document.querySelector('.message-container');
container.scrollTop = container.scrollHeight;
});
</script>
<?php $this->render('_templates/footer'); ?>
<?php $this->render('_templates/footer'); ?>

View File

@@ -0,0 +1,17 @@
<?php $this->render('_templates/header'); ?>
<div class="box">
<?php $this->renderFeedbackMessages(); ?>
<script>
// Redirect to main messages page and load global chat
window.location.href = '<?= Config::get('URL') ?>message' + '#load-global';
</script>
<div style="text-align: center; padding: 60px;">
<h3>Redirecting to Global Chat...</h3>
<p>If you're not redirected automatically, <a href="<?= Config::get('URL') ?>message">click here</a>.</p>
</div>
</div>
<?php $this->render('_templates/footer'); ?>

View File

@@ -1,175 +1,701 @@
<div class="container">
<h1>Messenger</h1>
<div class="box">
<h1>Messenger</h1>
<?php $this->renderFeedbackMessages(); ?>
<div class="row">
<!-- Conversations List -->
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
Conversations
<?php if ($this->unread_count > 0): ?>
<span class="badge pull-right"><?= $this->unread_count ?></span>
<?php endif; ?>
</div>
<div class="panel-body" style="padding: 0; max-height: 500px; overflow-y: auto;">
<div class="list-group">
<?php if (empty($this->conversations)): ?>
<div class="list-group-item">
<em>No conversations yet</em>
</div>
<?php else: ?>
<?php foreach ($this->conversations as $conv): ?>
<a href="<?= Config::get('URL') ?>message/conversation/<?= $conv->other_user_id ?>"
class="list-group-item <?= $conv->unread_count > 0 ? 'active' : '' ?>">
<h5 class="list-group-item-heading">
<?= htmlspecialchars($conv->user_name) ?>
<?php if ($conv->unread_count > 0): ?>
<span class="badge"><?= $conv->unread_count ?></span>
<?php endif; ?>
</h5>
<p class="list-group-item-text">
<small><?= date('M j, Y', strtotime($conv->last_message_time)) ?></small>
</p>
</a>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
</div>
<!-- Add user ID for JavaScript -->
<meta name="user-id" content="<?= Session::get('user_id') ?>">
<script src="<?= Config::get('URL') ?>public/js/messaging.js"></script>
<!-- New Message -->
<div class="panel panel-default">
<div class="panel-heading">New Message</div>
<div class="panel-body">
<form action="<?= Config::get('URL') ?>message/send" method="post">
<div class="form-group">
<label for="receiver_id">To:</label>
<select name="receiver_id" id="receiver_id" class="form-control" 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>
<div style="display: flex; gap: 20px; margin-top: 20px;">
<!-- Left Sidebar -->
<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>
<strong>Global Chat</strong>
</div>
<small style="color: #666; font-size: 11px;">Public chatroom</small>
</div>
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" class="form-control" required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea name="message" id="message" class="form-control" rows="3" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Send Message</button>
</form>
</div>
</div>
<!-- Send to Group -->
<div class="panel panel-default">
<div class="panel-heading">Send to Group</div>
<div class="panel-body">
<form action="<?= Config::get('URL') ?>message/sendgroup" method="post">
<div class="form-group">
<label for="group_type">Group:</label>
<select name="group_type" id="group_type" class="form-control" required>
<option value="">Select group</option>
<option value="all_users">All Users</option>
<option value="admins">Administrators</option>
<option value="moderators">Moderators</option>
</select>
<div style="margin-bottom: 20px; padding: 15px; background: #f5f5f5; border: 1px solid #ddd;">
<h3 style="margin: 0 0 15px 0;">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>
<?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'"
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>
<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>
<?php endif; ?>
</div>
<small style="color: #666; font-size: 11px;"><?= date('M j, H:i', strtotime($conv->last_message_time)) ?></small>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<div class="form-group">
<label for="group_subject">Subject:</label>
<input type="text" name="subject" id="group_subject" class="form-control" required>
<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>
<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>
</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>
<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>
</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-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>
</div>
<div class="form-group">
<label for="group_message">Message:</label>
<textarea name="message" id="group_message" class="form-control" rows="3" required></textarea>
</div>
<button type="submit" class="btn btn-warning">Send to Group</button>
</form>
</div>
</div>
</div>
<!-- Chat Area -->
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
Chat Area
<span class="pull-right">Select a conversation to start messaging</span>
</div>
<div class="panel-body" style="height: 500px; background-color: #f5f5f5; text-align: center; padding-top: 200px;">
<em>Select a conversation from the left to view messages</em>
</div>
</div>
</div>
</div>
</div>
<style>
.message-container {
height: 400px;
overflow-y: auto;
background-color: #f5f5f5;
padding: 15px;
border-radius: 5px;
margin-bottom: 15px;
}
.messaging-sidebar {
height: fit-content;
}
.message {
margin-bottom: 10px;
clear: both;
}
.chat-main-area {
height: auto;
}
.message.sent {
text-align: right;
}
#messages-container {
background: #fafafa;
scroll-behavior: smooth;
}
.message.received {
text-align: left;
}
.message-bubble {
.message-bubble {
display: inline-block;
max-width: 70%;
padding: 10px 15px;
border-radius: 18px;
position: relative;
}
margin-bottom: 8px;
word-wrap: break-word;
line-height: 1.4;
}
.message.sent .message-bubble {
background-color: #007bff;
.message-bubble.sent {
background: #2196F3;
color: white;
float: right;
}
border-bottom-right-radius: 4px;
}
.message.received .message-bubble {
background-color: #e5e5ea;
color: black;
float: left;
}
.message-bubble.received {
background: white;
color: #333;
border: 1px solid #e0e0e0;
border-bottom-left-radius: 4px;
}
.message-time {
font-size: 0.8em;
color: #666;
margin-top: 5px;
clear: both;
}
.message-time {
font-size: 11px;
color: #999;
margin-top: 4px;
}
.badge {
background-color: #d9534f;
}
.message-row {
margin-bottom: 15px;
display: flex;
}
.list-group-item.active {
background-color: #d9edf7;
border-color: #bce8f1;
color: #31708f;
}
.message-row.sent {
justify-content: flex-end;
}
.list-group-item.active .badge {
background-color: #d9534f;
}
.message-row.received {
justify-content: flex-start;
}
.global-message {
margin-bottom: 20px;
padding: 15px;
background: white;
border-radius: 12px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.global-message-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.global-message-bubble {
color: #333;
line-height: 1.5;
word-wrap: break-word;
}
@media (max-width: 768px) {
.chat-main-area {
height: 500px;
margin-top: 20px;
}
.message-bubble {
max-width: 85%;
}
}
</style>
<script>
let currentChatType = null;
let currentChatId = null;
let messagePollingInterval = null;
// 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;
loadConversation(userId, userName);
}
}, 100);
}
}
});
function loadGlobalChat() {
currentChatType = 'global';
currentChatId = 'global';
// Hide default state, show chat interface
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>
<strong>Global Chat</strong>
</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
setupGlobalMessageInput();
// Start polling for new messages
startMessagePolling();
}
function loadConversation(userId, userName) {
currentChatType = 'conversation';
currentChatId = userId;
// Hide default state, show chat interface
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>
<strong>${userName}</strong>
</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
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.getElementById('conversation-' + chatId);
if (activeEl) {
activeEl.style.backgroundColor = '#e8f4fd';
activeEl.style.borderColor = '#2196F3';
}
}
function loadGlobalMessages() {
const container = document.getElementById('messages-container');
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)}`);
});
}
return response.json();
})
.then(data => {
if (data.success && data.messages) {
displayGlobalMessages(data.messages);
} else {
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;">Error loading messages: ' + (data.message || 'Unknown error') + '</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>';
});
}
function loadConversationMessages(userId) {
const container = document.getElementById('messages-container');
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(data => {
if (data.success && data.messages) {
displayConversationMessages(data.messages);
} else {
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>';
});
}
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>
`;
return;
}
container.innerHTML = messages.map(message => {
const timeString = new Date(message.created_at).toLocaleString('en-US', {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
const isOwn = message.sender_id == document.querySelector('meta[name="user-id"]').content;
return `
<div class="global-message">
<div class="global-message-header">
<div style="display: flex; align-items: center; gap: 8px;">
<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>' : ''}
</div>
<span class="message-time">${timeString}</span>
</div>
<div class="global-message-bubble">
${escapeHtml(message.message)}
</div>
</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>
`;
return;
}
container.innerHTML = messages.map(message => {
const isSent = message.sender_id == currentUserId;
const timeString = new Date(message.created_at).toLocaleString('en-US', {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
return `
<div class="message-row ${isSent ? 'sent' : 'received'}">
<div>
<div class="message-bubble ${isSent ? 'sent' : 'received'}">
${escapeHtml(message.message)}
</div>
<div class="message-time" style="text-align: ${isSent ? 'right' : 'left'}">
${timeString}
</div>
</div>
</div>
`;
}).join('');
// Scroll to bottom
container.scrollTop = container.scrollHeight;
}
function setupGlobalMessageInput() {
const inputArea = document.getElementById('message-input-area');
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;"
required>
<button type="submit" class="button" style="border-radius: 25px; padding: 12px 20px;">Send</button>
</div>
</form>
`;
}
function setupConversationMessageInput(userId) {
const inputArea = document.getElementById('message-input-area');
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;"
required>
<button type="submit" class="button" style="border-radius: 25px; padding: 12px 20px;">Send</button>
</div>
</form>
`;
}
function sendGlobalMessage(event) {
event.preventDefault();
const form = event.target;
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: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
},
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)}`);
});
}
return response.json();
})
.then(data => {
if (data.success) {
form.reset();
loadGlobalMessages(); // Refresh messages
// Scroll to bottom after sending
setTimeout(() => {
scrollToBottom();
}, 500);
} 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 + ')');
})
.finally(() => {
submitButton.textContent = originalText;
submitButton.disabled = false;
});
}
function sendConversationMessage(event, userId) {
event.preventDefault();
const form = event.target;
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: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
},
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)}`);
});
}
return response.json();
})
.then(data => {
if (data.success) {
form.reset();
loadConversationMessages(userId); // Refresh messages
// Scroll to bottom after sending
setTimeout(() => {
scrollToBottom();
}, 500);
} 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 + ')');
})
.finally(() => {
submitButton.textContent = originalText;
submitButton.disabled = false;
});
}
function startMessagePolling() {
// Clear existing polling
if (messagePollingInterval) {
clearInterval(messagePollingInterval);
}
// Start new polling
messagePollingInterval = setInterval(() => {
if (currentChatType === 'global') {
loadGlobalMessages();
} else if (currentChatType === 'conversation') {
loadConversationMessages(currentChatId);
}
}, 3000); // Poll every 3 seconds
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = 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
})
.then(response => response.json())
.then(data => {
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(() => {
submitButton.textContent = originalText;
submitButton.disabled = false;
});
});
function showFeedback(message, type) {
const feedback = document.createElement('div');
feedback.className = `feedback-${type}`;
feedback.textContent = message;
feedback.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 15px 20px;
background: ${type === 'success' ? '#4caf50' : '#f44336'};
color: white;
border-radius: 4px;
z-index: 1000;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
animation: slideIn 0.3s ease;
`;
document.body.appendChild(feedback);
setTimeout(() => {
feedback.style.animation = 'slideOut 0.3s ease';
setTimeout(() => feedback.remove(), 300);
}, 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; }
}
`;
document.head.appendChild(animationStyle);
</script>
<?php $this->render('_templates/footer'); ?>

View File

@@ -1,44 +1,459 @@
<div class="container">
<h1>NoteController/index</h1>
<div class="box">
<div class="box">
<h1>My Notes</h1>
<?php $this->renderFeedbackMessages(); ?>
<!-- echo out the system feedback (error and success messages) -->
<?php $this->renderFeedbackMessages(); ?>
<div style="display: flex; gap: 20px; margin-top: 20px;">
<!-- Notes Sidebar -->
<div style="width: 300px;" class="notes-sidebar">
<div style="padding: 15px; background: #f5f5f5; border: 1px solid #ddd; margin-bottom: 20px;">
<form action="<?= Config::get('URL') ?>note/create" method="post" id="create-note-form" style="margin-bottom: 15px;">
<textarea name="note_text" placeholder="Write your note here..." style="width: 100%; max-width: 250px; padding: 8px; border: 1px solid #ddd; height: 80px; resize: vertical; margin-bottom: 10px;" required></textarea>
<button type="submit" class="button">Create Note</button>
</form>
</div>
<h3>What happens here ?</h3>
<p>
This is just a simple CRUD implementation. Creating, reading, updating and deleting things.
</p>
<p>
<form method="post" action="<?php echo Config::get('URL');?>note/create">
<label>Text of new note: </label><input type="text" name="note_text" />
<input type="submit" value='Create this note' autocomplete="off" />
</form>
</p>
<div style="padding: 15px; background: #f5f5f5; border: 1px solid #ddd;">
<h3 style="margin: 0 0 15px 0;">Your Notes</h3>
<?php if ($this->notes): ?>
<?php foreach ($this->notes as $note): ?>
<div onclick="viewNote(<?= $note->note_id ?>)" style="padding: 12px; background: white; border: 1px solid #ddd; margin-bottom: 8px; cursor: pointer; transition: background-color 0.2s;" onmouseover="this.style.backgroundColor='#f0f0f0'" onmouseout="this.style.backgroundColor='white'">
<div style="font-weight: bold; margin-bottom: 5px; word-wrap: break-word;">
<?= htmlspecialchars(substr($note->note_text, 0, 50)) ?><?= strlen($note->note_text) > 50 ? '...' : '' ?>
</div>
<div style="font-size: 12px; color: #666; margin-bottom: 8px;">
<?= date('M j, Y H:i', strtotime($note->note_timestamp)) ?>
</div>
<div style="font-size: 11px; color: #999; font-style: italic; word-wrap: break-word;">
<?= htmlspecialchars(substr(strip_tags($note->note_text), 0, 80)) ?><?= strlen(strip_tags($note->note_text)) > 80 ? '...' : '' ?>
</div>
<div style="display: flex; gap: 8px; margin-top: 8px;" onclick="event.stopPropagation()">
<a onclick="editNote(<?= $note->note_id ?>)" style="font-size: 12px; padding: 4px 8px; background: #4CAF50; color: white; text-decoration: none; border-radius: 3px;">Edit</a>
<a href="<?= Config::get('URL') ?>note/delete/<?= $note->note_id ?>" style="font-size: 12px; padding: 4px 8px; background: #f44336; color: white; text-decoration: none; border-radius: 3px;" onclick="return confirm('Are you sure you want to delete this note?');">Delete</a>
</div>
</div>
<?php endforeach; ?>
<?php else: ?>
<p style="text-align: center; padding: 20px; background: white; border: 1px solid #ddd;">No notes yet. Create your first note!</p>
<?php endif; ?>
</div>
</div>
<?php if ($this->notes) { ?>
<table class="note-table">
<thead>
<tr>
<td>Id</td>
<td>Note</td>
<td>EDIT</td>
<td>DELETE</td>
</tr>
</thead>
<tbody>
<?php foreach($this->notes as $key => $value) { ?>
<tr>
<td><?= $value->note_id; ?></td>
<td><?= htmlentities($value->note_text); ?></td>
<td><a href="<?= Config::get('URL') . 'note/edit/' . $value->note_id; ?>">Edit</a></td>
<td><a href="<?= Config::get('URL') . 'note/delete/' . $value->note_id; ?>">Delete</a></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<div>No notes yet. Create some !</div>
<?php } ?>
<!-- Notes Main Content -->
<div style="flex: 1; border: 1px solid #ddd; background: white;" class="note-main-content">
<div id="note-content" style="padding: 20px;">
<div style="text-align: center; padding: 60px 20px; color: #666; background: #f9f9f9;">
<h3>Note Viewer</h3>
<p>Select a note from the left to view its contents</p>
<small style="color: #999;">Click anywhere on a note card to view it</small>
</div>
</div>
<!-- Edit Note Form (Hidden by default) -->
<div id="note-edit-form" style="display: none; padding: 20px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #ddd;">
<h3 style="margin: 0;">Editing Note</h3>
<div style="display: flex; gap: 8px;">
<button onclick="cancelEdit()" class="button" style="background: #757575; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">Cancel</button>
<button onclick="saveEdit()" class="button" style="background: #4CAF50; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">Save Changes</button>
</div>
</div>
<div style="margin-bottom: 15px;">
<label style="display: block; margin-bottom: 8px; font-weight: bold; color: #333;">
Note Content (Markdown supported):
</label>
<textarea id="edit-note-text" style="width: 95%; padding: 12px; border: 1px solid #ddd; border-radius: 4px; font-family: 'Courier New', monospace; font-size: 14px; line-height: 1.5; resize: vertical; min-height: 300px;" placeholder="Write your note here...
Markdown syntax supported:
# Header
**Bold** *italic* `code`
- List item
[Link](url)
> Quote"></textarea>
</div>
<div style="margin-top: 20px; padding: 15px; background: #f5f5f5; border-radius: 4px;">
<h4 style="margin: 0 0 10px 0; color: #333;">Preview:</h4>
<div id="edit-preview" style="padding: 15px; background: white; border: 1px solid #ddd; border-radius: 4px; min-height: 100px; font-size: 14px; line-height: 1.6;"></div>
</div>
</div>
</div>
</div>
</div>
<script>
let currentNoteId = null;
let isEditMode = false;
function viewNote(noteId) {
if (currentNoteId === noteId && !isEditMode) return; // Don't reload if same note and not in edit mode
currentNoteId = noteId;
isEditMode = false;
// Show view mode
document.getElementById('note-content').style.display = 'block';
document.getElementById('note-edit-form').style.display = 'none';
// Show loading state
const contentDiv = document.getElementById('note-content');
contentDiv.innerHTML = `
<div style="text-align: center; padding: 40px;">
<div style="display: inline-block; padding: 10px; background: #f0f0f0; border-radius: 4px;">
Loading note...
</div>
</div>
`;
// Load note via AJAX
fetch(`<?= Config::get('URL') ?>note/getNote/${noteId}`)
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => {
if (data.success) {
const note = data.note;
contentDiv.innerHTML = `
<div style="padding-bottom: 15px; border-bottom: 1px solid #ddd; margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center;">
<div>
<h3 style="margin: 0; color: #333;">Note</h3>
<small style="color: #666;">
Created: ${new Date(note.note_timestamp).toLocaleString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}
</small>
</div>
<div style="display: flex; gap: 8px;">
<button onclick="editNote(${note.note_id})" style="padding: 8px 12px; background: #2196F3; color: white; border: none; border-radius: 4px; font-size: 12px; cursor: pointer;">Edit</button>
<a href="<?= Config::get('URL') ?>note/delete/${note.note_id}" style="padding: 8px 12px; background: #f44336; color: white; text-decoration: none; border-radius: 4px; font-size: 12px;" onclick="return confirm('Are you sure you want to delete this note?');">Delete</a>
</div>
</div>
<div style="white-space: pre-wrap; word-wrap: break-word; line-height: 1.6; font-size: 14px; color: #333;">
${note.note_html}
</div>
${note.note_text.length > 100 ? `
<div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #eee; font-size: 12px; color: #666;">
<i class="fa fa-file-text-o"></i> ${note.note_text.length} characters
</div>
` : ''}
`;
// Highlight the active note in the sidebar
document.querySelectorAll('.notes-sidebar .note-card').forEach(card => {
card.style.backgroundColor = card.dataset.noteId == noteId ? '#e8f4fd' : 'white';
card.style.borderColor = card.dataset.noteId == noteId ? '#2196F3' : '#ddd';
});
} else {
contentDiv.innerHTML = `
<div style="text-align: center; padding: 40px; color: #f44336;">
<div style="font-size: 48px; margin-bottom: 10px;">⚠️</div>
<h4>Error loading note</h4>
<p>${data.message || 'Note not found'}</p>
</div>
`;
}
})
.catch(error => {
console.error('Error loading note:', error);
contentDiv.innerHTML = `
<div style="text-align: center; padding: 40px; color: #f44336;">
<div style="font-size: 48px; margin-bottom: 10px;">❌</div>
<h4>Network Error</h4>
<p>Could not load note. Please try again.</p>
</div>
`;
});
}
function editNote(noteId) {
isEditMode = true;
// Hide view mode, show edit form
document.getElementById('note-content').style.display = 'none';
document.getElementById('note-edit-form').style.display = 'block';
// Load the note content
fetch(`<?= Config::get('URL') ?>note/getNote/${noteId}`)
.then(response => response.json())
.then(data => {
if (data.success) {
const note = data.note;
const textarea = document.getElementById('edit-note-text');
const preview = document.getElementById('edit-preview');
textarea.value = note.note_text;
preview.innerHTML = note.note_html;
// Setup live preview
textarea.oninput = function() {
preview.innerHTML = SimpleMarkdown.parse(this.value);
};
}
})
.catch(error => {
console.error('Error loading note for editing:', error);
alert('Error loading note for editing');
});
}
function cancelEdit() {
isEditMode = false;
document.getElementById('note-content').style.display = 'block';
document.getElementById('note-edit-form').style.display = 'none';
viewNote(currentNoteId);
}
function saveEdit() {
const textarea = document.getElementById('edit-note-text');
const noteText = textarea.value;
if (!noteText.trim()) {
alert('Note content cannot be empty');
return;
}
const saveButton = document.querySelector('button[onclick="saveEdit()"]');
const originalText = saveButton.textContent;
saveButton.textContent = 'Saving...';
saveButton.disabled = true;
fetch(`<?= Config::get('URL') ?>note/editSave`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
note_id: currentNoteId,
note_text: noteText
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
showFeedback('Note saved successfully!', 'success');
isEditMode = false;
document.getElementById('note-content').style.display = 'block';
document.getElementById('note-edit-form').style.display = 'none';
viewNote(currentNoteId); // Reload the note view
// Refresh the notes list to show the updated preview
setTimeout(() => {
refreshNotesList();
}, 500);
} else {
showFeedback(data.message || 'Failed to save note', 'error');
}
})
.catch(error => {
console.error('Error saving note:', error);
showFeedback('Network error. Please try again.', 'error');
})
.finally(() => {
saveButton.textContent = originalText;
saveButton.disabled = false;
});
}
// Simple markdown parser for browser use
class SimpleMarkdown {
static parse(text) {
text = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// Headers
text = text.replace(/^#{1,6}\s+(.+)$/gm, '<h3>$1</h3>');
// Bold
text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
// Italic
text = text.replace(/\*(.+?)\*/g, '<em>$1</em>');
// Code
text = text.replace(/`(.+?)`/g, '<code>$1</code>');
// Code blocks
text = text.replace(/```(.+?)```/gs, '<pre><code>$1</code></pre>');
// Links
text = text.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2" target="_blank">$1</a>');
// Blockquotes
text = text.replace(/^>\s+(.+)$/gm, '<blockquote>$1</blockquote>');
// Lists
text = text.replace(/^\-\s+(.+)$/gm, '<li>$1</li>');
text = text.replace(/(<li>.*<\/li>)/gs, '<ul>$1</ul>');
// Line breaks
text = text.replace(/\n/g, '<br>');
return text;
}
}
// Add note IDs to sidebar cards for highlighting
document.addEventListener('DOMContentLoaded', function() {
// Handle note creation form submission
const createForm = document.getElementById('create-note-form');
if (createForm) {
createForm.addEventListener('submit', function(e) {
e.preventDefault();
const noteText = this.note_text.value;
const submitButton = this.querySelector('button[type="submit"]');
const originalText = submitButton.textContent;
if (!noteText.trim()) {
alert('Please enter a note');
return;
}
// Show loading state
submitButton.textContent = 'Creating...';
submitButton.disabled = true;
fetch(`<?= Config::get('URL') ?>note/create`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
},
body: new URLSearchParams({ note_text: noteText })
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Clear form
this.reset();
// Show success message
showFeedback('Note created successfully!', 'success');
// Refresh notes list after a short delay
setTimeout(() => {
refreshNotesList();
}, 500);
} else {
showFeedback(data.message || 'Failed to create note', 'error');
}
})
.catch(error => {
console.error('Error creating note:', error);
showFeedback('Network error. Please try again.', 'error');
})
.finally(() => {
// Restore button state
submitButton.textContent = originalText;
submitButton.disabled = false;
});
});
}
// Add note IDs to sidebar cards for highlighting
const noteCards = document.querySelectorAll('.notes-sidebar > div:nth-child(2) > div');
noteCards.forEach((card, index) => {
// Skip the "Your Notes" header and the form
if (card.querySelector('a[href*="note/edit"]')) {
const editLink = card.querySelector('a[href*="note/edit"]');
const noteId = editLink.href.split('/').pop();
card.classList.add('note-card');
card.dataset.noteId = noteId;
card.style.cursor = 'pointer';
}
});
});
function refreshNotesList() {
// Reload the page to refresh the notes list
// This is simpler than trying to rebuild the sidebar via AJAX
window.location.reload();
}
function showFeedback(message, type) {
// Create feedback element
const feedback = document.createElement('div');
feedback.className = `feedback-${type}`;
feedback.textContent = message;
feedback.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 15px 20px;
background: ${type === 'success' ? '#4caf50' : '#f44336'};
color: white;
border-radius: 4px;
z-index: 1000;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
animation: slideIn 0.3s ease;
`;
document.body.appendChild(feedback);
// Remove after 3 seconds
setTimeout(() => {
feedback.style.animation = 'slideOut 0.3s ease';
setTimeout(() => feedback.remove(), 300);
}, 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; }
}
.feedback-success {
background: linear-gradient(135deg, #4caf50, #45a049) !important;
}
.feedback-error {
background: linear-gradient(135deg, #f44336, #d32f2f) !important;
}
`;
document.head.appendChild(animationStyle);
// Add some CSS for better styling
const style = document.createElement('style');
style.textContent = `
.note-card {
transition: all 0.2s ease;
position: relative;
}
.note-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.note-card:active {
transform: translateY(0);
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.note-main-content {
min-height: 500px;
}
@media (max-width: 768px) {
.note-main-content {
margin-top: 20px;
}
}
`;
document.head.appendChild(style);
</script>