<?php 
session_start(); // Start the session
include 'layouts/dbconn.php';

$current_month = date('m');
$current_year = date('Y');

// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php'); // Redirect to the login page
    exit();
}

// Process mark-as-read if requested
if(isset($_GET['mark_read']) && $_GET['mark_read'] == 'all') {
    // Update system notifications
    $mark_notif_read = "UPDATE notifications SET is_read = 1 WHERE is_read = 0";
    $conn->query($mark_notif_read);
    
    // Update messages
    $mark_msg_read = "UPDATE messages SET is_read = 1 WHERE receiver_id = $user_id AND is_read = 0";
    $conn->query($mark_msg_read);
    
    // Redirect to remove the query string
    header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
    exit();
}

// Query to fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.username, u.user_role, u.full_name, u.email, u.role_id, r.role_name 
                     FROM users u
                     LEFT JOIN user_role r ON u.role_id = r.role_id 
                     WHERE u.user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $role_name = $row_user_details['role_name']; // Get the role name from the join
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
} else {
    // Handle the case if user details are not found
}

// Get notifications count
$notification_query = "SELECT COUNT(*) as notif_count FROM notifications WHERE is_read = 0";
$notification_result = $conn->query($notification_query);
$notification_count = ($notification_result && $notification_result->num_rows > 0) ? 
                     $notification_result->fetch_assoc()['notif_count'] : 0;

// Get recent notifications
$recent_notifications_query = "SELECT n.*, f.file_number, nm.message, nm.icon, nm.type
                             FROM notifications n 
                             LEFT JOIN files f ON n.file_id = f.id
                             LEFT JOIN notif_messages nm ON n.notif_message_id = nm.id
                             ORDER BY n.created_at DESC LIMIT 4";
$recent_notifications = $conn->query($recent_notifications_query);

// Get unread message count
$messages_query = "SELECT COUNT(*) as msg_count FROM messages WHERE receiver_id = $user_id AND is_read = 0";
$messages_result = $conn->query($messages_query);
$message_count = ($messages_result && $messages_result->num_rows > 0) ? 
                $messages_result->fetch_assoc()['msg_count'] : 0;

// Get recent messages
$recent_messages_query = "SELECT m.*, u.full_name, u.username 
                        FROM messages m 
                        JOIN users u ON m.sender_id = u.user_id 
                        WHERE m.receiver_id = $user_id 
                        ORDER BY m.created_at DESC LIMIT 4";
$recent_messages = $conn->query($recent_messages_query);

// Calculate total notifications (messages + system notifications)
$total_notifications = $notification_count + $message_count;
?>

<header id="page-topbar">
    <div class="layout-width">
        <div class="navbar-header">
            <div class="d-flex">
                <!-- LOGO -->
                <div class="navbar-brand-box horizontal-logo">
                    <a href="index.php" class="logo logo-dark">
                        <span class="logo-sm">
                            <img src="assets/images/logo-sm.png" alt="" height="22">
                        </span>
                        <span class="logo-lg">
                            <img src="assets/images/logo-dark.png" alt="" height="17">
                        </span>
                    </a>

                    <a href="index.php" class="logo logo-light">
                        <span class="logo-sm">
                            <img src="assets/images/logo-sm.png" alt="" height="22">
                        </span>
                        <span class="logo-lg">
                            <img src="assets/images/logo-light.png" alt="" height="17">
                        </span>
                    </a>
                </div>

                <button type="button" class="btn btn-sm px-3 fs-16 header-item vertical-menu-btn topnav-hamburger" id="topnav-hamburger-icon">
                    <span class="hamburger-icon">
                        <span></span>
                        <span></span>
                        <span></span>
                    </span>
                </button>

            </div>

            <div class="d-flex align-items-center">

                <div class="ms-1 header-item d-none d-sm-flex">
                    <img src="assets/images/flags/tz.svg" alt="user-image" class="me-2 rounded" height="18">
                    <span class="align-middle">English</span>
                </div>

                <div class="dropdown topbar-head-dropdown ms-1 header-item" id="notificationDropdown">
                    <button type="button" class="btn btn-icon btn-topbar btn-ghost-secondary rounded-circle" id="page-header-notifications-dropdown" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-haspopup="true" aria-expanded="false">
                        <i class='bx bx-bell fs-22'></i>
                        <?php if ($total_notifications > 0): ?>
                        <span class="position-absolute topbar-badge fs-10 translate-middle badge rounded-pill bg-danger"><?php echo $total_notifications; ?><span class="visually-hidden">unread messages</span></span>
                        <?php endif; ?>
                    </button>
                    <div class="dropdown-menu dropdown-menu-lg dropdown-menu-end p-0" aria-labelledby="page-header-notifications-dropdown">

                        <div class="dropdown-head bg-secondary bg-pattern rounded-top">
                            <div class="p-3">
                                <div class="row align-items-center">
                                    <div class="col">
                                        <h6 class="m-0 fs-16 fw-semibold text-white"> Notifications </h6>
                                    </div>
                                    <div class="col-auto dropdown-tabs">
                                        <span class="badge bg-light-subtle text-body fs-13"> <?php echo $total_notifications; ?> New</span>
                                    </div>
                                </div>
                            </div>

                            <div class="px-2 pt-2">
                                <ul class="nav nav-tabs dropdown-tabs nav-tabs-custom" data-dropdown-tabs="true" id="notificationItemsTab" role="tablist">
                                    <li class="nav-item waves-effect waves-light">
                                        <a class="nav-link active" data-bs-toggle="tab" href="#all-noti-tab" role="tab" aria-selected="true">
                                            All (<?php echo $total_notifications; ?>)
                                        </a>
                                    </li>
                                    <li class="nav-item waves-effect waves-light">
                                        <a class="nav-link" data-bs-toggle="tab" href="#messages-tab" role="tab" aria-selected="false">
                                            Messages (<?php echo $message_count; ?>)
                                        </a>
                                    </li>
                                    <li class="nav-item waves-effect waves-light">
                                        <a class="nav-link" data-bs-toggle="tab" href="#alerts-tab" role="tab" aria-selected="false">
                                            Alerts (<?php echo $notification_count; ?>)
                                        </a>
                                    </li>
                                </ul>
                            </div>

                        </div>

                        <div class="tab-content position-relative" id="notificationItemsTabContent">
                            <div class="tab-pane fade show active py-2 ps-2" id="all-noti-tab" role="tabpanel">
                                <div data-simplebar style="max-height: 300px;" class="pe-2">
                                    <?php 
                                    // Show system notifications
                                    if ($recent_notifications && $recent_notifications->num_rows > 0):
                                        while ($notif = $recent_notifications->fetch_assoc()):
                                            $icon_class = !empty($notif['icon']) ? $notif['icon'] : 'bx bx-badge-check';
                                            $bg_class = !empty($notif['type']) ? "bg-{$notif['type']}-subtle text-{$notif['type']}" : 'bg-info-subtle text-info';
                                            $time_ago = time_elapsed_string($notif['created_at']);
                                    ?>
                                    <div class="text-reset notification-item d-block dropdown-item position-relative">
                                        <div class="d-flex">
                                            <div class="avatar-xs me-3 flex-shrink-0">
                                                <span class="avatar-title <?php echo $bg_class; ?> rounded-circle fs-16">
                                                    <i class="<?php echo $icon_class; ?>"></i>
                                                </span>
                                            </div>
                                            <div class="flex-grow-1">
                                                <a href="view_file.php?file_number=<?php echo $notif['file_number']; ?>" class="stretched-link">
                                                    <h6 class="mt-0 mb-2 lh-base">
                                                        <?php echo $notif['notif_message']; ?>
                                                    </h6>
                                                </a>
                                                <p class="mb-0 fs-11 fw-medium text-uppercase text-muted">
                                                    <span><i class="mdi mdi-clock-outline"></i> <?php echo $time_ago; ?></span>
                                                </p>
                                            </div>
                                            <div class="px-2 fs-15">
                                                <div class="form-check notification-check">
                                                    <input class="form-check-input" type="checkbox" value="<?php echo $notif['id']; ?>" id="all-notification-check<?php echo $notif['id']; ?>">
                                                    <label class="form-check-label" for="all-notification-check<?php echo $notif['id']; ?>"></label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php 
                                        endwhile;
                                    endif;
                                    
                                    // Show messages
                                    if ($recent_messages && $recent_messages->num_rows > 0):
                                        while ($msg = $recent_messages->fetch_assoc()):
                                            $time_ago = time_elapsed_string($msg['created_at']);
                                    ?>
                                    <div class="text-reset notification-item d-block dropdown-item position-relative">
                                        <div class="d-flex">
                                            <img src="assets/images/users/avatar-2.jpg" class="me-3 rounded-circle avatar-xs flex-shrink-0" alt="user-pic">
                                            <div class="flex-grow-1">
                                                <a href="chat.php?user=<?php echo $msg['sender_id']; ?>" class="stretched-link">
                                                    <h6 class="mt-0 mb-1 fs-13 fw-semibold"><?php echo $msg['full_name']; ?></h6>
                                                </a>
                                                <div class="fs-13 text-muted">
                                                    <p class="mb-1"><?php echo substr($msg['message'], 0, 50) . (strlen($msg['message']) > 50 ? '...' : ''); ?></p>
                                                </div>
                                                <p class="mb-0 fs-11 fw-medium text-uppercase text-muted">
                                                    <span><i class="mdi mdi-clock-outline"></i> <?php echo $time_ago; ?></span>
                                                </p>
                                            </div>
                                            <div class="px-2 fs-15">
                                                <div class="form-check notification-check">
                                                    <input class="form-check-input" type="checkbox" value="<?php echo $msg['id']; ?>" id="message-notification-check<?php echo $msg['id']; ?>">
                                                    <label class="form-check-label" for="message-notification-check<?php echo $msg['id']; ?>"></label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php
                                        endwhile;
                                    endif;
                                    
                                    if (($recent_notifications && $recent_notifications->num_rows == 0) && 
                                        ($recent_messages && $recent_messages->num_rows == 0)):
                                    ?>
                                    <div class="w-25 w-sm-50 pt-3 mx-auto">
                                        <img src="assets/images/svg/bell.svg" class="img-fluid" alt="user-pic">
                                    </div>
                                    <div class="text-center pb-5 mt-2">
                                        <h6 class="fs-18 fw-semibold lh-base">You have no notifications</h6>
                                    </div>
                                    <?php endif; ?>

                                    <div class="my-3 text-center">
                                        <div class="d-flex justify-content-center gap-2">
                                            <?php if ($total_notifications > 0): ?>
                                            <a href="?mark_read=all" class="btn btn-soft-secondary waves-effect waves-light">
                                                Mark All as Read
                                            </a>
                                            <?php endif; ?>
                                            <a href="notifications.php" class="btn btn-soft-success waves-effect waves-light">
                                                View All <i class="ri-arrow-right-line align-middle"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>

                            </div>

                            <div class="tab-pane fade py-2 ps-2" id="messages-tab" role="tabpanel" aria-labelledby="messages-tab">
                                <div data-simplebar style="max-height: 300px;" class="pe-2">
                                    <?php 
                                    // Show messages
                                    if ($recent_messages && $recent_messages->num_rows > 0):
                                        mysqli_data_seek($recent_messages, 0); // Reset result pointer
                                        while ($msg = $recent_messages->fetch_assoc()):
                                            $time_ago = time_elapsed_string($msg['created_at']);
                                    ?>
                                    <div class="text-reset notification-item d-block dropdown-item">
                                        <div class="d-flex">
                                            <img src="assets/images/users/avatar-3.jpg" class="me-3 rounded-circle avatar-xs" alt="user-pic">
                                            <div class="flex-grow-1">
                                                <a href="chat.php?user=<?php echo $msg['sender_id']; ?>" class="stretched-link">
                                                    <h6 class="mt-0 mb-1 fs-13 fw-semibold"><?php echo $msg['full_name']; ?></h6>
                                                </a>
                                                <div class="fs-13 text-muted">
                                                    <p class="mb-1"><?php echo substr($msg['message'], 0, 50) . (strlen($msg['message']) > 50 ? '...' : ''); ?></p>
                                                </div>
                                                <p class="mb-0 fs-11 fw-medium text-uppercase text-muted">
                                                    <span><i class="mdi mdi-clock-outline"></i> <?php echo $time_ago; ?></span>
                                                </p>
                                            </div>
                                            <div class="px-2 fs-15">
                                                <div class="form-check notification-check">
                                                    <input class="form-check-input" type="checkbox" value="<?php echo $msg['id']; ?>" id="messages-notification-check<?php echo $msg['id']; ?>">
                                                    <label class="form-check-label" for="messages-notification-check<?php echo $msg['id']; ?>"></label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php
                                        endwhile;
                                    else:
                                    ?>
                                    <div class="w-25 w-sm-50 pt-3 mx-auto">
                                        <img src="assets/images/svg/bell.svg" class="img-fluid" alt="user-pic">
                                    </div>
                                    <div class="text-center pb-5 mt-2">
                                        <h6 class="fs-18 fw-semibold lh-base">You have no messages</h6>
                                    </div>
                                    <?php endif; ?>

                                    <div class="my-3 text-center">
                                        <div class="d-flex justify-content-center gap-2">
                                            <?php if ($message_count > 0): ?>
                                            <a href="?mark_read=messages" class="btn btn-soft-secondary waves-effect waves-light">
                                                Mark All as Read
                                            </a>
                                            <?php endif; ?>
                                            <a href="chat.php" class="btn btn-soft-success waves-effect waves-light">
                                                View All Messages <i class="ri-arrow-right-line align-middle"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="tab-pane fade py-2 ps-2" id="alerts-tab" role="tabpanel" aria-labelledby="alerts-tab">
                                <div data-simplebar style="max-height: 300px;" class="pe-2">
                                    <?php 
                                    // Show system notifications only
                                    if ($recent_notifications && $recent_notifications->num_rows > 0):
                                        mysqli_data_seek($recent_notifications, 0); // Reset result pointer
                                        while ($notif = $recent_notifications->fetch_assoc()):
                                            $icon_class = !empty($notif['icon']) ? $notif['icon'] : 'bx bx-badge-check';
                                            $bg_class = !empty($notif['type']) ? "bg-{$notif['type']}-subtle text-{$notif['type']}" : 'bg-info-subtle text-info';
                                            $time_ago = time_elapsed_string($notif['created_at']);
                                    ?>
                                    <div class="text-reset notification-item d-block dropdown-item position-relative">
                                        <div class="d-flex">
                                            <div class="avatar-xs me-3 flex-shrink-0">
                                                <span class="avatar-title <?php echo $bg_class; ?> rounded-circle fs-16">
                                                    <i class="<?php echo $icon_class; ?>"></i>
                                                </span>
                                            </div>
                                            <div class="flex-grow-1">
                                                <a href="view_file.php?file_number=<?php echo $notif['file_number']; ?>" class="stretched-link">
                                                    <h6 class="mt-0 mb-2 lh-base">
                                                        <?php echo $notif['notif_message']; ?>
                                                    </h6>
                                                </a>
                                                <p class="mb-0 fs-11 fw-medium text-uppercase text-muted">
                                                    <span><i class="mdi mdi-clock-outline"></i> <?php echo $time_ago; ?></span>
                                                </p>
                                            </div>
                                            <div class="px-2 fs-15">
                                                <div class="form-check notification-check">
                                                    <input class="form-check-input" type="checkbox" value="<?php echo $notif['id']; ?>" id="alert-notification-check<?php echo $notif['id']; ?>">
                                                    <label class="form-check-label" for="alert-notification-check<?php echo $notif['id']; ?>"></label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php 
                                        endwhile;
                                    else:
                                    ?>
                                    <div class="w-25 w-sm-50 pt-3 mx-auto">
                                        <img src="assets/images/svg/bell.svg" class="img-fluid" alt="user-pic">
                                    </div>
                                    <div class="text-center pb-5 mt-2">
                                        <h6 class="fs-18 fw-semibold lh-base">You have no alerts</h6>
                                    </div>
                                    <?php endif; ?>

                                    <div class="my-3 text-center">
                                        <div class="d-flex justify-content-center gap-2">
                                            <?php if ($notification_count > 0): ?>
                                            <a href="?mark_read=alerts" class="btn btn-soft-secondary waves-effect waves-light">
                                                Mark All as Read
                                            </a>
                                            <?php endif; ?>
                                            <a href="notifications.php" class="btn btn-soft-success waves-effect waves-light">
                                                View All Alerts <i class="ri-arrow-right-line align-middle"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="notification-actions" id="notification-actions">
                                <div class="d-flex text-muted justify-content-center">
                                    Select <div id="select-content" class="text-body fw-semibold px-1">0</div> Result <button type="button" class="btn btn-link link-danger p-0 ms-3" data-bs-toggle="modal" data-bs-target="#removeNotificationModal">Remove</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="dropdown ms-sm-3 header-item topbar-user">
                    <button type="button" class="btn" id="page-header-user-dropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <span class="d-flex align-items-center">
                            <img class="rounded-circle header-profile-user" src="assets/images/users/avatar-1.jpg" alt="Header Avatar">
                            <span class="text-start ms-xl-2">
                                <span class="d-none d-xl-inline-block ms-1 fw-semibold user-name-text"><?php echo $full_name; ?></span>
                                <span class="d-none d-xl-block ms-1 fs-12 user-name-sub-text"><?php echo $role_name ?? $user_role; ?></span>
                            </span>
                        </span>
                    </button>
                    <div class="dropdown-menu dropdown-menu-end">
                        <!-- item-->
                        <h6 class="dropdown-header">Welcome <?php echo $full_name; ?></h6>
                        <a class="dropdown-item" href="user_profile.php"><i class="mdi mdi-account-circle text-muted fs-16 align-middle me-1"></i> <span class="align-middle">Profile</span></a>
                        <a class="dropdown-item" href="logout.php"><i class="mdi mdi-logout text-muted fs-16 align-middle me-1"></i> <span class="align-middle" data-key="t-logout">Logout</span></a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- removeNotificationModal -->
<div id="removeNotificationModal" class="modal fade zoomIn" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="NotificationModalbtn-close"></button>
            </div>
            <div class="modal-body">
                <div class="mt-2 text-center">
                    <lord-icon src="https://cdn.lordicon.com/gsqxdxog.json" trigger="loop" colors="primary:#495057,secondary:#f06548" style="width:100px;height:100px"></lord-icon>
                    <div class="mt-4 pt-2 fs-15 mx-4 mx-sm-5">
                        <h4 class="fw-bold">Are you sure ?</h4>
                        <p class="text-muted mx-4 mb-0">Are you sure you want to remove this Notification ?</p>
                    </div>
                </div>
                <div class="d-flex gap-2 justify-content-center mt-4 mb-2">
                    <button type="button" class="btn w-sm btn-light" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn w-sm btn-danger" id="delete-notification">Yes, Delete It!</button>
                </div>
            </div>

        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<?php
// Helper function to format time elapsed
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

// Add JavaScript to handle individual notification marking
?>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
    // Handle individual notification checks
    const notificationCheckboxes = document.querySelectorAll('.notification-check input');
    notificationCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            updateSelectedCount();
        });
    });

    // Update the selected count display
    function updateSelectedCount() {
        const selectedCount = document.querySelectorAll('.notification-check input:checked').length;
        document.getElementById('select-content').textContent = selectedCount;
        
        // Show/hide the action bar
        const actionDiv = document.getElementById('notification-actions');
        if (selectedCount > 0) {
            actionDiv.style.display = 'block';
        } else {
            actionDiv.style.display = 'none';
        }
    }

    // Handle delete button click
    document.getElementById('delete-notification').addEventListener('click', function() {
        const selectedNotifications = [];
        document.querySelectorAll('.notification-check input:checked').forEach(checkbox => {
            selectedNotifications.push(checkbox.value);
        });

        if (selectedNotifications.length > 0) {
            // Send AJAX request to mark as read/delete
            fetch('mark_notifications.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'delete',
                    notifications: selectedNotifications
                }),
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Refresh the page or update the UI
                    window.location.reload();
                }
            });
        }
    });

    // Initially hide the action bar
    document.getElementById('notification-actions').style.display = 'none';
});
</script>