<?php
/**
 * Enhanced Notifications Page with Real-time Updates
 * OBGYN Research & Collaboration Platform
 */

require_once '../config/config.php';

requireLogin();
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Notifications';
$userId = getCurrentUserId();

include '../templates/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">
                    <i class="fas fa-bell"></i> Notifications
                    <span id="unread-badge" class="badge bg-danger" style="display: none;">0</span>
                </h1>
                <div class="btn-toolbar">
                    <button id="mark-all-read-btn" class="btn btn-outline-primary me-2" style="display: none;">
                        <i class="fas fa-check-double"></i> Mark All Read
                    </button>
                    <button id="clear-all-btn" class="btn btn-outline-danger" style="display: none;">
                        <i class="fas fa-trash"></i> Clear All
                    </button>
                    <button id="refresh-btn" class="btn btn-outline-secondary ms-2">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                </div>
            </div>

            <!-- Success/Error Messages -->
            <div id="alert-container"></div>

            <!-- Filter Tabs -->
            <ul class="nav nav-pills mb-4">
                <li class="nav-item">
                    <a class="nav-link active" href="#" data-filter="all" id="filter-all">
                        All (<span id="total-count">0</span>)
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" data-filter="unread" id="filter-unread">
                        Unread (<span id="unread-count">0</span>)
                    </a>
                </li>
            </ul>

            <!-- Notifications List -->
            <div class="card shadow">
                <div class="card-body p-0">
                    <div id="notifications-container">
                        <div class="text-center py-5">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-3">Loading notifications...</p>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
// Notification Manager
const NotificationManager = {
    currentFilter: 'all',
    notifications: [],
    autoRefreshInterval: null,
    
    init() {
        this.loadNotifications();
        this.setupEventListeners();
        this.startAutoRefresh();
    },
    
    setupEventListeners() {
        // Filter tabs
        document.querySelectorAll('[data-filter]').forEach(tab => {
            tab.addEventListener('click', (e) => {
                e.preventDefault();
                this.setFilter(tab.dataset.filter);
            });
        });
        
        // Action buttons
        document.getElementById('mark-all-read-btn').addEventListener('click', () => {
            this.markAllAsRead();
        });
        
        document.getElementById('clear-all-btn').addEventListener('click', () => {
            if (confirm('Are you sure you want to clear all notifications?')) {
                this.clearAll();
            }
        });
        
        document.getElementById('refresh-btn').addEventListener('click', () => {
            this.loadNotifications();
        });
    },
    
    setFilter(filter) {
        this.currentFilter = filter;
        
        // Update active tab
        document.querySelectorAll('[data-filter]').forEach(tab => {
            tab.classList.remove('active');
        });
        document.getElementById(`filter-${filter}`).classList.add('active');
        
        this.renderNotifications();
    },
    
    async loadNotifications() {
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/notifications.php?limit=100');
            const data = await response.json();
            
            if (data.success) {
                this.notifications = data.notifications || [];
                this.updateCounts();
                this.renderNotifications();
            } else {
                this.showAlert('Error loading notifications', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to load notifications', 'danger');
        }
    },
    
    updateCounts() {
        const total = this.notifications.length;
        const unread = this.notifications.filter(n => !n.is_read).length;
        
        document.getElementById('total-count').textContent = total;
        document.getElementById('unread-count').textContent = unread;
        
        const unreadBadge = document.getElementById('unread-badge');
        if (unread > 0) {
            unreadBadge.textContent = unread;
            unreadBadge.style.display = 'inline-block';
            document.getElementById('mark-all-read-btn').style.display = 'inline-block';
        } else {
            unreadBadge.style.display = 'none';
            document.getElementById('mark-all-read-btn').style.display = 'none';
        }
        
        if (total > 0) {
            document.getElementById('clear-all-btn').style.display = 'inline-block';
        } else {
            document.getElementById('clear-all-btn').style.display = 'none';
        }
    },
    
    renderNotifications() {
        const container = document.getElementById('notifications-container');
        
        let filtered = this.notifications;
        if (this.currentFilter === 'unread') {
            filtered = this.notifications.filter(n => !n.is_read);
        }
        
        if (filtered.length === 0) {
            container.innerHTML = `
                <div class="text-center py-5">
                    <i class="fas fa-bell-slash fa-4x text-muted mb-3"></i>
                    <h5>No Notifications</h5>
                    <p class="text-muted">You're all caught up!</p>
                </div>
            `;
            return;
        }
        
        const html = `
            <div class="list-group list-group-flush">
                ${filtered.map(notif => this.renderNotification(notif)).join('')}
            </div>
        `;
        
        container.innerHTML = html;
        
        // Attach event listeners
        this.attachNotificationListeners();
    },
    
    renderNotification(notif) {
        const iconMap = {
            'collaboration_invite': { icon: 'fa-users', color: 'text-info' },
            'study_update': { icon: 'fa-flask', color: 'text-success' },
            'message': { icon: 'fa-envelope', color: 'text-warning' },
            'connection_request': { icon: 'fa-user-plus', color: 'text-primary' },
            'default': { icon: 'fa-bell', color: 'text-primary' }
        };
        
        const iconInfo = iconMap[notif.type] || iconMap.default;
        const bgClass = !notif.is_read ? 'bg-light' : '';
        
        return `
            <div class="list-group-item ${bgClass}" data-notif-id="${notif.id}">
                <div class="d-flex w-100 justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <div class="d-flex align-items-center mb-2">
                            <i class="fas ${iconInfo.icon} ${iconInfo.color} me-2"></i>
                            <h6 class="mb-0">
                                ${this.escapeHtml(notif.title)}
                                ${!notif.is_read ? '<span class="badge bg-primary ms-2">New</span>' : ''}
                            </h6>
                        </div>
                        <p class="mb-1">${this.escapeHtml(notif.message)}</p>
                        <small class="text-muted">
                            <i class="fas fa-clock"></i> ${this.timeAgo(notif.created_at)}
                        </small>
                    </div>
                    <div class="btn-group ms-3">
                        ${notif.link ? `
                            <a href="${this.escapeHtml(notif.link)}" class="btn btn-sm btn-outline-primary">
                                <i class="fas fa-eye"></i> View
                            </a>
                        ` : ''}
                        ${!notif.is_read ? `
                            <button class="btn btn-sm btn-outline-success mark-read-btn" data-id="${notif.id}" title="Mark as read">
                                <i class="fas fa-check"></i>
                            </button>
                        ` : ''}
                        <button class="btn btn-sm btn-outline-danger delete-btn" data-id="${notif.id}" title="Delete">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
    },
    
    attachNotificationListeners() {
        // Mark as read buttons
        document.querySelectorAll('.mark-read-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                this.markAsRead(parseInt(btn.dataset.id));
            });
        });
        
        // Delete buttons
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                this.deleteNotification(parseInt(btn.dataset.id));
            });
        });
    },
    
    async markAsRead(notifId) {
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/notifications.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'mark_read', notification_id: notifId })
            });
            
            const data = await response.json();
            
            if (data.success) {
                // Update local data
                const notif = this.notifications.find(n => n.id === notifId);
                if (notif) notif.is_read = true;
                
                this.updateCounts();
                this.renderNotifications();
                this.showAlert('Notification marked as read', 'success');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to mark notification as read', 'danger');
        }
    },
    
    async markAllAsRead() {
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/notifications.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'mark_all_read' })
            });
            
            const data = await response.json();
            
            if (data.success) {
                // Update local data
                this.notifications.forEach(n => n.is_read = true);
                
                this.updateCounts();
                this.renderNotifications();
                this.showAlert('All notifications marked as read', 'success');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to mark all as read', 'danger');
        }
    },
    
    async deleteNotification(notifId) {
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/notifications.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'delete', notification_id: notifId })
            });
            
            const data = await response.json();
            
            if (data.success) {
                // Remove from local data
                this.notifications = this.notifications.filter(n => n.id !== notifId);
                
                this.updateCounts();
                this.renderNotifications();
                this.showAlert('Notification deleted', 'success');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to delete notification', 'danger');
        }
    },
    
    async clearAll() {
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/api/notifications.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'clear_all' })
            });
            
            const data = await response.json();
            
            if (data.success) {
                this.notifications = [];
                this.updateCounts();
                this.renderNotifications();
                this.showAlert('All notifications cleared', 'success');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to clear notifications', 'danger');
        }
    },
    
    startAutoRefresh() {
        // Refresh every 30 seconds
        this.autoRefreshInterval = setInterval(() => {
            this.loadNotifications();
        }, 30000);
    },
    
    showAlert(message, type = 'info') {
        const container = document.getElementById('alert-container');
        const alert = document.createElement('div');
        alert.className = `alert alert-${type} alert-dismissible fade show`;
        alert.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        container.appendChild(alert);
        
        // Auto-dismiss after 3 seconds
        setTimeout(() => {
            alert.remove();
        }, 3000);
    },
    
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    },
    
    timeAgo(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const seconds = Math.floor((now - date) / 1000);
        
        const intervals = {
            year: 31536000,
            month: 2592000,
            week: 604800,
            day: 86400,
            hour: 3600,
            minute: 60
        };
        
        for (const [unit, secondsInUnit] of Object.entries(intervals)) {
            const interval = Math.floor(seconds / secondsInUnit);
            if (interval >= 1) {
                return interval === 1 ? `1 ${unit} ago` : `${interval} ${unit}s ago`;
            }
        }
        
        return 'Just now';
    }
};

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    NotificationManager.init();
});

// Cleanup on page unload
window.addEventListener('beforeunload', () => {
    if (NotificationManager.autoRefreshInterval) {
        clearInterval(NotificationManager.autoRefreshInterval);
    }
});
</script>

<style>
.list-group-item {
    transition: background-color 0.3s ease;
}

.list-group-item:hover {
    background-color: #f8f9fa !important;
}

#refresh-btn .fa-sync-alt {
    transition: transform 0.3s ease;
}

#refresh-btn:active .fa-sync-alt {
    transform: rotate(360deg);
}
</style>

<?php include '../templates/footer.php'; ?>
