<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

if (!isset($_SESSION['csr_id'])) {
    header('Location: login.php');
    exit();
}

$title = 'Notifications';
ob_start();
?>

<style>
:root {
    --csr-bg-1: #080240;
    --csr-bg-2: #093349;
    --csr-card-1: #17295e;
    --csr-card-2: #102448;
    --csr-border: rgba(96, 165, 250, 0.24);
    --csr-cyan: #17bdd4;
    --csr-blue: #1d9bf0;
    --csr-text: #f8fafc;
    --csr-muted: #aebbd4;
    --csr-soft: #d7e7ff;
}

body {
    background: linear-gradient(135deg, var(--csr-bg-1) 0%, var(--csr-bg-2) 100%) !important;
    color: var(--csr-text) !important;
}

.container-fluid {
    background: transparent !important;
}

.notifications-page-title {
    color: #ffffff;
    font-weight: 900;
    margin: 0;
}

.notifications-page-title i {
    color: #dff7ff;
}

.btn-mark-all {
    color: #dff7ff !important;
    border: 1px solid rgba(56, 189, 248, 0.42) !important;
    background: rgba(56, 189, 248, 0.10) !important;
    border-radius: 10px !important;
    font-weight: 800 !important;
    padding: 10px 14px !important;
}

.btn-mark-all:hover {
    background: rgba(56, 189, 248, 0.24) !important;
    color: #ffffff !important;
}

.card {
    background: linear-gradient(135deg, var(--csr-card-1) 0%, var(--csr-card-2) 100%) !important;
    border: 1px solid var(--csr-border) !important;
    border-radius: 16px !important;
    color: var(--csr-text) !important;
    box-shadow: 0 10px 24px rgba(0, 0, 0, 0.22) !important;
    overflow: hidden;
}

.card-header {
    background: rgba(56, 189, 248, 0.10) !important;
    border-bottom: 1px solid var(--csr-border) !important;
    color: var(--csr-text) !important;
    padding: 14px 16px !important;
}

.card-header h5 {
    color: #ffffff !important;
    font-weight: 900 !important;
}

.card-body {
    color: #ffffff !important;
}

.card-footer {
    background: rgba(8, 20, 48, 0.42) !important;
    border-top: 1px solid var(--csr-border) !important;
    color: var(--csr-soft) !important;
}

.form-label {
    color: #ffffff !important;
    font-weight: 800;
}

.form-select {
    background-color: rgba(8, 20, 48, 0.72) !important;
    border: 1px solid rgba(96, 165, 250, 0.34) !important;
    color: #ffffff !important;
    border-radius: 10px !important;
    min-height: 44px;
}

.form-select:focus {
    border-color: rgba(56, 189, 248, 0.60) !important;
    box-shadow: 0 0 0 0.18rem rgba(56, 189, 248, 0.18) !important;
}

.form-select option {
    background: #102448;
    color: #ffffff;
}

.notifications-list-wrap {
    padding: 12px;
}

.notification-row {
    display: flex;
    gap: 14px;
    align-items: flex-start;
    background: rgba(8, 20, 48, 0.36);
    border: 1px solid rgba(96, 165, 250, 0.20);
    border-radius: 15px;
    padding: 15px;
    margin-bottom: 12px;
    transition: all 0.25s ease;
}

.notification-row:hover {
    background: rgba(56, 189, 248, 0.10);
    border-color: rgba(56, 189, 248, 0.40);
    transform: translateY(-1px);
}

.notification-row.unread {
    background: linear-gradient(135deg, rgba(29, 155, 240, 0.18), rgba(23, 189, 212, 0.10));
    border-color: rgba(56, 189, 248, 0.42);
}

.notification-icon-box {
    width: 46px;
    height: 46px;
    min-width: 46px;
    border-radius: 13px;
    background: rgba(56, 189, 248, 0.14);
    border: 1px solid rgba(56, 189, 248, 0.28);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #dff7ff;
    font-size: 18px;
}

.notification-icon-box.info,
.notification-icon-box.primary {
    background: rgba(56, 189, 248, 0.14);
    color: #dff7ff;
}

.notification-icon-box.success {
    background: rgba(34, 197, 94, 0.16);
    color: #bbf7d0;
    border-color: rgba(34, 197, 94, 0.30);
}

.notification-icon-box.warning {
    background: rgba(245, 158, 11, 0.16);
    color: #fde68a;
    border-color: rgba(245, 158, 11, 0.30);
}

.notification-icon-box.danger {
    background: rgba(248, 113, 113, 0.16);
    color: #fecaca;
    border-color: rgba(248, 113, 113, 0.30);
}

.notification-main {
    flex: 1;
    min-width: 0;
}

.notification-top {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    justify-content: space-between;
    margin-bottom: 6px;
}

.notification-title {
    color: #ffffff;
    font-weight: 900;
    font-size: 15px;
    margin: 0;
    line-height: 1.25;
}

.notification-message {
    color: var(--csr-soft);
    font-size: 14px;
    margin: 0 0 8px;
    line-height: 1.4;
}

.notification-meta {
    color: var(--csr-muted);
    font-size: 12px;
}

.notification-actions {
    display: flex;
    gap: 6px;
    align-items: center;
    flex-shrink: 0;
}

.status-pill {
    border-radius: 999px !important;
    padding: 5px 10px !important;
    font-size: 11px !important;
    font-weight: 900 !important;
}

.btn-notif-action {
    border-radius: 10px !important;
    border: 1px solid rgba(56, 189, 248, 0.38) !important;
    color: #dff7ff !important;
    background: rgba(56, 189, 248, 0.10) !important;
    font-weight: 800 !important;
}

.btn-notif-action:hover {
    background: rgba(56, 189, 248, 0.24) !important;
    color: #ffffff !important;
}

.loader {
    border: 3px solid rgba(255,255,255,0.12);
    border-radius: 50%;
    border-top: 3px solid var(--csr-cyan);
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 0 auto;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.empty-state {
    text-align: center;
    padding: 48px 20px;
    color: #ffffff;
}

.empty-state i {
    color: #dff7ff;
}

.empty-state p {
    color: var(--csr-muted);
}

.pagination .page-link {
    background: rgba(8, 20, 48, 0.54) !important;
    border-color: rgba(96, 165, 250, 0.24) !important;
    color: #dff7ff !important;
    font-weight: 800;
}

.pagination .page-item.active .page-link {
    background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
    border-color: transparent !important;
    color: #ffffff !important;
}

.modal-content {
    background: linear-gradient(135deg, var(--csr-card-1) 0%, var(--csr-card-2) 100%) !important;
    border: 1px solid rgba(96, 165, 250, 0.30) !important;
    color: #ffffff !important;
    border-radius: 16px !important;
    overflow: hidden;
}

.modal-header {
    background: rgba(56, 189, 248, 0.10) !important;
    border-bottom: 1px solid var(--csr-border) !important;
}

.modal-title {
    color: #ffffff !important;
    font-weight: 900 !important;
}

.modal-body {
    background: linear-gradient(135deg, var(--csr-card-1) 0%, var(--csr-card-2) 100%) !important;
    color: #ffffff !important;
}

.modal-footer {
    background: rgba(8, 20, 48, 0.52) !important;
    border-top: 1px solid var(--csr-border) !important;
}

.btn-close {
    filter: brightness(0) invert(1) !important;
    opacity: 1 !important;
}

.btn-primary {
    background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
    border: none !important;
    font-weight: 800 !important;
}

.btn-secondary {
    background: rgba(148, 163, 184, 0.22) !important;
    border: 1px solid rgba(148, 163, 184, 0.30) !important;
    color: #ffffff !important;
    font-weight: 800 !important;
}

@media (max-width: 768px) {
    .notification-row {
        flex-direction: column;
    }

    .notification-top {
        flex-direction: column;
        gap: 6px;
    }

    .notification-actions {
        width: 100%;
        justify-content: flex-end;
    }

    .card-footer .d-flex {
        flex-direction: column;
        gap: 12px;
        align-items: flex-start !important;
    }
}
</style>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                <h2 class="notifications-page-title">
                    <i class="fas fa-bell me-2"></i>Notifications
                </h2>

                <button class="btn btn-mark-all" onclick="markAllAsRead()">
                    <i class="fas fa-check-double me-2"></i>Mark All as Read
                </button>
            </div>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Filter by Type</label>
                    <select class="form-select" id="filterType">
                        <option value="">All Types</option>
                        <option value="info">Info</option>
                        <option value="success">Success</option>
                        <option value="warning">Warning</option>
                        <option value="danger">Danger</option>
                        <option value="primary">Primary</option>
                    </select>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Filter by Status</label>
                    <select class="form-select" id="filterStatus">
                        <option value="">All</option>
                        <option value="unread">Unread</option>
                        <option value="read">Read</option>
                    </select>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Date Range</label>
                    <select class="form-select" id="filterDate">
                        <option value="">All Time</option>
                        <option value="today">Today</option>
                        <option value="week">This Week</option>
                        <option value="month">This Month</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">All Notifications</h5>
        </div>

        <div class="card-body p-0">
            <div id="notificationsList">
                <div class="text-center py-5">
                    <div class="loader mx-auto"></div>
                    <p class="text-muted mt-3">Loading notifications...</p>
                </div>
            </div>
        </div>

        <div class="card-footer">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    Showing <span id="showingStart">0</span> - <span id="showingEnd">0</span> of <span id="totalRecords">0</span>
                </div>

                <nav>
                    <ul class="pagination mb-0" id="pagination"></ul>
                </nav>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="notificationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="notificationModalTitle"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body" id="notificationModalBody"></div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="notificationModalLink" style="display: none;" onclick="goToLink()">View Details</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
let currentPage = 1;
let currentNotificationId = null;
let currentLink = null;

$(document).ready(function() {
    loadNotifications();
    
    $('#filterType, #filterStatus, #filterDate').on('change', function() {
        currentPage = 1;
        loadNotifications();
    });
});

function loadNotifications() {
    const filters = {
        page: currentPage,
        type: $('#filterType').val(),
        status: $('#filterStatus').val(),
        date_range: $('#filterDate').val()
    };
    
    $('#notificationsList').html(`
        <div class="text-center py-5">
            <div class="loader mx-auto"></div>
            <p class="text-muted mt-3">Loading notifications...</p>
        </div>
    `);
    
    $.ajax({
        url: 'ajax/get_all_notifications.php',
        method: 'POST',
        data: filters,
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                displayNotifications(response.notifications);
                updatePagination(response.pagination);
            } else {
                showError(response.message);
            }
        },
        error: function() {
            showError('Error loading notifications');
        }
    });
}

function displayNotifications(notifications) {
    if(!notifications || notifications.length === 0) {
        $('#notificationsList').html(`
            <div class="empty-state">
                <i class="fas fa-bell-slash fa-3x mb-3"></i>
                <p>No notifications found</p>
            </div>
        `);
        return;
    }
    
    let html = '<div class="notifications-list-wrap">';

    notifications.forEach(function(notification) {
        let icon = getNotificationIcon(notification.type);
        let badgeClass = notification.is_read ? 'bg-secondary' : 'bg-primary';
        let statusText = notification.is_read ? 'Read' : 'Unread';
        let rowClass = notification.is_read ? '' : 'unread';
        let typeClass = notification.type || 'primary';
        
        html += `
            <div class="notification-row ${rowClass}" id="notification-${notification.id}">
                <div class="notification-icon-box ${typeClass}">
                    <i class="${icon}"></i>
                </div>

                <div class="notification-main">
                    <div class="notification-top">
                        <div>
                            <h6 class="notification-title">${escapeHtml(notification.title)}</h6>
                        </div>

                        <span class="badge ${badgeClass} status-pill">${statusText}</span>
                    </div>

                    <p class="notification-message">${escapeHtml(notification.message)}</p>

                    <div class="notification-meta">
                        <i class="fas fa-clock me-1"></i>${formatDate(notification.created_at)}
                        ${notification.created_by_name ? `<span class="ms-2"><i class="fas fa-user me-1"></i>${escapeHtml(notification.created_by_name)}</span>` : ''}
                    </div>
                </div>

                <div class="notification-actions">
                    ${!notification.is_read ? `<button class="btn btn-sm btn-notif-action" onclick="markAsRead(${notification.id})" title="Mark as read"><i class="fas fa-check"></i></button>` : ''}
                    <button class="btn btn-sm btn-notif-action" onclick="viewNotification(${notification.id}, '${escapeJs(notification.title)}', '${escapeJs(notification.message)}', '${escapeJs(notification.link || '')}')" title="View details">
                        <i class="fas fa-eye"></i>
                    </button>
                </div>
            </div>
        `;
    });

    html += '</div>';
    
    $('#notificationsList').html(html);
}

function getNotificationIcon(type) {
    switch(type) {
        case 'info': return 'fas fa-info-circle';
        case 'success': return 'fas fa-check-circle';
        case 'warning': return 'fas fa-exclamation-triangle';
        case 'danger': return 'fas fa-times-circle';
        case 'primary': return 'fas fa-bell';
        default: return 'fas fa-bell';
    }
}

function updatePagination(pagination) {
    if(!pagination) return;
    
    $('#showingStart').text(pagination.start);
    $('#showingEnd').text(pagination.end);
    $('#totalRecords').text(pagination.total);
    
    let paginationHtml = '';
    
    if(pagination.current_page > 1) {
        paginationHtml += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${pagination.current_page - 1})">Previous</a></li>`;
    }
    
    for(let i = pagination.start_page; i <= pagination.end_page; i++) {
        paginationHtml += `<li class="page-item ${i === pagination.current_page ? 'active' : ''}">
            <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
        </li>`;
    }
    
    if(pagination.current_page < pagination.total_pages) {
        paginationHtml += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${pagination.current_page + 1})">Next</a></li>`;
    }
    
    $('#pagination').html(paginationHtml);
}

function changePage(page) {
    currentPage = page;
    loadNotifications();
}

function markAsRead(notificationId) {
    $.ajax({
        url: 'ajax/mark_notification_read.php',
        method: 'POST',
        data: { notification_id: notificationId },
        dataType: 'json',
        success: function(response) {
            if(response.success) {
                $(`#notification-${notificationId}`).removeClass('unread');
                $(`#notification-${notificationId} .status-pill`).removeClass('bg-primary').addClass('bg-secondary').text('Read');
                $(`#notification-${notificationId} .btn-notif-action`).first().remove();
                updateNotificationBadge();
            }
        }
    });
}

function markAllAsRead() {
    if(confirm('Mark all notifications as read?')) {
        $.ajax({
            url: 'ajax/mark_notification_read.php',
            method: 'POST',
            data: { mark_all: true },
            dataType: 'json',
            success: function(response) {
                if(response.success) {
                    loadNotifications();
                    updateNotificationBadge();
                }
            }
        });
    }
}

function viewNotification(id, title, message, link) {
    currentNotificationId = id;
    currentLink = link;
    
    $('#notificationModalTitle').text(title);
    $('#notificationModalBody').html(`<p>${escapeHtml(message)}</p>`);
    
    if(link) {
        $('#notificationModalLink').show();
    } else {
        $('#notificationModalLink').hide();
    }
    
    $('#notificationModal').modal('show');
    
    if(id) {
        markAsRead(id);
    }
}

function goToLink() {
    if(currentLink) {
        window.location.href = currentLink;
    }
}

function showError(message) {
    $('#notificationsList').html(`
        <div class="text-center py-5 text-danger">
            <i class="fas fa-exclamation-triangle fa-3x mb-3"></i>
            <p>${escapeHtml(message)}</p>
            <button class="btn btn-sm btn-primary" onclick="loadNotifications()">Retry</button>
        </div>
    `);
}

function updateNotificationBadge() {
    $.ajax({
        url: 'ajax/get_notifications.php',
        method: 'GET',
        data: { unread_only: true, limit: 1 },
        dataType: 'json',
        success: function(response) {
            if(response.success && response.unread_count > 0) {
                $('#notificationBadge').text(response.unread_count).show();
            } else {
                $('#notificationBadge').hide();
            }
        }
    });
}

function formatDate(dateString) {
    if(!dateString) return 'N/A';

    try {
        let date = new Date(dateString);
        if(isNaN(date.getTime())) return dateString;
        
        let now = new Date();
        let diff = now - date;
        let days = Math.floor(diff / (1000 * 60 * 60 * 24));
        
        if(days === 0) {
            return 'Today at ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        } else if(days === 1) {
            return 'Yesterday at ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        } else if(days < 7) {
            return days + ' days ago';
        } else {
            return date.toLocaleDateString('en-US', { 
                year: 'numeric', 
                month: 'short', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    } catch(e) {
        return dateString;
    }
}

function escapeHtml(text) {
    if(!text) return '';

    return String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

function escapeJs(text) {
    if(!text) return '';

    return String(text)
        .replace(/\\/g, '\\\\')
        .replace(/'/g, "\\'")
        .replace(/"/g, '&quot;')
        .replace(/\n/g, '\\n')
        .replace(/\r/g, '');
}
</script>

<?php
$content = ob_get_clean();
include 'layout.php';
?>