<?php

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['id'])) {
    exit;
}

include($_SERVER['DOCUMENT_ROOT']."/SEAT/config/db.php");

$user_id = (int)$_SESSION['id'];

/* =====================================================
   MARK SINGLE NOTIFICATION AS READ (AJAX)
===================================================== */
if(isset($_GET['mark_single'])){

    header("Content-Type: application/json");

    $id = (int)$_GET['mark_single'];

    $stmt = $conn->prepare("
        UPDATE notifications
        SET is_read = 1
        WHERE id = ? AND user_id = ?
    ");

    $stmt->bind_param("ii", $id, $user_id);
    $stmt->execute();

    echo json_encode(["status"=>"success"]);
    exit;
}

/* =====================================================
   MARK ALL AS READ (AJAX)
===================================================== */
if(isset($_GET['mark_read'])){

    header("Content-Type: application/json");

    $stmt = $conn->prepare("
        UPDATE notifications
        SET is_read = 1
        WHERE user_id = ?
    ");

    $stmt->bind_param("i", $user_id);
    $stmt->execute();

    echo json_encode(["status"=>"success"]);
    exit;
}

/* =====================================================
   GET NOTIFICATIONS
===================================================== */
$notifications = [];
$unread_count  = 0;

$q = $conn->prepare("
SELECT
    id,
    title,
    message,
    type,
    is_read,
    created_at
FROM notifications
WHERE user_id=?
AND created_at >= NOW() - INTERVAL 7 DAY
ORDER BY created_at DESC
");

$q->bind_param("i",$user_id);
$q->execute();

$res = $q->get_result();

while($row = $res->fetch_assoc()){

    if($row['is_read'] == 0){
        $unread_count++;
    }

    $row['time'] = date("d M Y, h:i A", strtotime($row['created_at']));
    $notifications[] = $row;
}

/* =====================================================
   AJAX REFRESH (dropdown)
===================================================== */
if(isset($_GET['ajax'])){

    ob_start();

    if(!empty($notifications)){

        foreach($notifications as $n){
?>
<div class="notifItem <?= $n['is_read'] ? '' : 'unread' ?>"

     onclick="openNotification(<?= $n['id'] ?>)">

    <div class="notifTitle">
        <?= htmlspecialchars($n['title']) ?>
    </div>

    <div class="notifMsg">
        <?= htmlspecialchars($n['message']) ?>
    </div>

    <div class="notifTime">
        <?= $n['time'] ?>
    </div>

</div>
<?php
        }

    }else{
?>
<div class="notifEmpty">
    <i class="fa-regular fa-bell-slash"></i>
    <span>No new message</span>
</div>
<?php
    }

    $html = ob_get_clean();

    header("Content-Type: application/json");

    echo json_encode([
        "unread_count" => $unread_count,
        "html" => $html
    ]);

    exit;
}
?>

<!-- ================= NOTIFICATION UI ================= -->
<div class="notifBox">

    <!-- BELL -->
    <div class="topIconWrap" onclick="toggleNotifDropdown()">

        <i class="fa-regular fa-bell"></i>

        <span class="badgeCount" id="notifBadge"
            <?= $unread_count > 0 ? '' : 'style="display:none"' ?>>
            <?= $unread_count ?>
        </span>

    </div>

    <!-- DROPDOWN -->
    <div class="notifDropdown" id="notifDropdown">

        <div class="notifHead">
            Notifications

            <!-- MARK ALL -->
            <button onclick="markAllRead()" class="markAllBtn">
                Mark all
            </button>
        </div>

        <div id="notifList">

        <?php foreach($notifications as $n): ?>

            <div class="notifItem <?= $n['is_read'] ? '' : 'unread' ?>"
                 onclick="openNotification(<?= $n['id'] ?>)">

                <div class="notifTitle">
                    <?= htmlspecialchars($n['title']) ?>
                </div>

                <div class="notifMsg">
                    <?= htmlspecialchars($n['message']) ?>
                </div>

                <div class="notifTime">
                    <?= $n['time'] ?>
                </div>

            </div>

        <?php endforeach; ?>

        </div>

    </div>

</div>

<!-- ================= SCRIPT ================= -->
<script>

function toggleNotifDropdown(){
    document.getElementById("notifDropdown")
    .classList.toggle("showNotif");
}

/* close outside */
document.addEventListener("click", function(e){

    const wrap = document.querySelector(".notifBox");
    const box  = document.getElementById("notifDropdown");

    if(wrap && box && !wrap.contains(e.target)){
        box.classList.remove("showNotif");
    }

});

/* =====================================================
   SINGLE NOTIFICATION
===================================================== */
function openNotification(id){

    fetch("/SEAT/modules/Notification/notification.php?mark_single=" + id)
    .then(res => res.json())
    .then(res => {

        if(res.status === "success"){

            loadNotificationRealtime();

            if(typeof showToast === "function"){
                showToast("Notification marked as read", "success");
            }

        }

    });

}

/* =====================================================
   MARK ALL AS READ
===================================================== */
function markAllRead(){

    fetch("/SEAT/modules/Notification/notification.php?mark_read=1")
    .then(res => res.json())
    .then(res => {

        if(res.status === "success"){

            loadNotificationRealtime();

            document.getElementById("notifDropdown")
            .classList.remove("showNotif");

            if(typeof showToast === "function"){
                showToast("All notifications marked as read", "success");
            }

        }

    });

}

/* =====================================================
   REALTIME REFRESH
===================================================== */
function loadNotificationRealtime(){

fetch("/SEAT/modules/Notification/notification.php?ajax=1&_=" + Date.now())
.then(res => res.json())
.then(data => {

    const badge = document.getElementById("notifBadge");
    const list  = document.getElementById("notifList");

    if(badge){

        if(parseInt(data.unread_count) > 0){
            badge.style.display = "flex";
            badge.textContent   = data.unread_count;
        }else{
            badge.style.display = "none";
        }

    }

    if(list){
        list.innerHTML = data.html;
    }

});

}

/* START */
loadNotificationRealtime();
setInterval(loadNotificationRealtime, 3000);

</script>