<?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');

/* =========================
   HIDE SIDEBAR FOR GUEST
========================= */
if (
    !isset($_SESSION['user_id']) ||
    (isset($_SESSION['role']) && $_SESSION['role'] === 'guest')
) {
    return;
}

/* =========================
   USER INFO
========================= */
$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'];
    }
}
?>

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

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

<!-- SIDEBAR -->
<div class="sidebar" id="sidebar">

    <!-- LOGO -->
    <div class="logo-container">

        <img src="<?= $baseURL ?>assets/logo.png" class="logo" alt="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>

    <!-- MENU -->
    <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>

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

</div>

<!-- =========================
     FLOATING INBOX BUTTON
========================= -->
<div class="floating-inbox" onclick="toggleInbox()">
    <span class="icon">📩</span>
    <span id="notif-badge" class="notif-badge" style="display:none;">0</span>
</div>

<!-- =========================
     POPUP INBOX
========================= -->
<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
========================= -->
<script>

/* =========================
   SIDEBAR TOGGLE
========================= */
function toggleSidebar(){

    const sidebar = document.getElementById("sidebar");

    sidebar.classList.toggle("collapsed");
}

/* =========================
   INBOX TOGGLE
========================= */
function toggleInbox(){

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

    if(popup.style.display === "flex"){

        popup.style.display = "none";

    } else {

        popup.style.display = "flex";
        loadInbox();
    }
}

/* =========================
   LOAD INBOX
========================= */
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">

                    <div class="inbox-title">
                        🔧 <strong>${item.equipment_name}</strong>
                    </div>

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

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

                </div>
                `;
            });
        }

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

/* =========================
   BADGE
========================= */
function updateBadge(){

    fetch("<?= $baseURL ?>includes/get_unread_count.php")

    .then(res => res.json())

    .then(data => {

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

        if(data.count > 0){

            badge.style.display = "flex";
            badge.innerText = data.count;

        } else {

            badge.style.display = "none";
        }
    });
}

updateBadge();

setInterval(updateBadge, 15000);

</script>

<!-- =========================
     STYLE
========================= -->
<style>

/* =========================
   SIDEBAR
========================= */
.sidebar{

    position: fixed;
    left: 0;
    top: 0;

    width: 240px;
    height: 100vh;

    background: #2bbbad;
    color: white;

    transition: 0.3s;

    z-index: 999;
    overflow: hidden;
}

.sidebar.collapsed{

    width: 80px;
}

/* =========================
   TOGGLE BUTTON
========================= */
.sidebar-toggle{

    position: fixed;
    top: 15px;
    left: 15px;

    z-index: 1000;

    border: none;
    background: #239c92;
    color: white;

    width: 40px;
    height: 40px;

    border-radius: 8px;
    cursor: pointer;

    font-size: 18px;
}

/* =========================
   LOGO
========================= */
.logo-container{

    text-align: center;
    padding: 25px 15px;
}

.logo{

    width: 70px;
    margin-bottom: 15px;
}

/* =========================
   USER INFO
========================= */
.user-info{

    transition: 0.3s;
}

.sidebar.collapsed .user-info{

    display: none;
}

.user-name{

    font-weight: bold;
    font-size: 15px;
}

.user-role{

    font-size: 13px;
    margin-top: 5px;
}

.user-department{

    font-size: 12px;
    margin-top: 3px;
    opacity: 0.9;
}

/* =========================
   MENU
========================= */
.menu{

    list-style: none;
    padding: 0;
    margin: 20px 0;
}

.menu li{

    margin-bottom: 5px;
}

.menu a{

    display: block;
    padding: 14px 20px;

    color: white;
    text-decoration: none;

    transition: 0.2s;
}

.menu a:hover,
.menu a.active{

    background: #239c92;
}

/* =========================
   LOGOUT
========================= */
.logout{

    position: absolute;
    bottom: 20px;
    width: 100%;
}

.logout a{

    display: block;
    padding: 14px 20px;

    color: white;
    text-decoration: none;
}

.logout a:hover{

    background: #239c92;
}

/* =========================
   FLOATING INBOX
========================= */
.floating-inbox{

    position: fixed;
    right: 20px;
    bottom: 20px;

    width: 55px;
    height: 55px;

    background: #4CAF50;
    color: white;

    border-radius: 50%;

    display: flex;
    align-items: center;
    justify-content: center;

    cursor: pointer;

    z-index: 999;
}

/* =========================
   BADGE
========================= */
.notif-badge{

    position: absolute;
    top: -3px;
    right: -3px;

    background: red;
    color: white;

    width: 18px;
    height: 18px;

    border-radius: 50%;

    display: flex;
    align-items: center;
    justify-content: center;

    font-size: 11px;
}

/* =========================
   INBOX
========================= */
.inbox-popup{

    position: fixed;
    right: 20px;
    bottom: 85px;

    width: 320px;
    max-height: 400px;

    background: white;

    border-radius: 12px;

    overflow: hidden;

    display: none;
    flex-direction: column;

    box-shadow: 0 5px 20px rgba(0,0,0,0.2);

    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;
}

/* =========================
   MOBILE
========================= */
@media(max-width:768px){

    .sidebar{

        transform: translateX(-100%);
    }

    .sidebar.collapsed{

        transform: translateX(0);
        width: 240px;
    }
}

</style>