/**
 * Notification Security Fix
 * Adds HTML escaping to prevent XSS attacks in notifications
 */

// HTML escape function to prevent XSS
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Safer notification rendering function
function renderNotifications(notifications, contentElement) {
    if (!notifications || notifications.length === 0) {
        contentElement.innerHTML = '<p class="empty-message">No notifications yet.</p>';
        return;
    }

    let html = '';
    notifications.forEach(notif => {
        // Escape all user-generated content
        const safeMessage = escapeHtml(notif.message);
        const safeTime = escapeHtml(notif.created_at);
        const readClass = notif.is_read ? '' : 'unread';

        html += `
            <div class="notification-item ${readClass}">
                <p>${safeMessage}</p>
                <span class="notif-time">${safeTime}</span>`;

        // Only add activity link if activity_id is a valid number
        if (notif.activity_id && !isNaN(parseInt(notif.activity_id))) {
            const activityId = parseInt(notif.activity_id);
            html += `<a href="take_activity.php?id=${activityId}" class="notif-link">View Activity →</a>`;
        }

        html += `</div>`;
    });

    contentElement.innerHTML = html;
}

// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { escapeHtml, renderNotifications };
}
