<?php
// -------------------- ACTIVE MENU SETUP --------------------
$menuActive = [
    "genealogy"        => "a",
    "list"             => "b",
    "registration"     => "b",
    "bonus"            => "c",
    "marketing"        => "d",
    "withdrawal"       => "e",
    "pin_transfer"     => "f",
    "buy_pin_fpx"      => "f",
    "generate"         => "f",
    "pinhistory"       => "f",
    "system"           => "g",
    "level_commission" => "g",
    "trip_packages"    => "g",
    "redeem"           => "h",
    "qr"               => "h",
    "dashboard"        => "i",
    "list_m"           => "j",
    "registration_m"   => "j",
    "profile"          => "k",
    "stock_purchase"   => "l",
    "order_list"       => "m",
    "wallet"           => "q"
];

$a = $b = $c = $d = $e = $f = $g = $h = $i = $j = $k = $l = $m = $q = "";
$x = "class=\"active-menu\" ";

// detect current page
$currentPage = basename($_SERVER["SCRIPT_FILENAME"], '.php');

// set active
if (isset($menuActive[$currentPage])) {
    ${$menuActive[$currentPage]} = $x;
}
?>
<!-- ==================== SIDEBAR ==================== -->
<style>
/* Sidebar Base */
.navbar-side {
    background: #222d32;
    color: #b8c7ce;
}
.navbar-side .nav > li > a {
    display: flex;
    align-items: center;
    padding: 12px 15px;
    color: #b8c7ce;
    text-decoration: none;
    transition: background 0.3s, color 0.3s;
}
.navbar-side .nav > li > a:hover,
.navbar-side .nav > li > a.active-menu {
    background: #1a2226;
    color: #fff;
}
/* Icon alignment */
.navbar-side .nav > li > a > i {
    width: 22px;
    text-align: center;
    margin-right: 10px;
}
/* Submenu base */
.nav-second-level,
.nav-third-level {
    list-style: none;
    padding: 0;
    margin: 0;
    background: #2c3b41;
}
.nav-second-level li a,
.nav-third-level li a {
    display: flex;
    align-items: center;
    padding: 10px 40px 10px 45px;
    color: #b8c7ce;
    text-decoration: none;
    transition: background 0.3s, color 0.3s;
}
.nav-second-level li a i,
.nav-third-level li a i {
    width: 18px;
    text-align: center;
    margin-right: 8px;
}
.nav-second-level li a:hover,
.nav-third-level li a:hover {
    background: #1a2226;
    color: #fff;
}
/* Third level (nested) indent */
.nav-third-level li a {
    padding-left: 65px;
}
/* Arrow rotation */
.fa.arrow {
    margin-left: auto;
    transition: transform 0.3s;
}
.open > a > .fa.arrow {
    transform: rotate(-90deg);
}
/* Badge style */
#orderBadge {
    font-size: 12px;
    padding: 2px 6px;
    border-radius: 12px;
    margin-left: 5px;
}
/* Blinking effect */
.blink {
    animation: blinkAnim 0.6s step-start 3;
}
@keyframes blinkAnim {
    50% { opacity: 0; }
}
</style>

<nav class="navbar-default navbar-side" role="navigation">
    <div class="sidebar-collapse">
        <ul class="nav" id="main-menu">
            
            <!-- USER INFO -->
            <li class="text-center">
<?php
                // Define username (optional check)
                $username = isset($_SESSION['username']) ? $_SESSION['username'] : '';
                
                // Define image path
                $userImage = "uploads/profile/{$username}.jpg";
                $defaultImage = "assets/img/find_user.png";
                
                // Check if user photo exists physically
                if (!empty($_SESSION['photo']) && file_exists($userImage)) {
                    $imgSrc = $userImage;
                } else {
                    $imgSrc = $defaultImage;
                }
?>
                <img src="<?= htmlspecialchars($imgSrc) ?>" 
                     class="user-image img-responsive" 
                     style="width:200px; height:200px; object-fit:cover; border-radius:50%;" 
                     alt="User profile image" />
                <br>
                <code><?= $_SESSION['username'] ?></code><br>
                <span style="color:#fff"><?= $_SESSION['namapenuh'] ?></span><br><br>
            </li>

            <!-- DASHBOARD -->
            <li>
                <a <?= $i ?> href="dashboard.php">
                    <i class="fa fa-dashboard"></i> Dashboard
                </a>
            </li>

            <!-- PROFILE -->
            <li>
                <a <?= $k ?> href="profile.php">
                    <i class="fa fa-circle-user"></i> My Profile
                </a>
            </li>

<?php if ($_SESSION['role'] !== "merchant") { ?>

            <!-- GENEALOGY -->
            <li>
                <a <?= $a ?> href="genealogy.php">
                    <i class="fa fa-sitemap"></i> Genealogy
                </a>
            </li>

            <!-- BONUS -->
            <li>
                <a <?= $c ?> href="#"><i class="fa fa-usd"></i> Bonus <span class="pull-right fa arrow"></span></a>
                <ul class="nav nav-second-level">
                    <li><a href="bonus.php"><i class="fa fa-history"></i> History</a></li>
                    <?php if ($_SESSION['role'] == "admin") { ?>
                        <li><a href="add_bonus.php"><i class="fa fa-plus-circle"></i> Add Bonus</a></li>
                        <li><a href="delete_bonus.php"><i class="fa fa-trash"></i> Delete Bonus</a></li>
                    <?php } ?>
                </ul>
            </li>

            <!-- WITHDRAWAL -->
            <li>
                <a <?= $e ?> href="withdrawal.php">
                    <i class="fa fa-money-bill-transfer"></i> Withdrawal
                </a>
            </li>

            <!-- MEMBERS -->
            <li>
                <a <?= $b ?> href="#"><i class="fa fa-users"></i> Members <span class="pull-right fa arrow"></span></a>
                <ul class="nav nav-second-level">
                    <?php if ($_SESSION['role'] == "admin") { ?>
                        <li><a href="list.php"><i class="fa fa-list"></i> Members List</a></li>
                    <?php } ?>
                    <li><a href="registration.php"><i class="fa fa-user-plus"></i> New Registration</a></li>
                </ul>
            </li>

            <!-- MERCHANTS -->
            <?php if ($_SESSION['role'] == "admin") { ?>
            <li>
                <a <?= $j ?> href="#"><i class="fa fa-store"></i> Merchants <span class="fa arrow"></span></a>
                <ul class="nav nav-second-level">
                    <li><a href="list_m.php"><i class="fa fa-list"></i> Merchant List</a></li>
                    <li><a href="registration_m.php"><i class="fa fa-user-plus"></i> New Registration</a></li>
                </ul>
            </li>
            <?php } ?>

            <!-- ORDER -->
            <li>
                <a <?= $m ?> href="#">
                    <i class="fa fa-bag-shopping"></i> Order 
                    <span id="orderBadge" class="badge bg-danger" style="color:white; background-color:red;">0</span>
                    <span class="fa arrow"></span>
                </a>
                <ul class="nav nav-second-level">
                    <li><a href="order_list.php"><i class="fa fa-list"></i> Order List</a></li>
                </ul>
            </li>

            <!-- STOCK -->
            <li>
                <a <?= $l ?> href="#"><i class="fa fa-boxes-stacked"></i> Stock <span class="fa arrow"></span></a>
                <ul class="nav nav-second-level">
                    <li><a href="stock_purchase.php"><i class="fa fa-cart-plus"></i> Stock Purchase</a></li>
                </ul>
            </li>

            <!-- PIN -->
            <li>
                <a <?= $f ?> href="#"><i class="fa fa-key"></i> PIN <span class="fa arrow"></span></a>
                <ul class="nav nav-second-level">
                    <?php if ($_SESSION['role'] == "admin") { ?>
                        <li><a href="generate.php"><i class="fa fa-cogs"></i> Generate PIN</a></li>
                    <?php } ?>
                    <li><a href="buy_pin_fpx.php"><i class="fa fa-credit-card"></i> Buy PIN via FPX</a></li>
                    <li><a href="pin_transfer.php"><i class="fa fa-exchange"></i> Transfer PIN</a></li>
                    <li>
                        <a href="#"><i class="fa fa-clock-rotate-left"></i> PIN History <span class="fa arrow"></span></a>
                        <ul class="nav nav-third-level">
                            <li><a href="pinhistory.php?x=unused"><i class="fa fa-circle"></i> Unused PIN</a></li>
                            <li><a href="pinhistory.php?x=used"><i class="fa fa-check"></i> Used PIN</a></li>
                        </ul>
                    </li>
                </ul>
            </li>

<?php } ?>

<?php if ($_SESSION['role'] == "merchant") { ?>
            <!-- EWALLET -->
            <li>
                <a <?= $q ?> href="wallet.php"><i class="fa fa-wallet"></i> eWallet</a>
            </li>
<?php } ?>

<?php if ($_SESSION['role'] == "merchant" || $_SESSION['role'] == "admin") { ?>
            <!-- REDEEM -->
            <li>
                <a <?= $h ?> href="#"><i class="fa fa-gift"></i> Redeem <span class="fa arrow"></span></a>
                <ul class="nav nav-second-level">
                    <li><a href="qr.php"><i class="fa fa-qrcode"></i> Scan QR Code</a></li>
                    <li><a href="redeem.php"><i class="fa fa-history"></i> History</a></li>
                </ul>
            </li>
<?php } ?>

<?php if ($_SESSION['role'] !== "merchant" && $_SESSION['role'] !== "admin") { ?>
            <!-- MARKETING -->
            <li>
                <a <?= $d ?> href="marketing.php"><i class="fa fa-bullhorn"></i> Marketing Tools</a>
            </li>
<?php } ?>

<?php if ($_SESSION['role'] == "admin") { ?>
            <!-- SETTINGS -->
            <li>
                <a <?= $g ?> href="#"><i class="fa fa-cogs"></i> Settings <span class="fa arrow"></span></a>
                <ul class="nav nav-second-level">
                    <li><a href="system.php"><i class="fa fa-gears"></i> MLM System</a></li>
                </ul>
            </li>
<?php } ?>

        </ul>
    </div>
</nav>

<!-- ==================== JS ORDER BADGE ==================== -->
<script>
let lastCount = null;

async function updateOrderBadge() {
    try {
        let res = await fetch('order_count.php');
        let data = await res.json();
        let badge = document.getElementById('orderBadge');

        if (badge) {
            if (lastCount !== null && lastCount !== data.count) {
                badge.textContent = data.count;
                badge.classList.add("blink");
                setTimeout(() => badge.classList.remove("blink"), 3000);
            } else {
                badge.textContent = data.count;
            }
            lastCount = data.count;
        }
    } catch (err) {
        console.error('Error fetching order count:', err);
    }
}

updateOrderBadge();
setInterval(updateOrderBadge, 10000);

// Menu toggle (hierarchy)
document.querySelectorAll('.nav > li > a').forEach(link => {
    link.addEventListener('click', e => {
        let nextEl = link.nextElementSibling;
        if(nextEl && nextEl.classList.contains('nav-second-level')) {
            e.preventDefault();
            link.parentElement.classList.toggle('open');
            nextEl.classList.toggle('open');
        }
    });
});
document.querySelectorAll('.nav-second-level > li > a').forEach(link => {
    link.addEventListener('click', e => {
        let nextEl = link.nextElementSibling;
        if(nextEl && nextEl.classList.contains('nav-third-level')) {
            e.preventDefault();
            link.parentElement.classList.toggle('open');
            nextEl.classList.toggle('open');
        }
    });
});
</script>
