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

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

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

$pageTitle = 'Notifications';
$isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/', $_SERVER['HTTP_USER_AGENT']);
$userId = getCurrentUserId();

// Include appropriate header based on device
if ($isMobile) {
    include '../templates/researcher-mobile-header.php';
} else {
    include '../templates/researcher-header.php';
}
?>

<div class="container-fluid p-4">
    <div class="row">
        <!-- Main content - full width since sidebar is offcanvas -->
        <main class="col-12">
            <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 class="badge bg-danger" id="unreadBadge" style="display: none;">0</span>
                </h1>
                <div class="btn-toolbar">
                    <button id="markAllReadBtn" class="btn btn-outline-primary me-2" style="display: none;">
                        <i class="fas fa-check-double"></i> Mark All Read
                    </button>
                    <button id="refreshBtn" class="btn btn-outline-secondary">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                </div>
            </div>

            <!-- Alert Container -->
            <div id="alertContainer"></div>

            <!-- Filter Tabs -->
            <ul class="nav nav-pills mb-4" id="notificationTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="all-tab" data-bs-toggle="tab" 
                            data-bs-target="#all" type="button" role="tab" onclick="NotificationManager.loadNotifications('all')">
                        <i class="fas fa-list"></i> All 
                        <span class="badge bg-secondary" id="allCount">0</span>
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="unread-tab" data-bs-toggle="tab" 
                            data-bs-target="#unread" type="button" role="tab" onclick="NotificationManager.loadNotifications('unread')">
                        <i class="fas fa-envelope"></i> Unread 
                        <span class="badge bg-danger" id="unreadCount">0</span>
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="connections-tab" data-bs-toggle="tab" 
                            data-bs-target="#connections" type="button" role="tab" onclick="NotificationManager.loadNotifications('connections')">
                        <i class="fas fa-user-friends"></i> Connections
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="collaborations-tab" data-bs-toggle="tab" 
                            data-bs-target="#collaborations" type="button" role="tab" onclick="NotificationManager.loadNotifications('collaborations')">
                        <i class="fas fa-users"></i> Collaborations
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="messages-tab" data-bs-toggle="tab" 
                            data-bs-target="#messages" type="button" role="tab" onclick="NotificationManager.loadNotifications('messages')">
                        <i class="fas fa-envelope"></i> Messages
                    </button>
                </li>
            </ul>

            <!-- Tab Content -->
            <div class="tab-content" id="notificationTabContent">
                <div class="tab-pane fade show active" id="all" role="tabpanel">
                    <div class="card shadow">
                        <div class="card-body">
                            <div id="notificationsLoading" class="text-center py-5">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2 text-muted">Loading notifications...</p>
                            </div>
                            <div id="notificationsList" style="display: none;"></div>
                            <div id="notificationsEmpty" class="text-center py-5" style="display: none;">
                                <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>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
const API_URL = '<?php echo SITE_URL; ?>/api';
const CURRENT_USER_ID = <?php echo $userId; ?>;

const NotificationManager = {
    notifications: [],
    currentFilter: 'all',
    autoRefreshInterval: null,
    
    init() {
        this.loadNotifications('all');
        this.setupEventListeners();
        this.startAutoRefresh();
    },
    
    setupEventListeners() {
        // Mark all read button
        document.getElementById('markAllReadBtn').addEventListener('click', () => {
            this.markAllAsRead();
        });
        
        // Refresh button
        document.getElementById('refreshBtn').addEventListener('click', () => {
            this.loadNotifications(this.currentFilter);
        });
    },
    
    async loadNotifications(filter = 'all') {
        this.currentFilter = filter;
        
        try {
            document.getElementById('notificationsLoading').style.display = 'block';
            document.getElementById('notificationsList').style.display = 'none';
            document.getElementById('notificationsEmpty').style.display = 'none';
            
            let url = `${API_URL}/notifications.php?limit=50`;
            
            if (filter === 'unread') {
                url += '&unread_only=true';
            }
            
            const response = await fetch(url);
            const data = await response.json();
            
            document.getElementById('notificationsLoading').style.display = 'none';
            
            if (data.success) {
                // Filter by type if needed
                let filteredNotifications = data.notifications;
                
                if (filter === 'connections') {
                    filteredNotifications = data.notifications.filter(n => 
                        n.type.includes('connection')
                    );
                } else if (filter === 'collaborations') {
                    filteredNotifications = data.notifications.filter(n => 
                        n.type.includes('collaboration') || n.type.includes('study')
                    );
                } else if (filter === 'messages') {
                    filteredNotifications = data.notifications.filter(n => 
                        n.type.includes('message')
                    );
                }
                
                this.notifications = filteredNotifications;
                this.renderNotifications();
                this.updateCounts(data.unread_count, data.notifications.length);
            } else {
                this.showAlert('Failed to load notifications', 'danger');
            }
        } catch (error) {
            console.error('Error loading notifications:', error);
            document.getElementById('notificationsLoading').style.display = 'none';
            this.showAlert('Failed to load notifications', 'danger');
        }
    },
    
    renderNotifications() {
        const container = document.getElementById('notificationsList');
        
        if (this.notifications.length === 0) {
            document.getElementById('notificationsEmpty').style.display = 'block';
            return;
        }
        
        container.style.display = 'block';
        
        let html = '<div class="list-group list-group-flush">';
        
        this.notifications.forEach(notif => {
            const iconInfo = this.getNotificationIcon(notif.type);
            const isUnread = !notif.is_read;
            
            html += `
                <div class="list-group-item ${isUnread ? 'bg-light border-start border-primary border-3' : ''}" 
                     data-notification-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">
                                <div class="notification-icon ${iconInfo.color} me-3">
                                    <i class="fas ${iconInfo.icon}"></i>
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-0">
                                        ${this.escapeHtml(notif.title)}
                                        ${isUnread ? '<span class="badge bg-primary ms-2">New</span>' : ''}
                                    </h6>
                                    <small class="text-muted">
                                        <i class="fas fa-clock"></i> ${this.timeAgo(notif.created_at)}
                                    </small>
                                </div>
                            </div>
                            <p class="mb-2">${this.escapeHtml(notif.message)}</p>
                            <div class="btn-group btn-group-sm">
                                ${notif.link ? `
                                    <a href="${notif.link}" class="btn btn-outline-primary">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                ` : ''}
                                ${isUnread ? `
                                    <button onclick="NotificationManager.markAsRead(${notif.id})" 
                                            class="btn btn-outline-success">
                                        <i class="fas fa-check"></i> Mark Read
                                    </button>
                                ` : ''}
                                <button onclick="NotificationManager.deleteNotification(${notif.id})" 
                                        class="btn btn-outline-danger">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        
        html += '</div>';
        container.innerHTML = html;
    },
    
    getNotificationIcon(type) {
        const icons = {
            'connection_request': { icon: 'fa-user-plus', color: 'text-primary' },
            'connection_accepted': { icon: 'fa-user-check', color: 'text-success' },
            'collaboration_invite': { icon: 'fa-users', color: 'text-info' },
            'collaboration_accepted': { icon: 'fa-handshake', color: 'text-success' },
            'study_update': { icon: 'fa-flask', color: 'text-warning' },
            'message': { icon: 'fa-envelope', color: 'text-primary' },
            'default': { icon: 'fa-bell', color: 'text-secondary' }
        };
        
        return icons[type] || icons['default'];
    },
    
    async markAsRead(notificationId) {
        try {
            const response = await fetch(`${API_URL}/notifications.php`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ notification_id: notificationId })
            });
            
            const data = await response.json();
            
            if (data.success) {
                // Update UI
                const notifElement = document.querySelector(`[data-notification-id="${notificationId}"]`);
                if (notifElement) {
                    notifElement.classList.remove('bg-light', 'border-start', 'border-primary', 'border-3');
                    notifElement.querySelector('.badge')?.remove();
                    notifElement.querySelector('.btn-outline-success')?.remove();
                }
                
                // Reload to update counts
                this.loadNotifications(this.currentFilter);
            } else {
                this.showAlert('Failed to mark as read', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to mark as read', 'danger');
        }
    },
    
    async markAllAsRead() {
        if (!confirm('Mark all notifications as read?')) return;
        
        try {
            const response = await fetch(`${API_URL}/notifications.php`, {
                method: 'PUT'
            });
            
            const data = await response.json();
            
            if (data.success) {
                this.showAlert(`${data.count} notifications marked as read`, 'success');
                this.loadNotifications(this.currentFilter);
            } else {
                this.showAlert('Failed to mark all as read', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to mark all as read', 'danger');
        }
    },
    
    async deleteNotification(notificationId) {
        if (!confirm('Delete this notification?')) return;
        
        try {
            const response = await fetch(`${API_URL}/notifications.php`, {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ notification_id: notificationId })
            });
            
            const data = await response.json();
            
            if (data.success) {
                // Remove from UI
                const notifElement = document.querySelector(`[data-notification-id="${notificationId}"]`);
                if (notifElement) {
                    notifElement.style.animation = 'fadeOut 0.3s ease-out';
                    setTimeout(() => {
                        notifElement.remove();
                        if (document.querySelectorAll('[data-notification-id]').length === 0) {
                            document.getElementById('notificationsEmpty').style.display = 'block';
                            document.getElementById('notificationsList').style.display = 'none';
                        }
                    }, 300);
                }
                
                this.loadNotifications(this.currentFilter);
            } else {
                this.showAlert('Failed to delete notification', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to delete notification', 'danger');
        }
    },
    
    updateCounts(unreadCount, totalCount) {
        // Update badges
        document.getElementById('unreadBadge').textContent = unreadCount;
        document.getElementById('unreadBadge').style.display = unreadCount > 0 ? 'inline-block' : 'none';
        
        document.getElementById('allCount').textContent = totalCount;
        document.getElementById('unreadCount').textContent = unreadCount;
        
        // Show/hide mark all read button
        document.getElementById('markAllReadBtn').style.display = unreadCount > 0 ? 'inline-block' : 'none';
    },
    
    startAutoRefresh() {
        // Refresh every 30 seconds
        this.autoRefreshInterval = setInterval(() => {
            this.loadNotifications(this.currentFilter);
        }, 30000);
    },
    
    showAlert(message, type = 'info') {
        const container = document.getElementById('alertContainer');
        const alert = document.createElement('div');
        alert.className = `alert alert-${type} alert-dismissible fade show`;
        alert.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        container.appendChild(alert);
        
        setTimeout(() => alert.remove(), 5000);
    },
    
    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
document.addEventListener('DOMContentLoaded', () => {
    NotificationManager.init();
});

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

<style>
.notification-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    background-color: rgba(0, 123, 255, 0.1);
    flex-shrink: 0;
}

.notification-icon.text-primary {
    background-color: rgba(0, 123, 255, 0.1);
}

.notification-icon.text-success {
    background-color: rgba(40, 167, 69, 0.1);
}

.notification-icon.text-info {
    background-color: rgba(23, 162, 184, 0.1);
}

.notification-icon.text-warning {
    background-color: rgba(255, 193, 7, 0.1);
}

.list-group-item {
    transition: all 0.3s ease;
}

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

@keyframes fadeOut {
    from {
        opacity: 1;
        transform: translateX(0);
    }
    to {
        opacity: 0;
        transform: translateX(100%);
    }
}

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

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

<?php // Include appropriate footer based on device
if ($isMobile) {
    include '../templates/researcher-mobile-footer.php';
} else {
    include '../templates/footer.php';
} ?>
