<?php include 'header.php'; ?>

<?php include 'template-parts/sub-header-user.php'; ?>

<div class="uk-container">

    <div class="page-header uk-margin-medium-bottom">
        <div class="uk-grid uk-grid-small" uk-grid>

            <div class="uk-width-expand@s">
                <div class="header-left uk-flex uk-flex-middle gap-16">
                    <div class="header-icon">
                        <span uk-icon="icon: bell; ratio: 1.2" class="uk-icon"></span>
                    </div>
                    <div>
                        <h1 class="header-title">My Notifications</h1>
                        <p class="header-subtitle uk-margin-remove">Stay updated with your latest activities</p>
                    </div>
                </div>
            </div>

            <div class="uk-width-auto@s">
                <div id="headerActions" class="header-actions uk-flex uk-flex-middle gap-6">
                    <button class="uk-button uk-button-secondary uk-button-small" onclick="clearAllNotifications()">
                        <span uk-icon="icon: trash; ratio: 0.6"></span> Clear All
                    </button>
                </div>
            </div>

        </div>
    </div>

    <div id="filterTabs" class="filter-tabs uk-margin-medium-bottom">
        <ul class="uk-tab uk-flex-center" uk-tab>
            <li class="uk-active"><a href="#" onclick="filterByTab('all')">All Notifications (8)</a></li>
            <li><a href="#" onclick="filterByTab('unread')">Unread (3)</a></li>
            <li><a href="#" onclick="filterByTab('read')">Read (5)</a></li>
        </ul>
    </div>

    <h2 id="notificationsHeading" class="uk-heading-divider uk-h4 f600 uk-margin-small-bottom">Your Notifications</h2>

    <div id="notificationsList" class="notifications-list">
        </div>

</div><div id="delete-modal" uk-modal>
    <div class="uk-modal-dialog uk-modal-body">
        <h2 class="uk-modal-title">Delete Notification</h2>
        <p>Are you sure you want to delete this notification? This action cannot be undone.</p>
        <p class="uk-text-right">
            <button class="uk-button uk-button-secondary" type="button" onclick="confirmDeleteNotification()">Delete</button>
            <button class="uk-button uk-button-default uk-modal-close" type="button">Cancel</button>
        </p>
    </div>
</div>

<div id="clear-all-modal" uk-modal>
    <div class="uk-modal-dialog uk-modal-body">
        <h2 class="uk-modal-title">Clear All Notifications</h2>
        <p>Are you sure you want to clear all notifications? This will permanently delete all your notifications.</p>
        <p class="uk-text-right">
            <button class="uk-button uk-button-secondary" type="button" onclick="confirmClearAll()">Clear All</button>
            <button class="uk-button uk-button-default uk-modal-close" type="button">Cancel</button>
        </p>
    </div>
</div>

<script>
    // Notifications data
    const notifications = [{
            id: 'NOT-2025-008',
            type: 'session',
            title: 'Session Reminder',
            message: 'Your session "Technical Interview Preparation" with Noor Abdullah starts in 2 hours',
            timestamp: '2025-01-15T12:00:00',
            status: 'unread',
            priority: 'high',
            actionUrl: '/sessions/MS-2025-001',
            actionText: 'View Session'
        },
        {
            id: 'NOT-2025-007',
            type: 'payment',
            title: 'Payment Confirmed',
            message: 'Your payment of 450 SAR for session "Data Science Interview Prep" has been processed successfully',
            timestamp: '2025-01-14T15:30:00',
            status: 'unread',
            priority: 'medium',
            actionUrl: '/payments/PAY-2025-015',
            actionText: 'View Receipt'
        },
        {
            id: 'NOT-2025-006',
            type: 'message',
            title: 'New Message from Trainer',
            message: 'Mohammed Ali sent you preparation materials for your upcoming session',
            timestamp: '2025-01-14T10:15:00',
            status: 'unread',
            priority: 'medium',
            actionUrl: '/messages/MSG-2025-032',
            actionText: 'Read Message'
        },
        {
            id: 'NOT-2025-005',
            type: 'session',
            title: 'Session Completed',
            message: 'Your session "Management Interview Coaching" has been completed. Please rate your experience',
            timestamp: '2025-01-08T16:00:00',
            status: 'read',
            priority: 'low',
            actionUrl: '/sessions/MS-2024-097',
            actionText: 'Rate Session'
        },
        {
            id: 'NOT-2025-004',
            type: 'system',
            title: 'Profile Updated',
            message: 'Your profile information has been successfully updated',
            timestamp: '2025-01-07T14:20:00',
            status: 'read',
            priority: 'low'
        },
        {
            id: 'NOT-2025-003',
            type: 'cancelled',
            title: 'Session Cancelled',
            message: 'Your session "Sales Interview Preparation" has been cancelled. Refund of 200 SAR will be processed within 3-5 business days',
            timestamp: '2025-01-05T09:45:00',
            status: 'read',
            priority: 'high',
            actionUrl: '/refunds/REF-2025-008',
            actionText: 'Track Refund'
        },
        {
            id: 'NOT-2025-002',
            type: 'payment',
            title: 'Payment Failed',
            message: 'Your payment for session booking failed. Please try again with a different payment method',
            timestamp: '2025-01-04T11:30:00',
            status: 'read',
            priority: 'high',
            actionUrl: '/payments/retry',
            actionText: 'Retry Payment'
        },
        {
            id: 'NOT-2025-001',
            type: 'system',
            title: 'Welcome to the Platform',
            message: 'Welcome! Your account has been created successfully. Complete your profile to get started',
            timestamp: '2025-01-01T08:00:00',
            status: 'read',
            priority: 'medium',
            actionUrl: '/profile/complete',
            actionText: 'Complete Profile'
        }
    ];

    let filteredNotifications = [...notifications];
    let currentTab = 'all';
    let currentNotificationToDelete = null;

    // Get notifications count by status
    function getNotificationCounts() {
        const counts = {
            all: notifications.length,
            unread: notifications.filter(n => n.status === 'unread').length,
            read: notifications.filter(n => n.status === 'read').length
        };
        return counts;
    }

    // Update header actions visibility based on notification count
    function updateHeaderActions() {
        const headerActions = document.getElementById('headerActions');
        const filterTabs = document.getElementById('filterTabs');
        const notificationsHeading = document.getElementById('notificationsHeading');

        if (notifications.length === 0) {
            // Hide header actions, tabs, and heading when no notifications
            headerActions.style.display = 'none';
            filterTabs.style.display = 'none';
            notificationsHeading.style.display = 'none';
        } else {
            // Show header actions, tabs, and heading when notifications exist
            headerActions.style.display = 'flex';
            filterTabs.style.display = 'block';
            notificationsHeading.style.display = 'block';
        }
    }

    // Update tab labels with counts
    function updateTabCounts() {
        const counts = getNotificationCounts();
        const tabs = document.querySelectorAll('.uk-tab li a');
        if (tabs.length >= 3) {
            tabs[0].textContent = `All Notifications (${counts.all})`;
            tabs[1].textContent = `Unread (${counts.unread})`;
            tabs[2].textContent = `Read (${counts.read})`;
        }
    }

    // Format timestamp
    function formatTimestamp(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diffMs = now - date;
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
        const diffMinutes = Math.floor(diffMs / (1000 * 60));

        if (diffMinutes < 60) {
            return `${diffMinutes} minutes ago`;
        } else if (diffHours < 24) {
            return `${diffHours} hours ago`;
        } else if (diffDays < 7) {
            return `${diffDays} days ago`;
        } else {
            return date.toLocaleDateString('en-US', {
                month: 'short',
                day: 'numeric',
                year: 'numeric'
            });
        }
    }

    // Get notification icon based on type
    function getNotificationIcon(type) {
        const icons = {
            cancelled: 'cancelled',
            session: 'calendar',
            payment: 'credit-card',
            message: 'mail',
            system: 'settings'
        };
        return icons[type] || 'bell';
    }

    // Get priority class
    function getPriorityClass(priority) {
        const classes = {
            high: 'priority-high',
            medium: 'priority-medium',
            low: 'priority-low'
        };
        return classes[priority] || '';
    }

    // Mark notification as read
    function markAsRead(notificationId) {
        const notificationIndex = notifications.findIndex(n => n.id === notificationId);
        if (notificationIndex !== -1 && notifications[notificationIndex].status === 'unread') {
            notifications[notificationIndex].status = 'read';
            updateTabCounts();
            updateHeaderActions();
            renderNotifications();

            UIkit.notification({
                message: 'Notification marked as read',
                status: 'success',
                pos: 'top-center',
                timeout: 2000
            });
        }
    }

    // Mark notification as unread
    function markAsUnread(notificationId) {
        const notificationIndex = notifications.findIndex(n => n.id === notificationId);
        if (notificationIndex !== -1 && notifications[notificationIndex].status === 'read') {
            notifications[notificationIndex].status = 'unread';
            updateTabCounts();
            updateHeaderActions();
            renderNotifications();

            UIkit.notification({
                message: 'Notification marked as unread',
                status: 'success',
                pos: 'top-center',
                timeout: 2000
            });
        }
    }

    // Delete notification
    function deleteNotification(notificationId) {
        currentNotificationToDelete = notificationId;
        UIkit.modal('#delete-modal').show();
    }

    // Confirm delete notification
    function confirmDeleteNotification() {
        if (currentNotificationToDelete) {
            const notificationIndex = notifications.findIndex(n => n.id === currentNotificationToDelete);
            if (notificationIndex !== -1) {
                notifications.splice(notificationIndex, 1);

                // Update filtered notifications
                filteredNotifications = filteredNotifications.filter(n => n.id !== currentNotificationToDelete);

                updateTabCounts();
                updateHeaderActions();
                renderNotifications();

                UIkit.notification({
                    message: 'Notification deleted successfully',
                    status: 'success',
                    pos: 'top-center',
                    timeout: 3000
                });
            }

            UIkit.modal('#delete-modal').hide();
            currentNotificationToDelete = null;
        }
    }

    // Clear all notifications
    function clearAllNotifications() {
        if (notifications.length === 0) {
            UIkit.notification({
                message: 'No notifications to clear',
                status: 'warning',
                pos: 'top-center',
                timeout: 2000
            });
            return;
        }
        UIkit.modal('#clear-all-modal').show();
    }

    // Confirm clear all notifications
    function confirmClearAll() {
        notifications.length = 0;
        filteredNotifications.length = 0;

        updateTabCounts();
        updateHeaderActions();
        renderNotifications();

        UIkit.modal('#clear-all-modal').hide();

        UIkit.notification({
            message: 'All notifications cleared',
            status: 'success',
            pos: 'top-center',
            timeout: 3000
        });
    }

    // Render notifications
    function renderNotifications(notificationsToRender = filteredNotifications) {
        const container = document.getElementById('notificationsList');

        if (notificationsToRender.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">
                        <span uk-icon="icon: bell; ratio: 3" class="uk-icon"></span>
                    </div>
                    <div class="empty-title">No notifications found</div>
                    <div class="empty-description">You're all caught up! Check back later for new updates.</div>
                </div>
            `;
            return;
        }

        container.innerHTML = notificationsToRender.map(notification => {
            const isUnread = notification.status === 'unread';
            const priorityClass = getPriorityClass(notification.priority);
            const icon = getNotificationIcon(notification.type);

            let actionsHTML = `
                <div class="notification-actions actions-btns uk-flex uk-flex-middle gap-8">
                    ${isUnread ? 
                        `<button class="uk-button uk-button-default uk-button-small" onclick="markAsRead('${notification.id}')">
                            <span uk-icon="icon: check; ratio: 0.7"></span> Mark Read
                        </button>` :
                        `<button class="uk-button uk-button-default uk-button-small" onclick="markAsUnread('${notification.id}')">
                            <span uk-icon="icon: refresh; ratio: 0.6"></span> Mark Unread
                        </button>`
                    }
                    ${notification.actionUrl ? 
                        `<button class="uk-button uk-button-secondary uk-button-small" onclick="window.location.href='${notification.actionUrl}'">
                            ${notification.actionText}
                        </button>` : ''
                    }
                    <button class="action-btn delete-btn" onclick="deleteNotification('${notification.id}')" aria-label="Delete notification">
                        <span uk-icon="icon: trash; ratio: 0.7"></span>
                    </button>
                </div>
            `;

            return `
                <div class="notification-item ${isUnread ? 'unread' : 'read'} ${priorityClass}" data-notification-id="${notification.id}">
                    <div class="notification-header uk-flex uk-flex-middle uk-flex-between uk-margin-small-bottom">
                        <div class="notification-meta uk-flex uk-flex-middle gap-12">
                            <div class="notification-icon notification-${icon}">
                                <span uk-icon="icon: ${icon}; ratio: .8" class="uk-icon"></span>
                            </div>
                            <div class="notification-info">
                                <span class="notification-type">${notification.type}</span>
                                <span class="notification-time">${formatTimestamp(notification.timestamp)}</span>
                            </div>
                        </div>
                        <div class="notification-status">
                            ${isUnread ? '<span class="status-badge unread">New</span>' : ''}
                        </div>
                    </div>

                    <div class="notification-content uk-margin-small-bottom">
                        <div class="uk-text-secondary notification-title uk-margin-remove">${notification.title}</div>
                        <p class="notification-message uk-margin-remove uk-margin-small-top">${notification.message}</p>
                    </div>

                    ${actionsHTML}
                </div>
            `;
        }).join('');
    }

    // Filter by tab
    function filterByTab(tab) {
        currentTab = tab;

        // Update active tab
        document.querySelectorAll('.uk-tab li').forEach(li => li.classList.remove('uk-active'));
        event.target.parentElement.classList.add('uk-active');

        // Filter notifications
        if (tab === 'all') {
            filteredNotifications = [...notifications];
        } else {
            filteredNotifications = notifications.filter(notification => notification.status === tab);
        }

        renderNotifications(filteredNotifications);
    }

    // Apply filters
    function applyFilters() {
        const typeFilter = document.getElementById('typeFilter').value;
        const statusFilter = document.getElementById('statusFilter').value;
        const dateRange = document.getElementById('dateRange').value;

        filteredNotifications = notifications.filter(notification => {
            // Type filter
            if (typeFilter && notification.type !== typeFilter) {
                return false;
            }

            // Status filter
            if (statusFilter && notification.status !== statusFilter) {
                return false;
            }

            // Date filter
            if (dateRange) {
                const notificationDate = new Date(notification.timestamp);
                const filterDate = new Date(dateRange);
                if (notificationDate.toDateString() !== filterDate.toDateString()) {
                    return false;
                }
            }

            return true;
        });

        renderNotifications(filteredNotifications);

        UIkit.notification({
            message: `Found ${filteredNotifications.length} notifications`,
            status: 'primary',
            pos: 'top-center',
            timeout: 2000
        });
    }

    // Initialize page
    document.addEventListener('DOMContentLoaded', function() {
        // Update tab counts
        updateTabCounts();

        // Update header actions visibility
        updateHeaderActions();

        // Render initial notifications
        renderNotifications();
    });
</script>

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