<?php
include_once __DIR__ . '/../includes/config.php';
if (!isset($_SESSION['user_id'])) {
    header('Location: ../index.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("
    SELECT u.first_name, u.last_name, r.role_name, s.store_name, u.profile_picture
    FROM users u
    JOIN roles r ON u.role_id = r.id
    LEFT JOIN stores s ON u.store_id = s.id
    WHERE u.id = ?
");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

$full_name = htmlspecialchars($user['first_name'] . ' ' . $user['last_name']);
$role = htmlspecialchars($user['role_name']);
$store = isset($user['store_name']) ? htmlspecialchars($user['store_name']) : 'Super Admin';
$profile_pic = !empty($user['profile_picture']) ? htmlspecialchars($user['profile_picture']) : 'default_profile.png';
$profile_pic_url = "/digital_pos/uploads/" . $profile_pic;

$dashboard_url = match (strtolower($role)) {
    'admin' => '../admin/admin_dashboard.php',
    'manager' => '../manager/manager_dashboard.php',
    'cashier' => '../cashier/cashier_dashboard.php',
    default => '../accountant/accountant_dashboard.php',
};
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Dashboard - <?= $full_name ?></title>
    <link rel="icon" href="/digital_pos/images/logo.png" type="image/png" />
    <style>
    /* Your existing CSS */
    .glassy-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 30px;
        height: 40px;
        background: rgba(30, 30, 30, 0.79);
        backdrop-filter: blur(14px);
        -webkit-backdrop-filter: blur(14px);
        box-shadow: 0 8px 15px rgba(0,0,0,0.3);
        font-family: 'Segoe UI', sans-serif;
        color: #eee;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 999;
        border-bottom: 1px solid rgba(255, 255, 255, 0);
    }
    .glassy-header .left {
        display: flex;
        align-items: center;
        gap: 18px;
    }
    .glassy-header img.profile-pic {
        width: 46px;
        height: 46px;
        border-radius: 50%;
        border: 2px solid #ffa500;
        object-fit: cover;
    }
    .glassy-header .info {
        display: flex;
        flex-direction: column;
        font-size: 14px;
    }
    .glassy-header .info .name {
        font-weight: bold;
        font-size: 16px;
        color: #ffa500;
    }
    .super-badge {
        margin-left: 6px;
        background: gold;
        color: black;
        font-size: 11px;
        padding: 2px 7px;
        border-radius: 12px;
        font-weight: bold;
        vertical-align: middle;
        box-shadow: 0 0 5px rgba(0,0,0,0.2);
    }
    .glassy-header .right {
        display: flex;
        align-items: center;
        gap: 20px;
        font-size: 14px;
    }
    .nav-links {
        display: flex;
        align-items: center;
        gap: 16px;
    }
    .nav-links a,
    .dropdown-toggle {
        color: #eee;
        text-decoration: none;
        font-weight: 600;
        padding: 6px 12px;
        border-radius: 6px;
        transition: background 0.3s ease;
        white-space: nowrap;
        cursor: pointer;
    }
    .nav-links a:hover,
    .dropdown-toggle:hover {
        background: rgba(255, 165, 0, 0.2);
    }
    .nav-links a.active {
        background: rgba(255, 165, 0, 0.3);
        color: #fff;
    }
    .dropdown {
        position: relative;
    }
    .dropdown-content {
        display: none;
        position: absolute;
        top: 38px;
        left: 0;
        background: rgba(20, 20, 20, 0.95);
        backdrop-filter: blur(8px);
        border-radius: 8px;
        box-shadow: 0 6px 14px rgba(0,0,0,0.3);
        min-width: 210px;
        z-index: 1000;
    }
    .dropdown-content a {
        display: block;
        padding: 10px 16px;
        font-size: 13px;
        color: #eee;
        border-bottom: 1px solid rgba(255,255,255,0.08);
    }
    .dropdown-content a:hover {
        background: rgba(255, 165, 0, 0.15);
    }
    .dropdown.show .dropdown-content {
        display: block;
    }
    .date-time {
        font-variant-numeric: tabular-nums;
        white-space: nowrap;
        min-width: 160px;
        text-align: right;
        font-weight: 600;
        color: #ffa500;
    }
    .badge {
        background: red;
        color: white;
        border-radius: 50%;
        font-size: 12px;
        padding: 2px 6px;
        margin-left: 5px;
    }
    </style>
</head>
<body>

<header class="glassy-header">
    <div class="left">
        <a href="../shared/profile.php" title="View Profile">
            <img src="<?= $profile_pic_url ?>" alt="<?= $full_name ?> Profile Picture" class="profile-pic" />
        </a>
        <div class="info">
            <div class="name">
                <?= $full_name ?>
                <?php if ($store === 'Super Admin'): ?>
                    <span class="super-badge" title="Super Admin">&#x1F451;</span>
                <?php endif; ?>
            </div>
            <div><?= $role ?> | <?= $store ?></div>
        </div>
    </div>

    <div class="right">
        <nav class="nav-links">
            <a href="<?= $dashboard_url ?>" class="dashboard-link">Dashboard</a>

            <?php if (in_array($role, ['Admin', 'Manager'])): ?>
                <div class="dropdown" onclick="toggleDropdown(this)">
                    <div class="dropdown-toggle">Inventory</div>
                    <div class="dropdown-content">
                        <?php if ($role === 'Admin'): ?>
                            <a href="/digital_pos/pages/admin/products.php">All Products</a>
                            <a href="/digital_pos/pages/admin/add_product.php">Add Product</a>
                            <a href="/digital_pos/pages/admin/add_supplier.php">Add Supplier</a>
                            <a href="/digital_pos/pages/admin/suppliers.php">Suppliers</a>
                            <a href="/digital_pos/pages/admin/categories.php">Categories</a>
                            <a href="/digital_pos/pages/admin/inventory.php">Current Stock</a>
                            <a href="/digital_pos/pages/admin/inventory_summary.php">Inventory Summary</a>
                            <a href="/digital_pos/pages/admin/add_stock.php">Add Stock Entry</a>
                            <a href="/digital_pos/pages/admin/stock_entries.php">Stock Entry History</a>
                            <a href="/digital_pos/pages/admin/adjust_stock.php">Stock Adjustment</a>
                            <a href="/digital_pos/pages/admin/stock_adjustments_log.php">Adjustment History</a>
                            <a href="/digital_pos/pages/admin/stock_transfer.php">Stock Transfer</a>
                            <a href="/digital_pos/pages/admin/stock_transfer_log.php">Transfer Log</a>
                        <?php elseif ($role === 'Manager'): ?>
                            <a href="/digital_pos/pages/manager/products.php">All Products</a>
                            <a href="/digital_pos/pages/manager/inventory.php">Current Stock</a>
                            <a href="/digital_pos/pages/manager/inventory_summary.php">Inventory Summary</a>
                            <a href="/digital_pos/pages/manager/add_stock.php">Add Stock Entry</a>
                            <a href="/digital_pos/pages/manager/stock_entries.php">Stock Entry History</a>
                            <a href="/digital_pos/pages/manager/adjust_stock.php">Stock Adjustment</a>
                            <a href="/digital_pos/pages/manager/stock_adjustments_log.php">Adjustment History</a>
                            <a href="/digital_pos/pages/manager/stock_transfer.php">Stock Transfer</a>
                            <a href="/digital_pos/pages/manager/stock_transfer_log.php">Transfer Log</a>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="dropdown" onclick="toggleDropdown(this)">
                    <div class="dropdown-toggle">Expenses</div>
                    <div class="dropdown-content">
                        <?php if ($role === 'Admin'): ?>
                            <a href="/digital_pos/pages/admin/expenses.php">All Expenses</a>
                            <a href="/digital_pos/pages/admin/add_expense.php">Add Expense</a>
                            <a href="/digital_pos/pages/admin/expense_types.php">Expense Types</a>
                            <a href="/digital_pos/pages/admin/expense_reports.php">Expense Reports</a>
                        <?php elseif ($role === 'Manager'): ?>
                            <a href="/digital_pos/pages/manager/expenses.php">All Expenses</a>
                            <a href="/digital_pos/pages/manager/add_expense.php">Add Expense</a>
                            <a href="/digital_pos/pages/manager/expense_reports.php">Expense Reports</a>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <a href="../shared/messaging/inbox.php" class="notification" id="messageNotification">Messages
                <span class="badge" id="messageBadge">0</span>
            </a>
            <a href="../../logout.php">Logout</a>
        </nav>
        <div class="date-time" id="dateTimeDisplay"></div>
    </div>
</header>

<script>
function updateDateTime() {
    const now = new Date();
    const formatted = now.getFullYear() + '-' +
        String(now.getMonth() + 1).padStart(2, '0') + '-' +
        String(now.getDate()).padStart(2, '0') + ' ' +
        String(now.getHours()).padStart(2, '0') + ':' +
        String(now.getMinutes()).padStart(2, '0') + ':' +
        String(now.getSeconds()).padStart(2, '0');
    document.getElementById('dateTimeDisplay').textContent = formatted;
}
updateDateTime();
setInterval(updateDateTime, 1000);

function fetchUnreadMessages() {
    if (!navigator.onLine) return;
    fetch('../messaging/unread_count.php', { credentials: 'same-origin' })
        .then(res => res.json())
        .then(data => {
            const badge = document.getElementById('messageBadge');
            if (data.success && data.count > 0) {
                badge.textContent = data.count;
                badge.style.display = 'inline-block';
            } else {
                badge.style.display = 'none';
            }
        }).catch(err => {
            console.warn('Message badge fetch failed:', err);
        });
}
fetchUnreadMessages();
setInterval(fetchUnreadMessages, 30000);

function toggleDropdown(dropdown) {
    document.querySelectorAll('.dropdown').forEach(d => {
        if (d !== dropdown) d.classList.remove('show');
    });
    dropdown.classList.toggle('show');
}
document.addEventListener('click', function (e) {
    if (!e.target.closest('.dropdown')) {
        document.querySelectorAll('.dropdown').forEach(d => d.classList.remove('show'));
    }
});
</script>

</body>
</html>
