<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("includes/function.php");

$usertype = $_SESSION["usertype_" . $dbname];
$dispyear = right($_SESSION["zdbyear_" . $dbname], 4);
$zdb      = $_SESSION["zdbyear_"   . $dbname];
$compcd   = $_SESSION["comp_"      . $dbname];
$loguser  = $_SESSION["username_"  . $dbname];

// ── Menu visibility for Staff (usertype=3): hide any module link the user
//    hasn't been granted a permission for. Uses the same passmain columns
//    that includes/check_permission.php enforces on the module pages
//    themselves, so the menu now matches what's actually reachable.
$_deniedMenu = [];
if ($usertype === 3) {
    $_menuPermCols = [
        'customer','supplier','agent','shipper','cha','godown','brand','product','expense',
        'purchexpense','bank','cash',
        'saleorder','dispatchalert','sale','salegst','salereturn',
        'purchentry','purchreturn','purchaseexport','inward','outward','damage','transfer','stockprod',
        'bankrecp','bankpay','cashrecp','cashpay','discountgiven','discounttaken','contra','jv',
        'ledger','payablerep','receivable','openbal',
        'salereg','salereturnreg','salegstreg','saleorderreg',
        'purreg','purchreturnreg','purchaseimportreg',
        'inwreg','otwreg','dmgreg','transferreg','contrareg','jvbook',
        'salesmanperf','custleading','custaging',
    ];
    mysqli_select_db($conn, $dbname);
    foreach ($_menuPermCols as $_mpc) {
        $_chk = mysqli_query($conn, "SHOW COLUMNS FROM `passmain` LIKE '$_mpc'");
        if ($_chk && mysqli_num_rows($_chk) == 0) {
            mysqli_query($conn, "ALTER TABLE `passmain` ADD COLUMN `$_mpc` VARCHAR(1) NOT NULL DEFAULT ''");
        }
    }
    $_prow = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT * FROM `passmain` WHERE `user`='" . mysqli_real_escape_string($conn, $loguser) . "'"));
    foreach ($_menuPermCols as $_mpc) {
        if (!$_prow || ($_prow[$_mpc] ?? '') !== 'Y') $_deniedMenu[] = $_mpc;
    }
}

$getcomp = mysqli_query($conn,
    "SELECT `code`, `name` FROM `company` WHERE `code`='$compcd'"
) or die(mysqli_error($conn));
$fetcomp = mysqli_fetch_array($getcomp);
$cmpname = $fetcomp['name'];

// ── Action → iframe src router ──────────────────────────────────────────
$action = isset($_GET["action"]) ? $_GET["action"] : "";
$src    = "default.php";

switch ($action) {

    // ── MASTERS ──────────────────────────────────────────
    case "supplier":     $src = "supplier.php?mode=last";         break;
    case "customer":     $src = "customer.php?mode=last";         break;
    case "agent":        $src = "agent.php?mode=last";            break;
    case "shipper":      $src = "shipper.php?mode=last";          break;
    case "cha":          $src = "cha.php?mode=last";              break;
    case "expense":      $src = "expense.php?mode=last";          break;
    case "bank":         $src = "bank.php?mode=last";             break;
    case "cash":         $src = "cash.php?mode=last";             break;
    case "godown":       $src = "godown.php?mode=last";           break;
    case "product":      $src = "product.php?mode=last";          break;
    case "brand":        $src = "brand.php?mode=last";            break;
    case "purchexpense": $src = "purchexpense.php?mode=last";     break;
    case "openbal":       $src = "openbal.php";                   break;

    // ── TRANSACTIONS ─────────────────────────────────────
    case "saleorder":      $src = "saleorder.php?mode=last";      break;
    case "dispatchalert":  $src = "dispatchalert.php";            break;
    case "purchentry":     $src = "purchentry.php?mode=last";     break;
    case "purchreturn":    $src = "purchreturn.php?mode=last";    break;
    case "purchaseexport": $src = "purchaseexport.php?mode=last"; break;
    case "sale":           $src = "sale.php?mode=last";           break;
    case "salegst":        $src = "salegst.php?mode=last";        break;
    case "salereturn":     $src = "salereturn.php?mode=last";     break;
    case "inward":         $src = "inward.php?mode=last";         break;
    case "outward":        $src = "outward.php?mode=last";        break;
    case "damage":         $src = "damage.php?mode=last";         break;
    case "transfer":       $src = "transfer.php?mode=last";       break;
    case "bankrecp":       $src = "bankrecp.php?mode=last";       break;
    case "bankpay":        $src = "bankpay.php?mode=last";        break;
    case "cashrecp":       $src = "cashrecp.php?mode=last";       break;
    case "cashpay":        $src = "cashpay.php?mode=last";        break;
    case "discountgiven":  $src = "discountgiven.php?mode=last";  break;
    case "discounttaken":  $src = "discounttaken.php?mode=last";  break;
    case "contra":         $src = "contra.php?mode=last";         break;
    case "jv":             $src = "jv.php?mode=last";             break;

    // ── REPORTS ──────────────────────────────────────────
    case "stock":        $src = "stock.php";                  break;
    case "stockprod":    $src = "stockprod.php";              break;
    case "ledger":       $src = "ledger.php";                 break;

    // Pending reports
    case "pending_despatch": $src = "pending_despatch.php"; break;
    case "pending_arrival":  $src = "pending_arrival.php";  break;
    case "pending_bill":     $src = "pending_bill.php";     break;
    case "bankbook":         $src = "bankbook.php?para=B";  break;
    case "cashbook":         $src = "bankbook.php?para=C";  break;
    case "payablerep":       $src = "osbill.php?para=P";    break;
    case "receivable":       $src = "osbill.php?para=R";    break;
    case "custaging":        $src = "custaging.php";        break;

    // ── REGISTERS ────────────────────────────────────────
    case "purreg":            $src = "purreg.php";            break;
    case "purchreturnreg":    $src = "purchreturnreg.php";    break;
    case "purchaseimportreg": $src = "purchaseimportreg.php"; break;
    case "salereg":           $src = "salereg.php";           break;
    case "salereturnreg":     $src = "salereturnreg.php";     break;
    case "salegstreg":        $src = "salegstreg.php";        break;
    case "saleorderreg":      $src = "saleorderreg.php";      break;
    case "inwreg":            $src = "inwreg.php";            break;
    case "otwreg":            $src = "otwreg.php";            break;
    case "dmgreg":            $src = "dmgreg.php";            break;
    case "transferreg":       $src = "transferreg.php";       break;
    case "contrareg":         $src = "contrareg.php";         break;
    case "jvbook":            $src = "jvbook.php";            break;
    case "salesmanperf":      $src = "salesmanperf.php";      break;
    case "custleading":       $src = "custleading.php";       break;

    // ── FINALIZATION ─────────────────────────────────────
    case "closestk":     $src = "closstk.php";               break;
    case "trbal":        $src = "trbal.php";                 break;
    case "profit":       $src = "profit.php";                break;
    case "profshar":     $src = "profshar.php";              break;
    case "balsheet":     $src = "balsheet.php";               break;

    // ── TOOLS (user dropdown) ─────────────────────────────
    case "company":     $src = "company.php?mode=last";     break;
    case "profile":     $src = "profile.php";               break;
    case "backup":      $src = "backup.php";                break;
    case "yearend":     $src = "yearend.php";               break;

    default:            $src = "default.php";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title><?php echo $project_title; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        /* height:100vh undercounts the visible area on mobile whenever the
           browser's own address/toolbar is showing (worst in landscape,
           where that chrome eats a much bigger share of a short screen) —
           with overflow:hidden below, that undercounted sliver becomes
           permanently inaccessible, which is exactly what was clipping the
           bottom action bar inside the content iframe. 100dvh tracks the
           actual visible viewport instead; the 100% line above it is the
           fallback for browsers that don't support dvh yet. */
        html, body { height: 100%; height: 100dvh; margin: 0; overflow: hidden; }

        /* ── Dropdown panel ── */
        .dropdown-menu {
            display: none;
            position: fixed;           /* fixed = escapes ALL overflow:hidden/auto clipping */
            top: 50px;
            left: 0;
            min-width: 215px;
            background: #fff;
            border-top: 3px solid #2563eb;
            border-radius: 0 0 10px 10px;
            box-shadow: 0 10px 35px rgba(0,0,0,.18);
            z-index: 99999;
            overflow-y: auto;
            max-height: calc(100vh - 56px);
            max-height: calc(100dvh - 56px);
        }
        .dropdown-menu.align-right { left: auto; right: 0; }

        .dropdown-menu a,
        .dropdown-menu button.dd-btn {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 9px 18px;
            font-size: 13px;
            color: #374151;
            text-decoration: none;
            transition: background .12s, color .12s;
            white-space: nowrap;
            width: 100%;
            border: none;
            background: transparent;
            cursor: pointer;
            text-align: left;
            box-sizing: border-box;
        }
        .dropdown-menu a:hover,
        .dropdown-menu button.dd-btn:hover { background: #eff6ff; color: #1d4ed8; }
        .dropdown-menu a:hover i,
        .dropdown-menu button.dd-btn:hover i { color: #2563eb; }
        .dropdown-menu a.danger       { color: #dc2626; }
        .dropdown-menu a.danger:hover { background: #fef2f2; color: #b91c1c; }

        .menu-divider { border: none; border-top: 1px solid #f1f5f9; margin: 4px 0; }
        .menu-section-label {
            padding: 7px 18px 2px;
            font-size: 10px;
            font-weight: 700;
            letter-spacing: .08em;
            text-transform: uppercase;
            color: #94a3b8;
        }
        .menu-user-header {
            padding: 10px 18px 9px;
            border-bottom: 1px solid #f1f5f9;
            background: #f8fafc;
        }

        /* Active nav button */
        .nav-module-btn.is-open { background: rgba(255,255,255,.1); color: #fff; }
        /* Prevent menu items from shrinking on mobile */
        .nav-module { flex-shrink: 0; }
        .nav-module-btn { white-space: nowrap; flex-shrink: 0; }

        /* iframe blocker prevents iframe from stealing mouse events when dropdown is open */
        #iframe-blocker {
            display: none;
            position: absolute;
            top: 50px; left: 0; right: 0; bottom: 0;
            z-index: 8000;
        }

        /* Desktop default — real CSS (not inline) so the mobile media query
           below can actually override it; inline display:flex would win over
           any @media rule regardless of viewport width. */
        #nav-tabs, #navRight { display: flex; }
        /* On desktop the wrapper is invisible to layout — nav-tabs/navRight
           stay direct flex children of #main-nav exactly as before. */
        #mobileNavPanel { display: contents; }

        /* ══ Mobile hamburger navigation ══ */
        #mobileMenuBtn { display: none; }

        @media (max-width: 900px) {
            #mobileMenuBtn {
                display: flex; align-items: center; justify-content: center;
                width: 46px; height: 100%; flex-shrink: 0;
                background: transparent; border: none; cursor: pointer;
                color: #cbd5e1; font-size: 18px;
            }
            #mobileMenuBtn:hover { background: rgba(255,255,255,.08); }

            /* One single fixed dropdown panel holding both the module tabs
               and the company/year/user section, stacked vertically — not
               two independently-fixed panels pinned to the same spot
               (that overlap and hide the dashboard behind them). */
            #mobileNavPanel {
                display: none;
                position: fixed;
                top: 50px; left: 0; right: 0;
                flex-direction: column;
                background: #1e293b;
                max-height: calc(100vh - 50px);
                max-height: calc(100dvh - 50px);
                overflow-y: auto;
                -webkit-overflow-scrolling: touch;
                border-top: 1px solid #334155;
                box-shadow: 0 12px 30px rgba(0,0,0,.3);
                z-index: 9500;
            }
            #main-nav.mobile-open #mobileNavPanel { display: flex; }

            #nav-tabs, #navRight {
                display: flex;
                flex-direction: column;
                align-items: stretch;
                width: 100%;
                max-height: none;
                overflow: visible;
                position: static;
            }

            #nav-tabs > div { flex-direction: column; width: 100%; }
            #nav-tabs .nav-module, #navRight .nav-module { width: 100%; }
            #nav-tabs .nav-module-btn,
            #navRight .nav-module-btn,
            #navRight > a {
                width: 100%; height: auto !important;
                padding: 14px 18px !important;
                border-bottom: 1px solid rgba(255,255,255,.06);
                justify-content: space-between;
            }
            #navRight { border-left: none; margin-left: 0; border-top: 1px solid #334155; }

            /* Dropdown panels become inline accordions instead of floating popovers */
            #nav-tabs .dropdown-menu, #navRight .dropdown-menu {
                position: static !important;
                box-shadow: none !important;
                border-radius: 0 !important;
                max-height: none !important;
                background: #0f172a !important;
                border-top: none !important;
            }
            #nav-tabs .dropdown-menu a, #navRight .dropdown-menu a,
            #nav-tabs .dropdown-menu button.dd-btn, #navRight .dropdown-menu button.dd-btn {
                color: #cbd5e1 !important;
                padding-left: 34px !important;
            }
            #nav-tabs .dropdown-menu a:hover, #navRight .dropdown-menu a:hover {
                background: rgba(255,255,255,.06) !important; color: #fff !important;
            }
            #nav-tabs .menu-section-label { color: #64748b !important; }
            #navRight .menu-user-header { background: #0f172a !important; }
            #navRight .menu-user-header div { color: #fff !important; }
        }
    </style>
</head>

<body style="display:flex; flex-direction:column; height:100vh; height:100dvh; overflow:hidden;">

    <!-- ══════════════════════════════ TOP NAVBAR ══ -->
    <nav id="main-nav" style="height:50px; flex-shrink:0; background:#1e293b; display:flex; align-items:stretch; position:relative; z-index:9999; overflow:visible;">

        <!-- Brand -->
        <a href="mainmenu.php"
           style="display:flex; align-items:center; gap:10px; padding:0 20px;
                  background:#0f172a; border-right:1px solid #334155;
                  text-decoration:none; flex-shrink:0;"
           onmouseover="this.style.background='#020617'"
           onmouseout="this.style.background='#0f172a'">
            <div style="width:28px;height:28px;background:#2563eb;border-radius:6px;
                        display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                                    <img src="images/tclublogo.jpeg">

            </div>
            <span style="font-weight:700;font-size:13px;color:#fff;letter-spacing:.05em;">
                <?php echo $project_name; ?>
            </span>
        </a>

        <!-- Mobile hamburger toggle (hidden on desktop, shown under 900px) -->
        <button id="mobileMenuBtn" type="button" aria-label="Toggle menu">
            <i class="fa fa-bars"></i>
        </button>

        <div id="mobileNavPanel">
        <!-- ── 4 Module Dropdowns ── -->
        <div id="nav-tabs" style="align-items:stretch; flex:1; overflow-x:auto; overflow-y:visible; -webkit-overflow-scrolling:touch; scrollbar-width:none;">
        <style>#nav-tabs::-webkit-scrollbar{display:none;}</style>
        <div style="display:flex; align-items:stretch; flex-shrink:0;">

            <!-- MASTERS -->
            <div class="nav-module" style="position:relative;">
                <button class="nav-module-btn"
                    style="display:flex;align-items:center;gap:8px;padding:0 18px;height:100%;
                           background:transparent;border:none;cursor:pointer;
                           font-size:13px;font-weight:600;color:#cbd5e1;
                           transition:background .15s,color .15s;"
                    onmouseover="if(!$(this).hasClass('is-open'))this.style.background='rgba(255,255,255,.07)'"
                    onmouseout="if(!$(this).hasClass('is-open'))this.style.background='transparent'">
                    <i class="fa fa-layer-group" style="color:#60a5fa;font-size:11px;"></i>
                    Masters
                    <i class="fa fa-chevron-down nav-arrow" style="color:#64748b;font-size:10px;margin-left:2px;transition:transform .2s;"></i>
                </button>
                <div class="dropdown-menu">
                    <div class="menu-section-label">Parties</div>
                    <a href="?action=customer" data-perm="customer">  <i class="fa fa-users w-4 text-center" style="color:#9ca3af;"></i> Customer</a>
                    <a href="?action=supplier" data-perm="supplier">  <i class="fa fa-truck w-4 text-center" style="color:#9ca3af;"></i> Supplier</a>
                    <a href="?action=agent" data-perm="agent">     <i class="fa fa-handshake w-4 text-center" style="color:#9ca3af;"></i> Salesman</a>
                    <a href="?action=shipper" data-perm="shipper">   <i class="fa fa-ship w-4 text-center" style="color:#9ca3af;"></i> Shipper</a>
                    <a href="?action=cha" data-perm="cha">       <i class="fa fa-file-signature w-4 text-center" style="color:#9ca3af;"></i> CHA</a>
                    <div class="menu-section-label">Item &amp; Stock</div>
                    <a href="?action=godown" data-perm="godown">    <i class="fa fa-warehouse w-4 text-center" style="color:#9ca3af;"></i> Godown</a>
                    <a href="?action=brand" data-perm="brand">     <i class="fa fa-box w-4 text-center" style="color:#9ca3af;"></i> Brand</a>
                    <a href="?action=product" data-perm="product">   <i class="fa fa-box w-4 text-center" style="color:#9ca3af;"></i> Product</a>
                    <hr class="menu-divider">
                    <hr class="menu-divider">
                    <div class="menu-section-label">Accounts</div>
                    <a href="?action=expense" data-perm="expense">   <i class="fa fa-receipt w-4 text-center" style="color:#9ca3af;"></i> Expense</a>
                    <a href="?action=purchexpense" data-perm="purchexpense">   <i class="fa fa-receipt w-4 text-center" style="color:#9ca3af;"></i> Purchase Expense</a>
                    <a href="?action=bank" data-perm="bank">      <i class="fa fa-landmark w-4 text-center" style="color:#9ca3af;"></i> Bank</a>
                    <a href="?action=cash" data-perm="cash">      <i class="fa fa-money-bill-wave w-4 text-center" style="color:#9ca3af;"></i> Cash</a>
                    <a href="?action=openbal" data-perm="openbal"> <i class="fa fa-scale-balanced w-4 text-center" style="color:#9ca3af;"></i> Opening Balance</a>
                </div>
            </div>

            <!-- TRANSACTIONS -->
            <div class="nav-module" style="position:relative;">
                <button class="nav-module-btn"
                    style="display:flex;align-items:center;gap:8px;padding:0 18px;height:100%;
                           background:transparent;border:none;cursor:pointer;
                           font-size:13px;font-weight:600;color:#cbd5e1;
                           transition:background .15s,color .15s;"
                    onmouseover="if(!$(this).hasClass('is-open'))this.style.background='rgba(255,255,255,.07)'"
                    onmouseout="if(!$(this).hasClass('is-open'))this.style.background='transparent'">
                    <i class="fa fa-file-invoice" style="color:#f59e0b;font-size:11px;"></i>
                    Order & Invoices
                    <i class="fa fa-chevron-down nav-arrow" style="color:#64748b;font-size:10px;margin-left:2px;transition:transform .2s;"></i>
                </button>
                <div class="dropdown-menu">                    
                    <div class="menu-section-label">Trading</div>
                    <a href="?action=saleorder" data-perm="saleorder"><i class="fa fa-file-invoice w-4 text-center" style="color:#9ca3af;"></i>Sale Order</a>
                    <a href="?action=dispatchalert" data-perm="dispatchalert"><i class="fa fa-truck-fast w-4 text-center" style="color:#9ca3af;"></i>Dispatch Alert</a>
                    <a href="?action=sale" data-perm="sale"><i class="fa fa-file-invoice w-4 text-center" style="color:#2563eb;"></i>Sale Invoice</a>
                    <a href="?action=salegst" data-perm="salegst"><i class="fa fa-receipt w-4 text-center" style="color:#f59e0b;"></i>Sale GST</a>
                    <a href="?action=salereturn" data-perm="salereturn"><i class="fa fa-rotate-left w-4 text-center" style="color:#ef4444;"></i>Sale Return</a>
                    <hr class="menu-divider">
                    <div class="menu-section-label">Sale Registers</div>
                    <a href="?action=salereg" data-perm="salereg">    <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Sale Register</a>
                    <a href="?action=salereturnreg" data-perm="salereturnreg"> <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Sale Return Register</a>
                    <a href="?action=salegstreg" data-perm="salegstreg"> <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Sale GST Register</a>
                    <a href="?action=saleorderreg" data-perm="saleorderreg"> <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Sale Order Register</a>
                    <hr class="menu-divider">
                    <div class="menu-section-label">Performance Reports</div>
                    <a href="?action=salesmanperf" data-perm="salesmanperf"> <i class="fa fa-user-tie w-4 text-center" style="color:#9ca3af;"></i> Salesman Performance</a>
                    <a href="?action=custleading" data-perm="custleading"> <i class="fa fa-ranking-star w-4 text-center" style="color:#9ca3af;"></i> Leading Customers</a>

                </div>
            </div>

            <!-- REPORTS -->
            <div class="nav-module" style="position:relative;">
                <button class="nav-module-btn"
                    style="display:flex;align-items:center;gap:8px;padding:0 18px;height:100%;
                           background:transparent;border:none;cursor:pointer;
                           font-size:13px;font-weight:600;color:#cbd5e1;
                           transition:background .15s,color .15s;"
                    onmouseover="if(!$(this).hasClass('is-open'))this.style.background='rgba(255,255,255,.07)'"
                    onmouseout="if(!$(this).hasClass('is-open'))this.style.background='transparent'">
                    <i class="fa fa-shopping-cart" style="color:green;font-size:11px;"></i>
                    Inventory
                    <i class="fa fa-chevron-down nav-arrow" style="color:#64748b;font-size:10px;margin-left:2px;transition:transform .2s;"></i>
                </button>
                <div class="dropdown-menu">
                    <div class="menu-section-label">Purchase</div>
                    <a href="?action=purchentry" data-perm="purchentry"> <i class="fa fa-cart-plus w-4 text-center" style="color:#9ca3af;"></i> Purchase Local</a>
                    <a href="?action=purchreturn" data-perm="purchreturn"> <i class="fa fa-rotate-left w-4 text-center" style="color:#9ca3af;"></i> Purchase Return </a>
                    <a href="?action=purchaseexport" data-perm="purchaseexport"> <i class="fa fa-truck-ramp-box w-4 text-center" style="color:#9ca3af;"></i> Purchase Import </a>
                    <hr class="menu-divider">
                    <div class="menu-section-label">Purchase Registers</div>
                    <a href="?action=purreg" data-perm="purreg">            <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Purchase Register</a>
                    <a href="?action=purchreturnreg" data-perm="purchreturnreg">    <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Purchase Return Register</a>
                    <a href="?action=purchaseimportreg" data-perm="purchaseimportreg"> <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Purchase Import Register</a>
                    <hr class="menu-divider">
                    <div class="menu-section-label">Stock Report</div>
                    <a href="?action=stockprod" data-perm="stockprod">  <i class="fa fa-boxes w-4 text-center" style="color:#9ca3af;"></i> Product Stock</a>
                    <div class="menu-section-label">Stock Movement</div>
                    <a href="?action=inward" data-perm="inward">    <i class="fa fa-arrow-down w-4 text-center" style="color:#16a34a;"></i> Inward</a>
                    <a href="?action=outward" data-perm="outward">   <i class="fa fa-arrow-up w-4 text-center" style="color:#dc2626;"></i> Outward</a>
                    <a href="?action=damage" data-perm="damage">    <i class="fa fa-triangle-exclamation w-4 text-center" style="color:#ea580c;"></i> Damage</a>
                    <a href="?action=transfer" data-perm="transfer">    <i class="fa fa-right-left w-4 text-center" style="color:#7c3aed;"></i> Internal Transfer</a>
                    <hr class="menu-divider">
                    <div class="menu-section-label">Stock Registers</div>
                    <a href="?action=inwreg" data-perm="inwreg">    <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Inward Register</a>
                    <a href="?action=otwreg" data-perm="otwreg">    <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Outward Register</a>
                    <a href="?action=dmgreg" data-perm="dmgreg">    <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Damage Register</a>
                    <a href="?action=transferreg" data-perm="transferreg">    <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Transfer Register</a>
                    <hr class="menu-divider">

                </div>
            </div>

            <!-- REGISTERS -->
            <div class="nav-module" style="position:relative;">
                <button class="nav-module-btn"
                    style="display:flex;align-items:center;gap:8px;padding:0 18px;height:100%;
                           background:transparent;border:none;cursor:pointer;
                           font-size:13px;font-weight:600;color:#cbd5e1;
                           transition:background .15s,color .15s;"
                    onmouseover="if(!$(this).hasClass('is-open'))this.style.background='rgba(255,255,255,.07)'"
                    onmouseout="if(!$(this).hasClass('is-open'))this.style.background='transparent'">
                    <i class="fa fa-calculator" style="color:#2563eb;font-size:11px;"></i>
                    Accounts
                    <i class="fa fa-chevron-down nav-arrow" style="color:#64748b;font-size:10px;margin-left:2px;transition:transform .2s;"></i>
                </button>
                
                <div class="dropdown-menu">  
                    <hr class="menu-divider">
                    <div class="menu-section-label">Bank</div>
                    <a href="?action=bankrecp" data-perm="bankrecp">  <i class="fa fa-circle-arrow-down w-4 text-center" style="color:#9ca3af;"></i> Bank Receipt</a>
                    <a href="?action=bankpay" data-perm="bankpay">   <i class="fa fa-circle-arrow-up w-4 text-center" style="color:#9ca3af;"></i> Bank Payment</a>
                    <div class="menu-section-label">Cash</div>
                    <a href="?action=cashrecp" data-perm="cashrecp">  <i class="fa fa-circle-arrow-down w-4 text-center" style="color:#9ca3af;"></i> Cash Receipt</a>
                    <a href="?action=cashpay" data-perm="cashpay">   <i class="fa fa-circle-arrow-up w-4 text-center" style="color:#9ca3af;"></i> Cash Payment</a>
                    <div class="menu-section-label">Contra</div>
                    <a href="?action=contra" data-perm="contra">   <i class="fa fa-right-left w-4 text-center" style="color:#9ca3af;"></i> Contra Entry</a>
                    <div class="menu-section-label">Journal</div>
                    <a href="?action=jv" data-perm="jv">   <i class="fa fa-book w-4 text-center" style="color:#9ca3af;"></i> Journal Voucher</a>
                    <div class="menu-section-label">Discount</div>
                    <a href="?action=discountgiven" data-perm="discountgiven"> <i class="fa fa-tags w-4 text-center" style="color:#9ca3af;"></i> Discount Given</a>
                    <a href="?action=discounttaken" data-perm="discounttaken"> <i class="fa fa-tags w-4 text-center" style="color:#9ca3af;"></i> Discount Taken</a>
                    <a href="?action=ledger" data-perm="ledger">     <i class="fa fa-book-open w-4 text-center" style="color:#9ca3af;"></i> Ledger</a>
                    <hr class="menu-divider">
                    <a href="?action=bankbook">   <i class="fa fa-landmark w-4 text-center" style="color:#9ca3af;"></i> Bank Book</a>
                    <a href="?action=cashbook">   <i class="fa fa-coins w-4 text-center" style="color:#9ca3af;"></i> Cash Book</a>
                    <a href="?action=contrareg" data-perm="contrareg"> <i class="fa fa-list w-4 text-center" style="color:#9ca3af;"></i> Contra Register</a>
                    <a href="?action=jvbook" data-perm="jvbook"> <i class="fa fa-book w-4 text-center" style="color:#9ca3af;"></i> JV Book</a>
                    <hr class="menu-divider">
                    <div class="menu-section-label">Outstanding</div>
                    <a href="?action=payablerep" data-perm="payablerep"> <i class="fa fa-hourglass w-4 text-center" style="color:#9ca3af;"></i> Payable</a>
                    <a href="?action=receivable" data-perm="receivable"> <i class="fa fa-hourglass-half w-4 text-center" style="color:#9ca3af;"></i> Receivable</a>
                    <a href="?action=custaging" data-perm="custaging"> <i class="fa fa-layer-group w-4 text-center" style="color:#9ca3af;"></i> Customer Ageing</a>

                </div>
            </div>

            <!-- FINALIZATION -->
            <div class="nav-module" style="position:relative;">
                <button class="nav-module-btn"
                    style="display:flex;align-items:center;gap:8px;padding:0 18px;height:100%;
                           background:transparent;border:none;cursor:pointer;
                           font-size:13px;font-weight:600;color:#cbd5e1;
                           transition:background .15s,color .15s;"
                    onmouseover="if(!$(this).hasClass('is-open'))this.style.background='rgba(255,255,255,.07)'"
                    onmouseout="if(!$(this).hasClass('is-open'))this.style.background='transparent'">
                    <i class="fa fa-flag-checkered" style="color:#2563eb;font-size:11px;"></i>
                    Finalization
                    <i class="fa fa-chevron-down nav-arrow" style="color:#64748b;font-size:10px;margin-left:2px;transition:transform .2s;"></i>
                </button>
                
                <div class="dropdown-menu">
                    <div class="menu-section-label">Year End</div>
                    <a href="?action=closestk"> <i class="fa fa-boxes-stacked w-4 text-center" style="color:#9ca3af;"></i> Closing Stock</a>
                    <hr class="menu-divider">
                    <div class="menu-section-label">Statements</div>
                    <a href="?action=trbal">    <i class="fa fa-scale-balanced w-4 text-center" style="color:#9ca3af;"></i> Trial Balance</a>
                    <a href="?action=profit">   <i class="fa fa-chart-line w-4 text-center" style="color:#9ca3af;"></i> Profit / Loss</a>
                    <a href="?action=profshar"> <i class="fa fa-handshake w-4 text-center" style="color:#9ca3af;"></i> Profit Sharing</a>
                    <a href="?action=balsheet"> <i class="fa fa-file-invoice-dollar w-4 text-center" style="color:#9ca3af;"></i> Balance Sheet</a>
                </div>
            </div>

        </div><!-- /4 modules -->

        </div><!-- /nav-tabs -->

        <!-- ── Right: company | year | user ── -->
        <div id="navRight" style="align-items:stretch; border-left:1px solid #334155; background:#1e293b; flex-shrink:0; margin-left:auto;">

            <!-- Company -->
            <a href="comp.php"
               style="display:flex;align-items:center;gap:7px;padding:0 16px;
                      font-size:12px;color:#94a3b8;text-decoration:none;
                      border-right:1px solid #334155;transition:background .15s,color .15s;"
               onmouseover="this.style.background='rgba(255,255,255,.07)';this.style.color='#fff'"
               onmouseout="this.style.background='transparent';this.style.color='#94a3b8'">
                <i class="fa fa-building" style="color:#475569;font-size:11px;"></i>
                <span style="font-weight:600;color:#cbd5e1;"><?php echo htmlspecialchars($cmpname); ?></span>
            </a>

            <!-- Year -->
            <a href="year.php"
               style="display:flex;align-items:center;gap:7px;padding:0 16px;
                      font-size:12px;color:#94a3b8;text-decoration:none;
                      border-right:1px solid #334155;transition:background .15s,color .15s;"
               onmouseover="this.style.background='rgba(255,255,255,.07)'"
               onmouseout="this.style.background='transparent'">
                <i class="fa fa-calendar-days" style="color:#3b82f6;font-size:11px;"></i>
                <span style="font-weight:700;color:#60a5fa;"><?php echo $dispyear; ?></span>
            </a>

            <!-- Notifications -->
            <div class="nav-module" style="position:relative;">
                <button id="notifBtn" class="nav-module-btn"
                    style="display:flex;align-items:center;gap:6px;padding:0 16px;height:100%;
                           background:transparent;border:none;cursor:pointer;
                           font-size:13px;font-weight:600;color:#cbd5e1;position:relative;
                           transition:background .15s,color .15s;"
                    onmouseover="this.style.background='rgba(255,255,255,.07)'"
                    onmouseout="this.style.background='transparent'">
                    <i class="fa fa-bell" style="color:#fbbf24;font-size:14px;"></i>
                    <span id="notifBadge" style="display:none;position:absolute;top:8px;right:8px;
                          background:#dc2626;color:#fff;font-size:9px;font-weight:700;
                          border-radius:9px;min-width:16px;height:16px;line-height:16px;
                          text-align:center;padding:0 3px;"></span>
                </button>
                <div id="notifDropdown" class="dropdown-menu align-right"
                     style="display:none;min-width:340px;max-height:420px;overflow:auto;">
                    <div class="menu-user-header" style="display:flex;align-items:center;justify-content:space-between;">
                        <span style="font-size:13px;font-weight:700;color:#1e293b;">Notifications</span>
                        <a href="javascript:void(0)" id="notifMarkAll" style="font-size:11px;color:#2563eb;text-decoration:none;">Mark all read</a>
                    </div>
                    <div id="notifList" style="padding:6px 0;"></div>
                </div>
            </div>

            <!-- User dropdown -->
            <div class="nav-module" style="position:relative;">
                <button class="nav-module-btn"
                    style="display:flex;align-items:center;gap:8px;padding:0 16px;height:100%;
                           background:transparent;border:none;cursor:pointer;
                           font-size:12px;font-weight:600;color:#cbd5e1;
                           transition:background .15s,color .15s;"
                    onmouseover="if(!$(this).hasClass('is-open'))this.style.background='rgba(255,255,255,.07)'"
                    onmouseout="if(!$(this).hasClass('is-open'))this.style.background='transparent'">
                    <i class="fa fa-user-circle" style="color:#64748b;font-size:14px;"></i>
                    <?php echo htmlspecialchars($loguser); ?>
                    <i class="fa fa-chevron-down nav-arrow" style="color:#64748b;font-size:10px;transition:transform .2s;"></i>
                </button>
                <div class="dropdown-menu align-right" style="min-width:200px;">
                    <div class="menu-user-header">
                        <div style="font-size:13px;font-weight:700;color:#1e293b;"><?php echo htmlspecialchars($loguser); ?></div>
                        <div style="font-size:11px;color:#94a3b8;"><?php echo $usertype == 1 ? 'Administrator' : ($usertype == 3 ? 'Staff (Salesman)' : 'Manager'); ?></div>
                    </div>
                    <a href="?action=profile"> <i class="fa fa-user w-4 text-center" style="color:#9ca3af;"></i> Profile</a>
                    <hr class="menu-divider">
                    <a href="?action=company"> <i class="fa fa-building w-4 text-center" style="color:#9ca3af;"></i> Company Setup</a>
                    <?php if ($usertype == 1): ?>
                    <a href="?action=backup">  <i class="fa fa-cloud-arrow-down w-4 text-center" style="color:#9ca3af;"></i> Backup</a>
                    <?php endif; ?>
                    <!-- <a href="?action=yearend"> <i class="fa fa-calendar-check w-4 text-center" style="color:#9ca3af;"></i> Year End</a> -->
                    <hr class="menu-divider">
                    <a href="logout.php" class="danger"> <i class="fa fa-power-off w-4 text-center"></i> Logout</a>
                </div>
            </div>

        </div><!-- /right section -->
        </div><!-- /mobileNavPanel -->

    </nav>
    <!-- ══════════════════════════════ /TOP NAVBAR ══ -->

    <!-- Transparent overlay to block iframe mouse capture when dropdown is open -->
    <div id="iframe-blocker" style="display:none;position:absolute;top:50px;left:0;right:0;bottom:0;z-index:8000;"></div>

    <!-- ══════════════════════════════ CONTENT IFRAME ══ -->
    <main style="flex:1; overflow:hidden;">
        <iframe
            id="main-frame"
            src="<?php echo htmlspecialchars($src); ?>"
            name="frame1"
            style="width:100%;height:100%;border:none;display:block;"
            scrolling="auto"
        ></iframe>
    </main>
    <!-- ══════════════════════════════ /CONTENT IFRAME ══ -->


    <script>
    $(function () {

        // ── Hide menu links Staff has no permission for ─────────────────
        var deniedMenuPerms = <?php echo json_encode($_deniedMenu); ?>;
        deniedMenuPerms.forEach(function (key) {
            $('a[data-perm="' + key + '"]').hide();
        });

        function closeAll() {
            $('.dropdown-menu').slideUp(130);
            $('.nav-arrow').css('transform', 'rotate(0deg)');
            $('.nav-module-btn').removeClass('is-open').css('background', 'transparent');
            $('#iframe-blocker').hide();
        }

        // ── Mobile hamburger menu toggle (visual only) ──────────────────
        $('#mobileMenuBtn').on('click', function (e) {
            e.stopPropagation();
            $('#main-nav').toggleClass('mobile-open');
            if (!$('#main-nav').hasClass('mobile-open')) closeAll();
        });

        // Tapping an actual menu link on mobile should close the panel
        // (the iframe navigates; no page reload happens on mainmenu.php itself)
        $('#nav-tabs, #navRight').on('click', 'a[href*="?action="], a[href="comp.php"], a[href="year.php"], a[href="logout.php"]', function () {
            $('#main-nav').removeClass('mobile-open');
        });

        // ── Notifications ────────────────────────────────────────────
        function notifLoad() {
            $.post('includes/notifications.php', {action:'list'}, function (data) {
                if (data.error) { $('#notifBtn').hide(); return; }
                var $badge = $('#notifBadge');
                if (data.unread > 0) {
                    $badge.text(data.unread).show();
                } else {
                    $badge.hide();
                }
                var html = '';
                if (data.items.length == 0) {
                    html = '<div style="padding:18px 16px;text-align:center;color:#94a3b8;font-size:12.5px;">No notifications</div>';
                } else {
                    data.items.forEach(function (n) {
                        var unread = n.readflag != 'Y';
                        html += '<div class="notif-item" data-id="' + n.id + '" data-vouchno="' + n.vouchno + '" style="padding:10px 16px;border-bottom:1px solid #f1f5f9;cursor:pointer;'
                              + (unread ? 'background:#eff6ff;' : '') + '">';
                        html += '<div class="notif-msg" style="font-size:12.5px;color:#1e293b;line-height:1.4;">' + n.message + '</div>';
                        html += '<div style="font-size:10.5px;color:#94a3b8;margin-top:3px;">' + (n.createddate || '') + (n.vouchno ? ' &middot; Voucher #' + n.vouchno : '') + '</div>';
                        if (n.vouchno) {
                            html += '<div style="margin-top:6px;">'
                                  + '<button class="notif-view" data-vouchno="' + n.vouchno + '" data-id="' + n.id + '" data-reftype="' + (n.reftype || '') + '" '
                                  + 'style="padding:4px 10px;border:1px solid #cbd5e1;border-radius:5px;background:#fff;color:#374151;font-size:11.5px;font-weight:600;cursor:pointer;">'
                                  + '<i class="fa fa-eye"></i> View Entry</button>'
                                  + '</div>';
                        }
                        html += '</div>';
                    });
                }
                $('#notifList').html(html);
            }, 'json');
        }

        // Which page each notification's "View Entry" should open — keyed by
        // the `reftype` stored on the notification (saleorder.php's dispatch
        // alerts, sale.php's auto-generated invoices). Bill Confirmation /
        // China notifications have been removed from this bell — that's a
        // separate application's workflow.
        var notifReftypePage = {
            'saleorder': 'saleorder.php',
            'sale':      'sale.php'
        };

        $('#notifList').on('click', '.notif-view', function (e) {
            e.stopPropagation();
            var $btn     = $(this);
            var vouchno  = $btn.data('vouchno');
            var id       = $btn.data('id');
            var reftype  = $btn.data('reftype');
            var page     = notifReftypePage[reftype];
            if (!page) { closeAll(); return; }

            $.post('includes/notifications.php', {action:'read', id:id}, function () { notifLoad(); }, 'json');

            $('#main-frame').attr('src', page + '?mode=edit&vouchno=' + vouchno);
            closeAll();
        });

        $('#notifMarkAll').on('click', function (e) {
            e.stopPropagation();
            $.post('includes/notifications.php', {action:'readall'}, function () { notifLoad(); }, 'json');
        });

        $('#notifBtn').on('click', function () {
            setTimeout(notifLoad, 50);
        });

        notifLoad();
        setInterval(notifLoad, 30000);

        // Open / toggle dropdown on button click
        $('.nav-module-btn').on('click', function (e) {
            e.stopPropagation();

            var $btn   = $(this);
            var $menu  = $btn.siblings('.dropdown-menu');
            var $arrow = $btn.find('.nav-arrow');
            var isOpen = $menu.is(':visible');

            closeAll();

            if (!isOpen) {
                // Position the fixed dropdown under the button
                var rect = $btn[0].getBoundingClientRect();
                if ($menu.hasClass('align-right')) {
                    $menu.css({ left: 'auto', right: (window.innerWidth - rect.right) + 'px' });
                } else {
                    $menu.css({ left: rect.left + 'px', right: 'auto' });
                }
                $menu.slideDown(170);
                $arrow.css('transform', 'rotate(180deg)');
                $btn.addClass('is-open').css('background', 'rgba(255,255,255,.1)');
                $('#iframe-blocker').show();
            }
        });

        // Clicks inside a dropdown don't close it
        $('.dropdown-menu').on('click', function (e) {
            e.stopPropagation();
        });

        // Clicks inside the mobile nav/right panel shouldn't bubble and
        // immediately collapse the hamburger panel itself
        $('#nav-tabs, #navRight').on('click', function (e) {
            e.stopPropagation();
        });

        // Close on outside click or iframe-blocker click
        $(document).on('click', function () {
            closeAll();
            $('#main-nav').removeClass('mobile-open');
        });
        $('#iframe-blocker').on('click', closeAll);

        // Close on Escape
        $(document).on('keydown', function (e) {
            if (e.key === 'Escape') { closeAll(); $('#main-nav').removeClass('mobile-open'); }
        });

    });
    </script>

</body>
</html>
