<?php
require_once __DIR__ . "/../config/db.php";

$baseURL = "/";

$currentPage = basename($_SERVER['PHP_SELF']);

$isDashboard   = ($currentPage === 'dashboard.php');
$isItems       = ($currentPage === 'items.php');
$isMaintenance = ($currentPage === 'maintenance.php');
$isReports     = ($currentPage === 'reports.php');
$isSettings    = ($currentPage === 'settings.php');

if (
    !isset($_SESSION['user_id']) ||
    (isset($_SESSION['role']) && $_SESSION['role'] === 'guest')
) {
    return;
}

$userName = $_SESSION['full_name'] ?? 'User';
$userRole = ucfirst($_SESSION['role'] ?? '-');
$departmentName = '-';

if (!empty($_SESSION['department_id'])) {

    $dept_id = $_SESSION['department_id'];

    $deptQuery = mysqli_prepare($conn,
        "SELECT name FROM departments WHERE id = ?"
    );

    mysqli_stmt_bind_param($deptQuery, "i", $dept_id);
    mysqli_stmt_execute($deptQuery);

    $deptResult = mysqli_stmt_get_result($deptQuery);

    if ($dept = mysqli_fetch_assoc($deptResult)) {
        $departmentName = $dept['name'];
    }
}
?>

<link rel="icon" type="image/png" href="<?= $baseURL ?>assets/logo.png">

<button class="sidebar-toggle" onclick="toggleSidebar()">☰</button>

<div class="sidebar" id="sidebar">

    <div class="logo-container">
        <img src="<?= $baseURL ?>assets/logo.png" class="logo">

        <div class="user-info">
            <div class="user-name"><?= htmlspecialchars($userName) ?></div>
            <div class="user-role"><?= htmlspecialchars($userRole) ?></div>
            <div class="user-department"><?= htmlspecialchars($departmentName) ?></div>
        </div>
    </div>

    <ul class="menu">
        <li><a href="<?= $baseURL ?>dashboard.php" class="<?= $isDashboard ? 'active' : '' ?>">Dashboard</a></li>
        <li><a href="<?= $baseURL ?>items.php" class="<?= $isItems ? 'active' : '' ?>">Items</a></li>
        <li><a href="<?= $baseURL ?>maintenance.php" class="<?= $isMaintenance ? 'active' : '' ?>">Maintenance</a></li>
        <li><a href="<?= $baseURL ?>reports.php" class="<?= $isReports ? 'active' : '' ?>">Reports</a></li>
        <li><a href="<?= $baseURL ?>settings.php" class="<?= $isSettings ? 'active' : '' ?>">Settings</a></li>
    </ul>

    <!-- BOTTOM -->
    <div class="sidebar-bottom">

        <!-- INBOX -->
        <div class="sidebar-inbox" onclick="toggleInbox()">

            <div class="inbox-left">
                <i class="fas fa-inbox"></i>
                <span>Inbox</span>
            </div>

            <span id="notif-badge" class="sidebar-badge" style="display:none;">0</span>

        </div>

        <!-- LOGOUT -->
        <div class="logout">
            <a href="<?= $baseURL ?>auth/logout.php">Logout</a>
        </div>

    </div>

</div>

<!-- INBOX POPUP -->
<div id="inbox-popup" class="inbox-popup">
    <div class="inbox-header">
        <strong>Notifications</strong>
        <span onclick="toggleInbox()" style="cursor:pointer;">✖</span>
    </div>
    <div id="inbox-content" class="inbox-content">Loading...</div>
</div>

<script>

function toggleSidebar(){
    document.getElementById("sidebar").classList.toggle("collapsed");
}

/* =========================
   🔴 BADGE AUTO LOAD (IMPORTANT)
========================= */
function updateBadge(){

    fetch("<?= $baseURL ?>includes/get_inbox.php")
    .then(res => res.json())
    .then(data => {

        let badge = document.getElementById("notif-badge");

        if(!badge) return;

        let count = data.length || 0;

        if(count > 0){
            badge.style.display = "flex";
            badge.innerText = count;
        } else {
            badge.style.display = "none";
        }
    })
    .catch(err => console.log(err));
}

/* run immediately when page loads */
document.addEventListener("DOMContentLoaded", updateBadge);

/* keep updating */
setInterval(updateBadge, 15000);


/* =========================
   INBOX POPUP ONLY
========================= */
function loadInbox(){

    fetch("<?= $baseURL ?>includes/get_inbox.php")
    .then(res => res.json())
    .then(data => {

        let html = "";

        if(data.length === 0){
            html = "<p>No notifications</p>";
        } else {

            data.forEach(item => {

                html += `
                <div class="inbox-item">

                    <strong>${item.equipment_name}</strong><br>

                    <small class="${item.class}">
                        ${item.time_text}<br>
                        Due: ${item.due_date}
                    </small>

                    <br>

                    <a href="${item.link}" class="view-btn">View</a>

                </div>`;
            });
        }

        document.getElementById("inbox-content").innerHTML = html;
    });
}

function toggleInbox(){

    let popup = document.getElementById("inbox-popup");

    if(popup.style.display === "flex"){
        popup.style.display = "none";
    } else {
        popup.style.display = "flex";
        loadInbox();
    }
}

</script>

<style>

/* SIDEBAR */
.sidebar{
    position:fixed;
    left:0;
    top:0;
    width:240px;
    height:100vh;
    background:linear-gradient(180deg,#2bbbad,#1e8f86);
    color:white;
    display:flex;
    flex-direction:column;
    transition:0.3s;
    overflow:hidden;
    box-shadow: 5px 0 20px rgba(0,0,0,0.15);
}

.sidebar.collapsed{ width:80px; }

/* TOGGLE */
.sidebar-toggle{
    position:fixed;
    top:15px;
    left:15px;
    z-index:1000;
}

/* LOGO */
.logo-container{
    text-align:center;
    padding:25px 15px;
}

.logo{ width:70px; }

.user-info{ transition:0.3s; }
.sidebar.collapsed .user-info{ display:none; }

/* MENU */
.menu{ list-style:none; padding:0; margin:0; }

.menu a{
    display:block;
    padding:14px 20px;
    color:white;
    text-decoration:none;
    transition:0.2s;
}

.menu a:hover,
.menu a.active{
    background:rgba(255,255,255,0.15);
    border-left:4px solid #fff;
}

/* BOTTOM */
.sidebar-bottom{
    margin-top:auto;
    padding-bottom:15px;
}

/* =========================
   🔥 INBOX BUTTON (IMPROVED)
========================= */
.sidebar-inbox{
    display:flex;
    justify-content:space-between;
    align-items:center;

    margin:10px 12px;
    padding:12px 14px;

    background:rgba(255,255,255,0.12);
    border-radius:12px;

    cursor:pointer;
    transition:0.25s;

    backdrop-filter: blur(6px);
}

.sidebar-inbox:hover{
    transform:translateY(-2px);
    background:rgba(255,255,255,0.22);
    box-shadow:0 6px 18px rgba(0,0,0,0.2);
}

.inbox-left{
    display:flex;
    align-items:center;
    gap:10px;
}

/* ICON STYLE */
.inbox-left i{
    background:#fff;
    color:#1e8f86;
    padding:8px;
    border-radius:8px;
    font-size:14px;
}

/* BADGE */
.sidebar-badge{
    background:#ff3b3b;
    color:white;
    width:20px;
    height:20px;

    border-radius:50%;
    display:flex;
    align-items:center;
    justify-content:center;

    font-size:11px;
    font-weight:bold;

    animation:pulse 1.5s infinite;
}

/* PULSE ANIMATION */
@keyframes pulse{
    0%{ transform:scale(1); }
    50%{ transform:scale(1.15); }
    100%{ transform:scale(1); }
}

/* LOGOUT */
.logout a{
    display:block;
    padding:14px 20px;
    color:white;
    text-decoration:none;
}

.logout a:hover{
    background:#239c92;
}

/* INBOX POPUP */
.inbox-popup{
    position:fixed;
    left:260px;
    bottom:90px;
    width:320px;
    max-height:400px;
    background:white;
    border-radius:12px;
    display:none;
    flex-direction:column;
    box-shadow:0 10px 30px rgba(0,0,0,0.25);
    z-index:999;
}

.inbox-header{
    background:#2bbbad;
    color:white;
    padding:12px;
    display:flex;
    justify-content:space-between;
}

.inbox-content{
    padding:10px;
    overflow-y:auto;
}

.inbox-item{
    padding:10px;
    border-bottom:1px solid #eee;
}

.view-btn{
    display:inline-block;
    margin-top:8px;
    padding:6px 10px;
    background:#2bbbad;
    color:white;
    border-radius:5px;
    text-decoration:none;
    font-size:12px;
}

</style>