<?php
// my_main_sidebar.php
// --- Assumes session is already started in layout.php ---

// --- User info ---
$username   = isset($_SESSION['username']) ? ucfirst(strtolower(htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8'))) : "Guest";
$role       = $_SESSION['role'] ?? '';
$department = $_SESSION['department'] ?? '';
$isAdmin    = in_array($role, ['Admin', 'Super']);

// --- Current page ---
$currentPage = basename($_SERVER['PHP_SELF'], '.php');

// --- Menu groups ---
$businessPages   = ['businessPermits','addBusinessPermit','editBusinessPermit','healthPermits','addHealthPermit','editHealthPermit','businessPermitsList','businessCertificates'];
$cdfPages        = ['grantsList','loans','secBursaryList','skillsBursaryList','addGrant', 'addSecBursary','conveyanceList'];
$projectPages    = ['projectsList','tasksList'];
$posPages        = ['transactionList'];
$ledgerPages     = ['arrearsList'];
$voucherPages    = ['paymentVoucherList'];
$banksPages      = ['banksDashboard','bankDeposit'];
$valuationPages  = ['propertyList'];

// --- Deeds Records pages ---
$deedsPages      = ['deedsList'];

// --- Helper functions ---
function isGroupOpen(array $pages, string $current) {
    return in_array($current, $pages, true);
}

function getDashboardRoute(string $role, string $department): string {
    $adminRoles = ['Super', 'Admin', 'Confidential'];
    if (in_array($role, $adminRoles, true)) return 'admin_dashboard';

    $deptRoutes = [
        'Finance'        => 'financeDashboard',
        'Planning'       => 'planningDashboard',
        'Engineering'    => 'dash_engineering',
        'Institutional'  => 'dash_institutional',
        'HR'             => 'dash_hr',
        'Administration' => 'dash_administration',
        'Clearing & Forwarding' => 'clearing/dashboard',
    ];

    return $deptRoutes[$department] ?? 'dashboard';
}

// --- Compute dashboard route and active flag ---
$dashboardRoute  = getDashboardRoute($role, $department);
$dashboardActive = ($currentPage === $dashboardRoute) || ($currentPage === 'dashboard');

// --- Finance menu permission ---
$roleNorm = strtolower(trim($role));
$deptNorm = strtolower(trim($department));
$allowedRoles = ['accounts', 'assistantaccountant', 'accountant', 'chiefaccountant'];
$allowedDepts = ['finance'];
$canFinanceMenu = in_array($roleNorm, $allowedRoles, true) && in_array($deptNorm, $allowedDepts, true);

// --- Clearing & Forwarding pages ---
$clearingShipmentsPages = ['shipments', 'createShipment', 'viewShipment', 'trackShipment'];
$clearingInvoicesPages  = ['invoicesList'];
$clearingMessagesPages  = ['chat', 'messages'];

// --- Clearing menu permission (department + roles) ---
$isClearingDept = (strcasecmp(trim($department), 'Clearing & Forwarding') === 0);
$clearingRolesAllowed = ['Admin','Accounts','customsagent','customsclient'];
$canClearingMenu = $isClearingDept && in_array($role, $clearingRolesAllowed, true);

// --- Deeds Records permission (Admin OR Institutional + Legal/ICT + Approver) ---
$deptIsInstitutional = (strcasecmp(trim($department), 'Institutional') === 0);

$section = $_SESSION['section'] ?? '';   // Legal / ICT from DB
$roleVal = $_SESSION['role'] ?? '';      // Admin / Approver / etc

$allowedSections = ['Legal', 'ICT'];
$allowedRoles    = ['Approver', 'Initiator','Data Entry'];         // ✅ NEW

$canDeedsMenu =
    $isAdmin
    || (
        $deptIsInstitutional
        && in_array($section, $allowedSections, true)
        && in_array($roleVal, $allowedRoles, true)
    );



?>

<aside class="app-sidebar sticky" id="sidebar">
    <div class="main-sidebar-header">
        <a href="<?= BASE_URL . $dashboardRoute ?>" class="header-logo">
            <img src="<?= BASE_URL ?>assets/images/brand-logos/smartsync_logo_dark.svg" alt="logo" class="desktop-logo" style="height:33px!important;">
            <img src="<?= BASE_URL ?>assets/images/brand-logos/toggle-dark.png" alt="logo" class="toggle-dark">
            <img src="<?= BASE_URL ?>assets/images/brand-logos/smartsync_logo.svg" alt="logo" class="desktop-dark" style="height:33px!important;">
            <img src="<?= BASE_URL ?>assets/images/brand-logos/toggle-logo.png" alt="logo" class="toggle-logo">
        </a>
    </div>

    <div class="main-sidebar" id="sidebar-scroll">
        <nav class="main-menu-container nav nav-pills flex-column sub-open">
            <ul class="main-menu">

                <!-- Dashboard -->
                <li class="slide">
                    <a href="<?= BASE_URL . $dashboardRoute ?>" class="side-menu__item <?= $dashboardActive ? 'active' : '' ?>">
                        <i class="bi bi-house-door side-menu__icon"></i>
                        <span class="side-menu__label">Dashboard</span>
                    </a>
                </li>

                <!-- Clearing & Forwarding -->
                <?php if ($canClearingMenu): ?>
                  <?php $openShip = isGroupOpen($clearingShipmentsPages, $currentPage); ?>

                  <li class="slide__category"><span class="category-name">Clearing & Forwarding</span></li>

                  <!-- Shipments -->
                  <li class="slide has-sub <?= $openShip ? 'open' : '' ?>">
                    <a href="javascript:void(0);" class="side-menu__item <?= $openShip ? 'active' : '' ?>">
                      <i class="bi bi-truck side-menu__icon"></i>
                      <span class="side-menu__label">Shipments</span>
                      <i class="fe fe-chevron-right side-menu__angle"></i>
                    </a>
                    <ul class="slide-menu child1" style="<?= $openShip ? 'display:block;' : '' ?>">

                      <li>
                        <a href="<?= BASE_URL ?>clearing/createShipment.php"
                           class="side-menu__item <?= $currentPage === 'createShipment' ? 'active' : '' ?>">
                          Add Shipment
                        </a>
                      </li>

                      <li>
                        <a href="<?= BASE_URL ?>clearing/trackShipment.php"
                           class="side-menu__item <?= $currentPage === 'trackShipment' ? 'active' : '' ?>">
                          Track Shipment
                        </a>
                      </li>

                      <li>
                        <a href="<?= BASE_URL ?>clearing/shipments.php"
                           class="side-menu__item <?= $currentPage === 'shipments' ? 'active' : '' ?>">
                          All Shipments
                        </a>
                      </li>
                    </ul>
                  </li>

                  <!-- My Invoices -->
                  <li class="slide">
                    <a href="<?= BASE_URL ?>clearing/invoicesList.php"
                       class="side-menu__item <?= $currentPage === 'invoicesList' ? 'active' : '' ?>">
                      <i class="bi bi-receipt side-menu__icon"></i>
                      <span class="side-menu__label">My Invoices</span>
                    </a>
                  </li>

                  <!-- Messages -->
                  <li class="slide">
                    <a href="<?= BASE_URL ?>clearing/chat.php"
                       class="side-menu__item <?= $currentPage === 'chat' ? 'active' : '' ?>">
                      <i class="bi bi-chat-dots side-menu__icon"></i>
                      <span class="side-menu__label">Messages</span>
                    </a>
                  </li>
                <?php endif; ?>


                <!-- Deeds Records (Institutional > Legal/ICT only) -->
                <?php if ($canDeedsMenu): ?>
                    <li class="slide">
                        <a href="<?= BASE_URL ?>deedsoffice/deedsList"
                           class="side-menu__item <?= $currentPage === 'deedsList' ? 'active' : '' ?>">
                            <i class="bi bi-file-earmark-text side-menu__icon"></i>
                            <span class="side-menu__label">Deeds Records</span>
                        </a>
                    </li>
                <?php endif; ?>


                <!-- Business Registration -->
                <?php if ($isAdmin || ($department === 'Planning')): ?>
                    <?php $open = isGroupOpen($businessPages, $currentPage); ?>
                    <li class="slide has-sub <?= $open ? 'open' : '' ?>">
                        <a href="javascript:void(0);" class="side-menu__item <?= $open ? 'active' : '' ?>">
                            <i class="bi bi-briefcase side-menu__icon"></i>
                            <span class="side-menu__label">Business Registration</span>
                        </a>
                        <ul class="slide-menu child1" style="<?= $open ? 'display:block;' : '' ?>">
                            <li><a href="<?= BASE_URL ?>permits/businessPermitsList" class="side-menu__item <?= $currentPage === 'businessPermitsList' ? 'active' : '' ?>">Business Permits</a></li>
                            <li><a href="<?= BASE_URL ?>permits/businessCertificates" class="side-menu__item <?= $currentPage === 'businessCertificates' ? 'active' : '' ?>">Certificate</a></li>
                        </ul>
                    </li>
                <?php endif; ?>

                <!-- CDF Applications -->
                <?php if ($isAdmin || ($department === 'Planning')): ?>
                    <?php $open = isGroupOpen($cdfPages, $currentPage); ?>
                    <li class="slide has-sub <?= $open ? 'open' : '' ?>">
                        <a href="javascript:void(0);" class="side-menu__item <?= $open ? 'active' : '' ?>">
                            <i class="bi bi-folder-plus side-menu__icon"></i>
                            <span class="side-menu__label">CDF Applications</span>
                        </a>
                        <ul class="slide-menu child1" style="<?= $open ? 'display:block;' : '' ?>">
                            <li><a href="<?= BASE_URL ?>cdfoffice/grantsList" class="side-menu__item <?= $currentPage === 'grantsList' ? 'active' : '' ?>">Grants</a></li>
                            <li><a href="<?= BASE_URL ?>cdfofficeloans" class="side-menu__item <?= $currentPage === 'loans' ? 'active' : '' ?>">Loans</a></li>
                            <li><a href="<?= BASE_URL ?>cdfoffice/secBursaryList" class="side-menu__item <?= in_array($currentPage, ['secBursaryList','addSecBursary'], true) ? 'active' : '' ?>">Secondary Bursaries</a></li>
                            <li><a href="<?= BASE_URL ?>cdfoffice/skillsBursaryList" class="side-menu__item <?= $currentPage === 'skillsBursaryList' ? 'active' : '' ?>">Skills Bursaries</a></li>
                            <li><a href="<?= BASE_URL ?>cdfoffice/conveyanceList" class="side-menu__item <?= $currentPage === 'conveyanceList' ? 'active' : '' ?>">Conveyance List</a></li>
                        </ul>
                    </li>
                <?php endif; ?>

                <!-- Projects -->
                <?php if ($isAdmin || ($department === 'Planning')): ?>
                    <?php $open = isGroupOpen($projectPages, $currentPage); ?>
                    <li class="slide has-sub <?= $open ? 'open' : '' ?>">
                        <a href="javascript:void(0);" class="side-menu__item <?= $open ? 'active' : '' ?>">
                            <i class="bi bi-diagram-3 side-menu__icon"></i>
                            <span class="side-menu__label">Projects</span>
                        </a>
                        <ul class="slide-menu child1" style="<?= $open ? 'display:block;' : '' ?>">
                            <li><a href="<?= BASE_URL ?>projectsList" class="side-menu__item <?= $currentPage === 'projectsList' ? 'active' : '' ?>">Projects</a></li>
                            <li><a href="<?= BASE_URL ?>tasksList" class="side-menu__item <?= $currentPage === 'tasksList' ? 'active' : '' ?>">Tasks List</a></li>
                        </ul>
                    </li>
                <?php endif; ?>

                <!-- Finance Menus -->
                <?php if ($isAdmin || $canFinanceMenu): ?>
                    <?php $open = isGroupOpen($ledgerPages, $currentPage); ?>
                    <li class="slide has-sub <?= $open ? 'open' : '' ?>">
                        <a href="javascript:void(0);" class="side-menu__item <?= $open ? 'active' : '' ?>">
                            <i class="bi bi-journal-text side-menu__icon"></i>
                            <span class="side-menu__label">Ledgers</span>
                        </a>
                        <ul class="slide-menu child1" style="<?= $open ? 'display:block;' : '' ?>">
                            <li><a href="<?= BASE_URL ?>arrearsList" class="side-menu__item <?= $currentPage === 'arrearsList' ? 'active' : '' ?>">Salary Arrears</a></li>
                        </ul>
                    </li>

                    <?php $open = isGroupOpen($posPages, $currentPage); ?>
                    <li class="slide has-sub <?= $open ? 'open' : '' ?>">
                        <a href="javascript:void(0);" class="side-menu__item <?= $open ? 'active' : '' ?>">
                            <i class="bi bi-journal-text side-menu__icon"></i>
                            <span class="side-menu__label">POS Terminal</span>
                        </a>
                        <ul class="slide-menu child1" style="<?= $open ? 'display:block;' : '' ?>">
                            <li><a href="<?= BASE_URL ?>transactionList" class="side-menu__item <?= $currentPage === 'transactionList' ? 'active' : '' ?>">Transaction List</a></li>
                        </ul>
                    </li>

                    <?php $open = isGroupOpen($voucherPages, $currentPage); ?>
                    <li class="slide has-sub <?= $open ? 'open' : '' ?>">
                        <a href="javascript:void(0);" class="side-menu__item <?= $open ? 'active' : '' ?>">
                            <i class="bi bi-journal-text side-menu__icon"></i>
                            <span class="side-menu__label">Vouchers</span>
                        </a>
                        <ul class="slide-menu child1" style="<?= $open ? 'display:block;' : '' ?>">
                            <li><a href="<?= BASE_URL ?>paymentVoucherList" class="side-menu__item <?= $currentPage === 'paymentVoucherList' ? 'active' : '' ?>">Payment Vouchers</a></li>
                        </ul>
                    </li>

                    <?php $open = isGroupOpen($banksPages, $currentPage); ?>
                    <li class="slide has-sub <?= $open ? 'open' : '' ?>">
                        <a href="javascript:void(0);" class="side-menu__item <?= $open ? 'active' : '' ?>">
                            <i class="bi bi-bank side-menu__icon"></i>
                            <span class="side-menu__label">Bank Accounts</span>
                        </a>
                        <ul class="slide-menu child1" style="<?= $open ? 'display:block;' : '' ?>">
                            <li><a href="<?= BASE_URL ?>banksDashboard" class="side-menu__item <?= $currentPage === 'banksDashboard' ? 'active' : '' ?>">Dashboard</a></li>
                            <li><a href="<?= BASE_URL ?>bankDeposit" class="side-menu__item <?= $currentPage === 'bankDeposit' ? 'active' : '' ?>">Bank Deposits</a></li>
                        </ul>
                    </li>
                <?php endif; ?>

                <!-- Valuation Roll -->
                <?php if ($isAdmin || $department === 'Planning'): ?>
                    <?php $open = isGroupOpen($valuationPages, $currentPage); ?>
                    <li class="slide has-sub <?= $open ? 'open' : '' ?>">
                        <a href="javascript:void(0);" class="side-menu__item <?= $open ? 'active' : '' ?>">
                            <i class="bi bi-building side-menu__icon"></i>
                            <span class="side-menu__label">Valuation Roll</span>
                        </a>
                        <ul class="slide-menu child1" style="<?= $open ? 'display:block;' : '' ?>">
                            <li><a href="<?= BASE_URL ?>propertyList" class="side-menu__item <?= $currentPage === 'propertyList' ? 'active' : '' ?>">Properties</a></li>
                        </ul>
                    </li>
                <?php endif; ?>

                <!-- Logout -->
                <li class="slide">
                    <a href="<?= BASE_URL ?>logout" class="side-menu__item">
                        <i class="bi bi-box-arrow-right side-menu__icon"></i>
                        <span class="side-menu__label">Logout</span>
                    </a>
                </li>

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