<?php require_once __DIR__ . '/../config.php'; require_once __DIR__ . '/../includes/auth.php'; ?>
<nav id="sidebar" class="d-flex flex-column flex-shrink-0 p-3 bg-light border-end" style="width: 260px; min-height: 100vh;">
  
  
  <?php 
    $current = $_GET['page'] ?? 'dashboard'; 
    $productPages = ['ship_modes','delivery_terms','payment_terms','materials','types','colors','finishes']; 
    $productOpen = in_array($current, $productPages, true); 
    $finalPages = ['polishing','finished_products','slab_cutting','cutting_inventory'];
    $finalOpen = in_array($current, $finalPages, true);
    $invoicingPages = ['customers','sales'];
    $invoicingOpen = in_array($current, $invoicingPages, true);
    $poSettingsPages = ['shop_settings','services','users','branches','store_locations','company_licenses']; 
    $poSettingsOpen = in_array($current, $poSettingsPages, true); 
    $purchaseMgmtPages = ['suppliers','purchase_orders','import_raw_materials'];
    $purchaseMgmtOpen = in_array($current, $purchaseMgmtPages, true);
    $financePages = ['finance_dashboard','finance_realtime_dashboard','finance_manager_dashboard','bank_reconciliation','petty_cash','cash_book_entry','transaction_history','bank_accounts','expenditures','expenditure_to_cashbook','journal_entries'];
    $financeOpen = in_array($current, $financePages, true);
    $adminPages = ['payroll','salary_management','attendance','payroll_loans','payroll_deductions','payroll_settings'];
    $adminOpen = in_array($current, $adminPages, true);
    $payrollPages = ['payroll','salary_management','attendance','payroll_loans','payroll_deductions','payroll_settings','employees'];
    $payrollOpen = in_array($current, $payrollPages, true);
  ?>
  <!-- Branch selector / current branch -->
  <div class="mb-3">
    <?php $curBranchName = $_SESSION['branch_name'] ?? null; $curBranchId = $_SESSION['branch_id'] ?? null; ?>
    <?php if (has_role(['admin','super_admin'])): ?>
      <label class="form-label small text-muted">Active Branch</label>
      <div class="input-group input-group-sm">
        <select id="sbBranchSelect" class="form-select">
          <?php if ($curBranchId): ?><option value="<?php echo (int)$curBranchId; ?>" selected><?php echo htmlspecialchars($curBranchName ?? ('Branch #'.(int)$curBranchId)); ?></option><?php endif; ?>
        </select>
        <button class="btn btn-outline-secondary" id="sbBranchRefresh" title="Refresh"><i class="bi bi-arrow-repeat"></i></button>
      </div>
      <input type="hidden" id="sb_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>" />
      <div class="form-text">Switch to manage a different branch.</div>
    <?php else: ?>
      <div class="small text-muted">Current Branch</div>
      <div>
        <span class="badge bg-primary"><?php echo htmlspecialchars($curBranchName ?? 'Not Selected'); ?></span>
      </div>
    <?php endif; ?>
  </div>

  <ul class="nav nav-pills flex-column mb-auto">
    <li class="nav-item"><a class="nav-link" href="<?php echo url_for('index.php?page=dashboard'); ?>"><i class="bi bi-speedometer2 me-2"></i>Dashboard</a></li>
    

    <?php if (!has_role('sales_user')): ?>
    <li class="mt-2">
      <a class="nav-link d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#purchaseMenu" role="button" aria-expanded="<?php echo $purchaseMgmtOpen ? 'true' : 'false'; ?>" aria-controls="purchaseMenu">
        <span><i class="bi bi-truck me-2"></i>PO Management</span>
        <span class="bi bi-chevron-down"></span>
      </a>
      <div class="collapse <?php echo $purchaseMgmtOpen ? 'show' : ''; ?>" id="purchaseMenu">
        <ul class="btn-toggle-nav list-unstyled fw-normal small ps-3">
          <li><a class="nav-link <?php echo $current==='suppliers'?'active':''; ?>" href="<?php echo url_for('index.php?page=suppliers'); ?>"><i class="bi bi-people me-2"></i>Suppliers</a></li>
          <li><a class="nav-link <?php echo $current==='purchase_orders'?'active':''; ?>" href="<?php echo url_for('index.php?page=purchase_orders'); ?>"><i class="bi bi-receipt me-2"></i>Purchase Orders</a></li>
          <li><a class="nav-link <?php echo $current==='import_raw_materials'?'active':''; ?>" href="<?php echo url_for('index.php?page=import_raw_materials'); ?>"><i class="bi bi-box-seam me-2"></i>Import Raw Materials</a></li>
      </ul>
  <?php if (has_role(['admin','super_admin'])): ?>
  <script>
  (function(){
    const $sel = $('#sbBranchSelect'); const $csrf=$('#sb_csrf');
    function loadBranches(){
      $.get('api/branches.php',{ action:'list' }, function(res){
        if(!$sel.length) return; const cur=$sel.val(); $sel.empty();
        (res.data||[]).forEach(b=>{ if(parseInt(b.is_active)) $sel.append(`<option value="${b.id}">${$('<div>').text(b.name||'').html()}</option>`); });
        if (cur) $sel.val(cur);
      });
    }
    $('#sbBranchRefresh').on('click', function(){ loadBranches(); });
    $sel.on('change', function(){ const id=$(this).val(); if(!id) return; const fd=new FormData(); fd.append('csrf',$csrf.val()); fd.append('action','set_current'); fd.append('id', id);
      $.ajax({ url:'api/branches.php', method:'POST', data:fd, processData:false, contentType:false })
        .done(function(){ location.reload(); })
        .fail(function(xhr){ alert((xhr.responseJSON&&xhr.responseJSON.message)||'Failed to switch branch'); });
    });
    // initial populate
    loadBranches();
  })();
  </script>
  <?php endif; ?>
      </div>
    </li> 
    <?php endif; ?>

    <li class="mt-2">
      <a class="nav-link d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#finalMenu" role="button" aria-expanded="<?php echo $finalOpen ? 'true' : 'false'; ?>" aria-controls="finalMenu">
        <span><i class="bi bi-box2-heart me-2"></i>Production</span>
        <span class="bi bi-chevron-down"></span>
      </a>
      <div class="collapse <?php echo $finalOpen ? 'show' : ''; ?>" id="finalMenu">
        <ul class="btn-toggle-nav list-unstyled fw-normal small ps-3">
          <?php if (!has_role('sales_user')): ?>
            <li><a class="nav-link <?php echo $current==='polishing'?'active':''; ?>" href="<?php echo url_for('index.php?page=polishing'); ?>"><i class="bi bi-tools me-2"></i>Polishing</a></li>
            <li><a class="nav-link <?php echo $current==='slab_cutting'?'active':''; ?>" href="<?php echo url_for('index.php?page=slab_cutting'); ?>"><i class="bi bi-scissors me-2"></i>Slab Cutting</a></li>
          <?php endif; ?>
          <li><a class="nav-link <?php echo $current==='finished_products'?'active':''; ?>" href="<?php echo url_for('index.php?page=finished_products'); ?>"><i class="bi bi-box2 me-2"></i>Finished Products Inventory</a></li>
          <li><a class="nav-link <?php echo $current==='cutting_inventory'?'active':''; ?>" href="<?php echo url_for('index.php?page=cutting_inventory'); ?>"><i class="bi bi-grid-3x3-gap me-2"></i>Cutting Inventory</a></li>
          <li><a class="nav-link <?php echo $current==='production'?'active':''; ?>" href="<?php echo url_for('index.php?page=production'); ?>"><i class="bi bi-boxes me-2"></i>Production Inventory</a></li>
        </ul>
      </div>
    </li>

    <li class="mt-2">
      <a class="nav-link d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#invoicingMenu" role="button" aria-expanded="<?php echo $invoicingOpen ? 'true' : 'false'; ?>" aria-controls="invoicingMenu">
        <span><i class="bi bi-receipt me-2"></i>Invoicing</span>
        <span class="bi bi-chevron-down"></span>
      </a>
      <div class="collapse <?php echo $invoicingOpen ? 'show' : ''; ?>" id="invoicingMenu">
        <ul class="btn-toggle-nav list-unstyled fw-normal small ps-3">
          <li><a class="nav-link <?php echo $current==='customers'?'active':''; ?>" href="<?php echo url_for('index.php?page=customers'); ?>"><i class="bi bi-person-lines-fill me-2"></i>Customers</a></li>
          <li><a class="nav-link <?php echo $current==='sales'?'active':''; ?>" href="<?php echo url_for('index.php?page=sales'); ?>"><i class="bi bi-cart3 me-2"></i>Sales</a></li>
        </ul>
      </div>
    </li>

    <li class="mt-2">
      <a class="nav-link d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#analyticsMenu" role="button" aria-expanded="<?php echo ($current==='reports' || $current==='stock_summary_report' || $current==='competitor_analysis' || $current==='production_report') ? 'true' : 'false'; ?>" aria-controls="analyticsMenu">
        <span><i class="bi bi-graph-up me-2"></i>Analytics</span>
        <span class="bi bi-chevron-down"></span>
      </a>
      <div class="collapse <?php echo ($current==='reports' || $current==='stock_summary_report' || $current==='competitor_analysis' || $current==='production_report') ? 'show' : ''; ?>" id="analyticsMenu">
        <ul class="btn-toggle-nav list-unstyled fw-normal small ps-3">
          <li><a class="nav-link <?php echo $current==='reports'?'active':''; ?>" href="<?php echo url_for('index.php?page=reports'); ?>"><i class="bi bi-bar-chart-line me-2"></i>Sales Reports</a></li>
          <li><a class="nav-link <?php echo $current==='stock_summary_report'?'active':''; ?>" href="<?php echo url_for('index.php?page=stock_summary_report'); ?>"><i class="bi bi-box-seam me-2"></i>Stock Summary Report</a></li>
          <li><a class="nav-link <?php echo $current==='production_report'?'active':''; ?>" href="<?php echo url_for('index.php?page=production_report'); ?>"><i class="bi bi-tools me-2"></i>Production Report</a></li>
          <li><a class="nav-link <?php echo $current==='competitor_analysis'?'active':''; ?>" href="<?php echo url_for('index.php?page=competitor_analysis'); ?>"><i class="bi bi-people me-2"></i>Competitor Analysis</a></li>
        </ul>
      </div>
    </li>

    <?php if (!has_role('sales_user')): ?>
    <li class="mt-2">
      <a class="nav-link d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#financeMenu" role="button" aria-expanded="<?php echo $financeOpen ? 'true' : 'false'; ?>" aria-controls="financeMenu">
        <span><i class="bi bi-cash-coin me-2"></i>Finance</span>
        <span class="bi bi-chevron-down"></span>
      </a>
      <div class="collapse <?php echo $financeOpen ? 'show' : ''; ?>" id="financeMenu">
        <ul class="btn-toggle-nav list-unstyled fw-normal small ps-3">
          <li><a class="nav-link <?php echo $current==='finance_dashboard'?'active':''; ?>" href="<?php echo url_for('index.php?page=finance_dashboard'); ?>"><i class="bi bi-speedometer2 me-2"></i>Finance Dashboard</a></li>
          <li><a class="nav-link <?php echo $current==='finance_realtime_dashboard'?'active':''; ?>" href="<?php echo url_for('index.php?page=finance_realtime_dashboard'); ?>"><i class="bi bi-graph-up-arrow me-2"></i>Real-Time Dashboard</a></li>
          <?php if (has_role(['admin','super_admin','finance_manager'])): ?>
          <li><a class="nav-link <?php echo $current==='finance_manager_dashboard'?'active':''; ?>" href="<?php echo url_for('index.php?page=finance_manager_dashboard'); ?>"><i class="bi bi-shield-check me-2"></i>Manager Dashboard</a></li>
          <?php endif; ?>
          <?php if (has_role(['admin','super_admin','accountant','finance_manager'])): ?>
          <li><a class="nav-link <?php echo $current==='bank_reconciliation'?'active':''; ?>" href="<?php echo url_for('index.php?page=bank_reconciliation'); ?>"><i class="bi bi-bank me-2"></i>Bank Reconciliation</a></li>
          <?php endif; ?>
          <li><a class="nav-link <?php echo $current==='petty_cash'?'active':''; ?>" href="<?php echo url_for('index.php?page=petty_cash'); ?>"><i class="bi bi-wallet me-2"></i>Petty Cash</a></li>
          <li><a class="nav-link <?php echo $current==='cash_book_entry'?'active':''; ?>" href="<?php echo url_for('index.php?page=cash_book_entry'); ?>"><i class="bi bi-cash me-2"></i>Cash Book Entry</a></li>
          <li><a class="nav-link <?php echo $current==='transaction_history'?'active':''; ?>" href="<?php echo url_for('index.php?page=transaction_history'); ?>"><i class="bi bi-journal-text me-2"></i>Cash Book History</a></li>
           <li><a class="nav-link <?php echo $current==='journal_entries'?'active':''; ?>" href="<?php echo url_for('index.php?page=journal_entries'); ?>"><i class="bi bi-journal-bookmark-fill me-2"></i>Journal Entries</a></li>
          <li><a class="nav-link <?php echo $current==='bank_accounts'?'active':''; ?>" href="<?php echo url_for('index.php?page=bank_accounts'); ?>"><i class="bi bi-bank me-2"></i>Bank Accounts</a></li>
          <li><a class="nav-link <?php echo $current==='expenditures'?'active':''; ?>" href="<?php echo url_for('index.php?page=expenditures'); ?>"><i class="bi bi-cash-stack me-2"></i>Expenditures</a></li>
          <li><a class="nav-link <?php echo $current==='expenditure_to_cashbook'?'active':''; ?>" href="<?php echo url_for('index.php?page=expenditure_to_cashbook'); ?>"><i class="bi bi-arrow-left-right me-2"></i>Exp &rarr; Cash Book</a></li>
         
      </ul>
      </div>
    </li>
    <?php endif; ?>

    <?php if (!has_role('sales_user')): ?>
    <li class="mt-2">
      <a class="nav-link d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#payrollMenu" role="button" aria-expanded="<?php echo $payrollOpen ? 'true' : 'false'; ?>" aria-controls="payrollMenu">
        <span><i class="bi bi-wallet2 me-2"></i>Payroll</span>
        <span class="bi bi-chevron-down"></span>
      </a>
      <div class="collapse <?php echo $payrollOpen ? 'show' : ''; ?>" id="payrollMenu">
        <ul class="btn-toggle-nav list-unstyled fw-normal small ps-3">
          <li><a class="nav-link <?php echo $current==='payroll'?'active':''; ?>" href="<?php echo url_for('index.php?page=payroll'); ?>"><i class="bi bi-calculator me-2"></i>Process Payroll</a></li>
          <li><a class="nav-link <?php echo $current==='employees'?'active':''; ?>" href="<?php echo url_for('index.php?page=employees'); ?>"><i class="bi bi-people me-2"></i>Employees</a></li>
          <li><a class="nav-link <?php echo $current==='attendance'?'active':''; ?>" href="<?php echo url_for('index.php?page=attendance'); ?>"><i class="bi bi-calendar-check me-2"></i>Attendance</a></li>
          <li class="mt-2"><hr class="dropdown-divider my-1"></li>
          <li class="small text-muted ps-2">Payroll Settings</li>
          <li><a class="nav-link <?php echo $current==='payroll_loans'?'active':''; ?>" href="<?php echo url_for('index.php?page=payroll&tab=loans'); ?>"><i class="bi bi-bank me-2"></i>Staff Loans</a></li>
          <li><a class="nav-link <?php echo $current==='payroll_deductions'?'active':''; ?>" href="<?php echo url_for('index.php?page=payroll&tab=deductions'); ?>"><i class="bi bi-dash-circle me-2"></i>Deductions</a></li>
          <li><a class="nav-link <?php echo $current==='payroll_settings'?'active':''; ?>" href="<?php echo url_for('index.php?page=payroll&tab=settings'); ?>"><i class="bi bi-gear me-2"></i>OT & Tax Settings</a></li>
          <li><a class="nav-link <?php echo $current==='salary_management'?'active':''; ?>" href="<?php echo url_for('index.php?page=salary_management'); ?>"><i class="bi bi-clock-history me-2"></i>Salary (Old)</a></li>
        </ul>
      </div>
    </li>
    <?php endif; ?>

    <?php if (!has_role('sales_user')): ?>
    <li class="mt-2">
      <a class="nav-link d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#adminMenu" role="button" aria-expanded="<?php echo $adminOpen ? 'true' : 'false'; ?>" aria-controls="adminMenu">
        <span><i class="bi bi-gear me-2"></i>Administration</span>
        <span class="bi bi-chevron-down"></span>
      </a>
      <div class="collapse <?php echo $adminOpen ? 'show' : ''; ?>" id="adminMenu">
        <ul class="btn-toggle-nav list-unstyled fw-normal small ps-3">
          <li><a class="nav-link <?php echo $current==='users'?'active':''; ?>" href="<?php echo url_for('index.php?page=users'); ?>"><i class="bi bi-people me-2"></i>System Users</a></li>
          <li><a class="nav-link <?php echo $current==='designations'?'active':''; ?>" href="<?php echo url_for('index.php?page=designations'); ?>"><i class="bi bi-person-badge me-2"></i>Designations</a></li>
      </ul>
      </div>
    </li>
    <?php endif; ?>

    <!-- Product settings (catalog) -->
    <?php if (!has_role('sales_user')): ?>
    <li class="mt-2">
      <a class="nav-link d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#productMenu" role="button" aria-expanded="<?php echo $productOpen ? 'true' : 'false'; ?>" aria-controls="productMenu">
        <span><i class="bi bi-boxes me-2"></i>Products Setting</span>
        <span class="bi bi-chevron-down"></span>
      </a>
      <div class="collapse <?php echo $productOpen ? 'show' : ''; ?>" id="productMenu">
        <ul class="btn-toggle-nav list-unstyled fw-normal small ps-3">
          <li><a class="nav-link <?php echo $current==='materials'?'active':''; ?>" href="<?php echo url_for('index.php?page=materials'); ?>"><i class="bi bi-box me-2"></i>Materials</a></li>
          <li><a class="nav-link <?php echo $current==='types'?'active':''; ?>" href="<?php echo url_for('index.php?page=types'); ?>"><i class="bi bi-tags me-2"></i>Raw Material Types</a></li>
          <li><a class="nav-link <?php echo $current==='colors'?'active':''; ?>" href="<?php echo url_for('index.php?page=colors'); ?>"><i class="bi bi-palette me-2"></i>Colors</a></li>
          <li><a class="nav-link <?php echo $current==='finishes'?'active':''; ?>" href="<?php echo url_for('index.php?page=finishes'); ?>"><i class="bi bi-brush me-2"></i>Finishes</a></li>
                    <li><a class="nav-link <?php echo $current==='ship_modes'?'active':''; ?>" href="<?php echo url_for('index.php?page=ship_modes'); ?>"><i class="bi bi-truck me-2"></i>Ship Modes</a></li>
          <li><a class="nav-link <?php echo $current==='delivery_terms'?'active':''; ?>" href="<?php echo url_for('index.php?page=delivery_terms'); ?>"><i class="bi bi-truck-front me-2"></i>Delivery Terms</a></li>
          <li><a class="nav-link <?php echo $current==='payment_terms'?'active':''; ?>" href="<?php echo url_for('index.php?page=payment_terms'); ?>"><i class="bi bi-credit-card me-2"></i>Payment Terms</a></li>
        </ul>
      </div>
    </li>
    <?php endif; ?>

    <!-- Settings -->
    <?php if (!has_role('sales_user')): ?>
    <li class="mt-2">
      <a class="nav-link d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#poSettingsMenu" role="button" aria-expanded="<?php echo $poSettingsOpen ? 'true' : 'false'; ?>" aria-controls="poSettingsMenu">
        <span><i class="bi bi-gear me-2"></i>Settings</span>
        <span class="bi bi-chevron-down"></span>
      </a>
      <div class="collapse <?php echo $poSettingsOpen ? 'show' : ''; ?>" id="poSettingsMenu">
        <ul class="btn-toggle-nav list-unstyled fw-normal small ps-3">
          <li><a class="nav-link <?php echo $current==='users'?'active':''; ?>" href="<?php echo url_for('index.php?page=users'); ?>"><i class="bi bi-people me-2"></i>System Users</a></li>
          <li><a class="nav-link <?php echo $current==='designations'?'active':''; ?>" href="<?php echo url_for('index.php?page=designations'); ?>"><i class="bi bi-person-badge me-2"></i>Employee Designations</a></li>

          <li><a class="nav-link <?php echo $current==='shop_settings'?'active':''; ?>" href="<?php echo url_for('index.php?page=shop_settings'); ?>"><i class="bi bi-shop me-2"></i>Shop Settings</a></li>
          <li><a class="nav-link <?php echo $current==='services'?'active':''; ?>" href="<?php echo url_for('index.php?page=services'); ?>"><i class="bi bi-wrench-adjustable me-2"></i>Services</a></li>
          <li><a class="nav-link <?php echo $current==='company_licenses'?'active':''; ?>" href="<?php echo url_for('index.php?page=company_licenses'); ?>"><i class="bi bi-file-earmark-text me-2"></i>Company Licenses</a></li>
          <li><a class="nav-link <?php echo $current==='branches'?'active':''; ?>" href="<?php echo url_for('index.php?page=branches'); ?>"><i class="bi bi-building me-2"></i>Branches</a></li>
          <li><a class="nav-link <?php echo $current==='store_locations'?'active':''; ?>" href="<?php echo url_for('index.php?page=store_locations'); ?>"><i class="bi bi-geo-alt me-2"></i>Store Locations</a></li>
          <li><a class="nav-link <?php echo $current==='backups'?'active':''; ?>" href="<?php echo url_for('index.php?page=backups'); ?>"><i class="bi bi-hdd-network me-2"></i>Backups</a></li>
        </ul>
      </div>
    </li>
    <?php endif; ?>
  </ul>
  <!-- <hr>
  <div class="dropdown">
{{ ... }}
      <img src="https://ui-avatars.com/api/?name=<?php echo urlencode(current_user()['full_name'] ?? current_user()['username'] ?? 'U'); ?>&background=0D6EFD&color=fff" alt="" width="32" height="32" class="rounded-circle me-2">
      <strong><?php echo htmlspecialchars(current_user()['full_name'] ?? current_user()['username'] ?? ''); ?></strong>
    </a>
    <ul class="dropdown-menu text-small shadow">
      <li class="dropdown-item">Role: <?php echo htmlspecialchars(current_user()['role'] ?? ''); ?></li>
      <li><hr class="dropdown-divider"></li>
      <li><a class="dropdown-item" href="<?php echo url_for('logout.php'); ?>">Sign out</a></li>
    </ul>
  </div> -->
</nav>
