<?php
$username    = $_SESSION['user_name'] ?? 'User';
$userRole    = $_SESSION['user_role'] ?? '';
$userInitial = strtoupper(substr($username, 0, 1));
$currentPath = $_SERVER['PHP_SELF'] ?? '';

function isActive(string $path): string {
    global $currentPath;
    return (strpos($currentPath, $path) !== false) ? 'active' : '';
}
function isGroupActive(array $paths): string {
    global $currentPath;
    foreach ($paths as $p) {
        if (strpos($currentPath, $p) !== false) return 'active';
    }
    return '';
}
?>

<nav class="navbar" id="navbar">

    <!-- Brand -->
    <a href="<?= BASE_URL ?>/dashboard.php" class="navbar-brand">
        <div class="brand-icon"><i class="fas fa-store-alt"></i></div>
        <span class="brand-name">My ERP</span>
    </a>

    <!-- Mobile toggle -->
    <button class="nav-toggle" id="navToggle" aria-label="Toggle menu">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Menu -->
    <ul class="nav-menu" id="navMenu">

        <li class="nav-item">
            <a href="<?= BASE_URL ?>/dashboard.php"
               class="nav-link <?= isActive('dashboard') ?>">
                <i class="fas fa-home"></i>
                <span>Dashboard</span>
            </a>
        </li>

        <?php if (hasPermission('products') || hasPermission('vendors') || hasPermission('clients')): ?>
        <li class="nav-item nav-dropdown <?= isGroupActive(['/products/', '/vendors/', '/clients/']) ?>">
            <a class="nav-link" href="#">
                <i class="fas fa-layer-group"></i>
                <span>Master</span>
                <i class="fas fa-chevron-down nav-caret"></i>
            </a>
            <ul class="nav-submenu">
                <?php if (hasPermission('products')): ?>
                <li><a href="<?= BASE_URL ?>/products/index.php" class="<?= isActive('/products/') ?>">
                    <i class="fas fa-box"></i> Products
                </a></li>
                <?php endif; ?>
                <?php if (hasPermission('vendors')): ?>
                <li><a href="<?= BASE_URL ?>/vendors/index.php" class="<?= isActive('/vendors/') ?>">
                    <i class="fas fa-truck"></i> Vendors
                </a></li>
                <?php endif; ?>
                <?php if (hasPermission('clients')): ?>
                <li><a href="<?= BASE_URL ?>/clients/index.php" class="<?= isActive('/clients/') ?>">
                    <i class="fas fa-users"></i> Clients
                </a></li>
                <?php endif; ?>
            </ul>
        </li>
        <?php endif; ?>

        <?php
        $hasMasterAccess    = hasPermission('master_sales');
        $canViewPurchases   = hasPermission('purchases') || hasPermission('purchase_returns');
        $canViewSales       = hasPermission('sales') || hasPermission('sales_returns') || $hasMasterAccess;
        $txnPurchasesActive = $canViewPurchases && isGroupActive(['/purchases/', '/purchase_returns/']) === 'active';
        $txnSalesPaths      = $hasMasterAccess
            ? ['/master_sales/', '/master_returns/', '/sales/', '/sales_return/']
            : ['/sales/', '/sales_return/'];
        $txnSalesActive     = $canViewSales && isGroupActive($txnSalesPaths) === 'active';
        $txnActive          = ($txnPurchasesActive || $txnSalesActive) ? 'active' : '';
        ?>
        <?php if ($canViewPurchases || $canViewSales): ?>
        <li class="nav-item nav-dropdown <?= $txnActive ?>">
            <a class="nav-link" href="#">
                <i class="fas fa-exchange-alt"></i>
                <span>Transactions</span>
                <i class="fas fa-chevron-down nav-caret"></i>
            </a>
            <ul class="nav-submenu">

                <!-- Purchases sub-group -->
                <?php if ($canViewPurchases): ?>
                <li class="nav-sub-group <?= $txnPurchasesActive ? 'open' : '' ?>">
                    <a class="nav-sub-group-toggle <?= $txnPurchasesActive ? 'active' : '' ?>" href="#">
                        <i class="fas fa-file-invoice"></i>
                        Purchases
                        <i class="fas fa-chevron-right nav-sub-caret"></i>
                    </a>
                    <ul class="nav-sub-submenu">
                        <?php if (hasPermission('purchases')): ?>
                        <li><a href="<?= BASE_URL ?>/purchases/index.php" class="<?= isActive('/purchases/') ?>">
                            <i class="fas fa-shopping-basket"></i> Purchase Orders
                        </a></li>
                        <?php endif; ?>
                        <?php if (hasPermission('purchase_returns')): ?>
                        <li><a href="<?= BASE_URL ?>/purchase_returns/index.php" class="<?= isActive('/purchase_returns/') ?>">
                            <i class="fas fa-undo"></i> Purchase Returns
                        </a></li>
                        <?php endif; ?>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- Sales sub-group -->
                <?php if ($canViewSales): ?>
                <li class="nav-sub-group <?= $txnSalesActive ? 'open' : '' ?>">
                    <a class="nav-sub-group-toggle <?= $txnSalesActive ? 'active' : '' ?>" href="#">
                        <i class="fas fa-receipt"></i>
                        Sales
                        <i class="fas fa-chevron-right nav-sub-caret"></i>
                    </a>
                    <ul class="nav-sub-submenu">
                        <?php if ($hasMasterAccess): ?>
                        <li><a href="<?= BASE_URL ?>/master_sales/index.php" class="<?= isActive('/master_sales/') ?>">
                            <i class="fas fa-layer-group"></i> Master Invoice
                        </a></li>
                        <li><a href="<?= BASE_URL ?>/master_returns/index.php" class="<?= isActive('/master_returns/') ?>">
                            <i class="fas fa-rotate-left"></i> Master Returns
                        </a></li>
                        <li class="nav-sub-divider"></li>
                        <?php endif; ?>
                        <?php if (hasPermission('sales')): ?>
                        <li><a href="<?= BASE_URL ?>/sales/index.php" class="<?= isActive('/sales/') ?>">
                            <i class="fas fa-file-invoice-dollar"></i> Sales Invoices
                        </a></li>
                        <?php endif; ?>
                        <?php if (hasPermission('sales_returns')): ?>
                        <li><a href="<?= BASE_URL ?>/sales_return/index.php" class="<?= isActive('/sales_return/') ?>">
                            <i class="fas fa-undo"></i> Sales Returns
                        </a></li>
                        <?php endif; ?>
                    </ul>
                </li>
                <?php endif; ?>

            </ul>
        </li>
        <?php endif; ?>

        <?php if (hasPermission('inventory')): ?>
        <li class="nav-item nav-dropdown <?= isGroupActive(['/inventory/']) ?>">
            <a class="nav-link" href="#">
                <i class="fas fa-boxes"></i>
                <span>Inventory</span>
                <i class="fas fa-chevron-down nav-caret"></i>
            </a>
            <ul class="nav-submenu">
                <li><a href="<?= BASE_URL ?>/inventory/stocks.php" class="<?= isActive('stocks') ?>">
                    <i class="fas fa-warehouse"></i> Stocks
                </a></li>
                <li><a href="<?= BASE_URL ?>/inventory/product_inventory.php" class="<?= isActive('product_inventory') ?>">
                    <i class="fas fa-clipboard-list"></i> Product Inventory
                </a></li>
            </ul>
        </li>
        <?php endif; ?>

        <?php if (hasPermission('reports')): ?>
        <li class="nav-item">
            <a href="<?= BASE_URL ?>/reports/index.php"
               class="nav-link <?= isActive('/reports/') ?>">
                <i class="fas fa-chart-bar"></i>
                <span>Reports</span>
            </a>
        </li>
        <?php endif; ?>

        <?php if (hasPermission('ledgers')): ?>
        <li class="nav-item nav-dropdown <?= isGroupActive(['/vendor_ledger/', '/client_ledger/']) ?>">
            <a class="nav-link" href="#">
                <i class="fas fa-book"></i>
                <span>Ledgers</span>
                <i class="fas fa-chevron-down nav-caret"></i>
            </a>
            <ul class="nav-submenu">
                <li><a href="<?= BASE_URL ?>/vendor_ledger/index.php" class="<?= isActive('/vendor_ledger/') ?>">
                    <i class="fas fa-truck"></i> Vendor Ledger
                </a></li>
                <li><a href="<?= BASE_URL ?>/client_ledger/index.php" class="<?= isActive('/client_ledger/') ?>">
                    <i class="fas fa-users"></i> Client Ledger
                </a></li>
            </ul>
        </li>
        <?php endif; ?>

        <?php if (hasPermission('settings') || $userRole === 'admin'): ?>
        <li class="nav-item nav-dropdown <?= isGroupActive(['/settings/']) ?>">
            <a class="nav-link" href="#">
                <i class="fas fa-cog"></i>
                <span>Settings</span>
                <i class="fas fa-chevron-down nav-caret"></i>
            </a>
            <ul class="nav-submenu">
                <?php if ($userRole === 'admin'): ?>
                <li><a href="<?= BASE_URL ?>/settings/companies/index.php" class="<?= isGroupActive(['/settings/companies/']) ?>">
                    <i class="fas fa-building"></i> Companies
                </a></li>
                <li><a href="<?= BASE_URL ?>/includes/invoice_sequences.php" class="<?= isActive('/includes/invoice_sequences.php') ?>">
                    <i class="fas fa-list-ol"></i> Invoice Sequences
                </a></li>
                <li><a href="<?= BASE_URL ?>/settings/bank_accounts.php" class="<?= isActive('/settings/bank_accounts.php') ?>">
                    <i class="fas fa-university"></i> Bank Accounts
                </a></li>
                <li><a href="<?= BASE_URL ?>/settings/users/index.php" class="<?= isGroupActive(['/settings/users/']) ?>">
                    <i class="fas fa-users-cog"></i> Users
                </a></li>
                <li><a href="<?= BASE_URL ?>/settings/roles/index.php" class="<?= isGroupActive(['/settings/roles/']) ?>">
                    <i class="fas fa-shield-alt"></i> Roles & Permissions
                </a></li>
                <li><a href="<?= BASE_URL ?>/company_select.php" class="<?= isActive('/company_select') ?>">
                    <i class="fas fa-exchange-alt"></i> Switch Company
                </a></li>
                <?php else: ?>
                <?php if (hasPermission('settings', 'edit')): ?>
                <li><a href="<?= BASE_URL ?>/settings/company.php" class="<?= isActive('/settings/company.php') ?>">
                    <i class="fas fa-building"></i> Company Details
                </a></li>
                <li><a href="<?= BASE_URL ?>/settings/bank_accounts.php" class="<?= isActive('/settings/bank_accounts.php') ?>">
                    <i class="fas fa-university"></i> Bank Accounts
                </a></li>
                <?php endif; ?>
                <li><a href="<?= BASE_URL ?>/settings/users/form.php?id=<?= (int)$_SESSION['user_id'] ?>" class="<?= isActive('/settings/users/form.php') ?>">
                    <i class="fas fa-user-edit"></i> My Profile
                </a></li>
                <?php endif; ?>
            </ul>
        </li>
        <?php endif; ?>

        <li class="nav-item nav-menu-logout">
            <a href="<?= BASE_URL ?>/logout.php" class="nav-link" style="color:#f87171;">
                <i class="fas fa-sign-out-alt"></i>
                <span>Logout</span>
            </a>
        </li>

    </ul>

    <!-- Right: active company indicator + user + logout -->
    <div class="navbar-right">
        <?php
        // Show active company badge (only if DB connection is available and company set)
        if (!empty($_SESSION['active_company_id']) && isset($conn)) {
            $__activeCid = (int)$_SESSION['active_company_id'];
            $__coRow = $conn->query("SELECT company_name FROM company_master WHERE id = $__activeCid LIMIT 1");
            $__coName = ($__coRow && $__coRow->num_rows) ? $__coRow->fetch_row()[0] : null;
            if ($__coName):
        ?>
        <a href="<?= BASE_URL ?>/company_select.php"
           title="Active company — click to switch"
           style="display:flex;align-items:center;gap:6px;background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.1);border-radius:20px;padding:4px 10px;color:#cbd5e1;font-size:12px;text-decoration:none;white-space:nowrap;max-width:180px;overflow:hidden;transition:background 0.15s;"
           onmouseover="this.style.background='rgba(255,255,255,0.13)'"
           onmouseout="this.style.background='rgba(255,255,255,0.07)'">
            <i class="fas fa-building" style="font-size:11px;flex-shrink:0;"></i>
            <span style="overflow:hidden;text-overflow:ellipsis;"><?= htmlspecialchars($__coName) ?></span>
        </a>
        <?php
            endif;
        }
        ?>
        <div class="nav-user">
            <div class="nav-avatar"><?= htmlspecialchars($userInitial) ?></div>
            <div class="nav-user-info">
                <span class="nav-user-name"><?= htmlspecialchars($username) ?></span>
                <?php if($userRole): ?>
                <span class="nav-user-role"><?= htmlspecialchars($userRole) ?></span>
                <?php endif; ?>
            </div>
        </div>
        <a href="<?= BASE_URL ?>/logout.php" class="nav-logout" title="Logout">
            <i class="fas fa-sign-out-alt"></i>
            <span>Logout</span>
        </a>
    </div>

</nav>

<div class="content" id="mainContent">
<div class="page-body">
<?php /* ---- individual page content below ---- */ ?>

<script>
// Mobile nav toggle
document.getElementById('navToggle').addEventListener('click', function() {
    document.getElementById('navMenu').classList.toggle('open');
});

// Dropdown: click to open on desktop too (more reliable than pure CSS hover)
document.querySelectorAll('.nav-dropdown > .nav-link').forEach(function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        const parent = this.parentElement;
        const isAlreadyOpen = parent.classList.contains('open');
        document.querySelectorAll('.nav-dropdown').forEach(function(d) {
            d.classList.remove('open');
        });
        if (!isAlreadyOpen) parent.classList.add('open');
    });
});

// Close dropdowns on outside click
document.addEventListener('click', function(e) {
    if (!e.target.closest('.nav-dropdown')) {
        document.querySelectorAll('.nav-dropdown').forEach(function(d) {
            d.classList.remove('open');
        });
    }
});

// Sub-group toggles (Transactions → Purchases / Sales)
document.querySelectorAll('.nav-sub-group-toggle').forEach(function(toggle) {
    toggle.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        const group = this.closest('.nav-sub-group');
        const isOpen = group.classList.contains('open');
        // Close siblings
        group.closest('.nav-submenu').querySelectorAll('.nav-sub-group').forEach(function(g) {
            g.classList.remove('open');
        });
        if (!isOpen) group.classList.add('open');
    });
});

// Close mobile menu only on real page navigation links (not toggles with href="#")
document.querySelectorAll('.nav-menu .nav-submenu a:not([href="#"]), .nav-menu > .nav-item > .nav-link:not([href="#"])').forEach(function(a) {
    a.addEventListener('click', function() {
        document.getElementById('navMenu').classList.remove('open');
    });
});
</script>
