document.addEventListener('DOMContentLoaded', (event) => { const socket = io(); function checkFriendRequests() { const friendRequestsList = document.getElementById('friend-requests'); const friendRequestsSection = document.getElementById('friend-requests-section'); if (friendRequestsList && friendRequestsSection) { if (friendRequestsList.children.length === 0) { friendRequestsSection.style.display = 'none'; } else { friendRequestsSection.style.display = 'flex'; } } } checkFriendRequests(); const acceptButtons = document.querySelectorAll('.accept-friend-request'); const rejectButtons = document.querySelectorAll('.reject-friend-request'); acceptButtons.forEach(button => { button.addEventListener('click', function() { const requestId = this.dataset.requestId; fetch(`/accept_friend/${requestId}`, { method: 'POST' }) .then(response => response.json()) .then(data => { if (data.status === 'Friend request accepted') { this.closest('.friend-request').remove(); checkFriendRequests(); } }); }); }); rejectButtons.forEach(button => { button.addEventListener('click', function() { const requestId = this.dataset.requestId; fetch(`/reject_friend/${requestId}`, { method: 'POST' }) .then(response => response.json()) .then(data => { if (data.status === 'Friend request rejected') { this.closest('.friend-request').remove(); checkFriendRequests(); } }); }); }); const addFriendForm = document.getElementById('add-friend-form'); if (addFriendForm) { addFriendForm.addEventListener('submit', function(event) { event.preventDefault(); const formData = new FormData(addFriendForm); fetch('/add_friend', { method: 'POST', body: formData }).then(response => response.json()) .then(data => { const addFriendMessage = document.getElementById('add-friend-message'); if (data.status === 'Friend request sent') { addFriendMessage.textContent = 'Friend request sent'; addFriendMessage.style.color = 'green'; } else { addFriendMessage.textContent = 'Failed to send friend request'; addFriendMessage.style.color = 'red'; } }); }); } const createGroupForm = document.getElementById('create-group-form'); if (createGroupForm) { createGroupForm.addEventListener('submit', function(event) { event.preventDefault(); const formData = new FormData(createGroupForm); const members = formData.get('members').split(',').map(member => member.trim()); formData.set('members', members.join(',')); fetch('/create_group', { method: 'POST', body: formData }).then(response => response.json()) .then(data => { const createGroupMessage = document.getElementById('create-group-message'); if (data.status === 'Group created') { createGroupMessage.textContent = 'Group created successfully'; createGroupMessage.style.color = 'green'; setTimeout(() => location.reload(), 1000); } else { createGroupMessage.textContent = 'Failed to create group: ' + data.message; createGroupMessage.style.color = 'red'; } }); }); } });