<?php 
$currentPage = basename($_SERVER['PHP_SELF']);
$isSuper = isSuperAdmin();
$branchId = $_SESSION['branch_id'] ?? 0;

$menusSuperAdmin = [
    ['section' => 'MAIN'],
    ['url'=>'/admin/index.php',              'icon'=>'speedometer2',       'label'=>'Dashboard'],
    ['url'=>'/admin/customers.php',          'icon'=>'people',             'label'=>'Pelanggan'],
    ['url'=>'/admin/bills.php',              'icon'=>'receipt',            'label'=>'Tagihan'],
    ['url'=>'/admin/packages.php',           'icon'=>'box',                'label'=>'Paket Internet'],
    
    ['section' => 'PAYMENT'],
    ['url'=>'/admin/payment_settings.php',   'icon'=>'credit-card-2-front','label'=>'Payment Gateway'],
    ['url'=>'/admin/bank_verification.php',  'icon'=>'bank',               'label'=>'Verifikasi Rekening Bank'],
    ['url'=>'/admin/withdrawals.php',        'icon'=>'cash-stack',         'label'=>'Approval Penarikan'],
    ['url'=>'/admin/branch_finance.php',     'icon'=>'cash-stack',         'label'=>'Keuangan Cabang'],
    
    ['section' => 'MANAGEMENT'],
    ['url'=>'/admin/branches.php',           'icon'=>'building',           'label'=>'Cabang'],
    ['url'=>'/admin/users.php',              'icon'=>'person-gear',        'label'=>'User Management'],
    
    ['section' => 'COMMUNICATION'],
    ['url'=>'/admin/broadcast.php',          'icon'=>'megaphone',          'label'=>'Broadcast WA'],
    ['url'=>'/admin/whatsapp_settings.php',  'icon'=>'whatsapp',           'label'=>'WhatsApp Gateway'],
    
    ['section' => 'INFRASTRUCTURE'],
    ['url'=>'/admin/mikrotik_status.php',    'icon'=>'router',             'label'=>'MikroTik Status'],
    ['url'=>'/admin/mikrotik_settings.php',  'icon'=>'gear-wide-connected','label'=>'MikroTik Settings'],
    
    ['section' => 'SYSTEM'],
    ['url'=>'/admin/logs.php',               'icon'=>'journal-text',       'label'=>'Log Aktivitas'],
    ['url'=>'/admin/settings.php',           'icon'=>'sliders',            'label'=>'Pengaturan'],
];

$menusBranch = [
    ['section' => 'MAIN'],
    ['url'=>'/branch/index.php',           'icon'=>'speedometer2',       'label'=>'Dashboard'],
    ['url'=>'/branch/customers.php',       'icon'=>'people',             'label'=>'Pelanggan'],
    ['url'=>'/branch/bills.php',           'icon'=>'receipt',            'label'=>'Tagihan'],
    ['url'=>'/branch/packages.php',        'icon'=>'box',                'label'=>'Paket Internet'],
    
    ['section' => 'FINANCE'],
    ['url'=>'/branch/finance.php',         'icon'=>'cash-stack',         'label'=>'Finance'],
    
    ['section' => 'COMMUNICATION'],
    ['url'=>'/branch/broadcast.php',       'icon'=>'megaphone',          'label'=>'Broadcast WA'],
    ['url'=>'/branch/templates.php',       'icon'=>'receipt',          'label'=>'Templates'],
    ['url'=>'/branch/broadcast_logs.php',  'icon'=>'clock-history',      'label'=>'Broadcast Logs'],
    ['url'=>'/branch/whatsapp_settings.php','icon'=>'whatsapp',          'label'=>'WhatsApp Gateway'],
    
    ['section' => 'INFRASTRUCTURE'],
    ['url'=>'/branch/mikrotik_status.php', 'icon'=>'router',             'label'=>'MikroTik Status'],
    ['url'=>'/branch/mikrotik_settings.php','icon'=>'gear-wide-connected','label'=>'MikroTik Settings'],
    ['url'=>'/branch/cron_manager.php',              'icon'=>'person-gear',        'label'=>'cron Management'],
];

$menus = $isSuper ? $menusSuperAdmin : $menusBranch;

$logoPath = '/assets/img/rocky.png'; 
$branchName = $_SESSION['branch_name'] ?? $_SESSION['branch_code'] ?? 'Nama Cabang';
$logoSize = 'auto';
$showLogo = !empty($logoPath) && file_exists(__DIR__ . '/..' . $logoPath);
?>

<div class="sidebar" id="sidebar">
  <div class="sidebar-header">
    <div class="sidebar-brand">
      <div class="sidebar-brand-logo">
        <?php if ($showLogo): ?>
          <img src="<?= htmlspecialchars($logoPath) ?>" alt="Logo" class="sidebar-logo-img">
        <?php else: ?>
          <h5 class="sidebar-brand-fallback"><?= htmlspecialchars($branchName) ?></h5>
        <?php endif; ?>
      </div>
    </div>
    <button class="sidebar-close" onclick="toggleSidebar()">
      <i class="bi bi-x-lg"></i>
    </button>
  </div>
  
  <nav class="sidebar-nav">
    <?php foreach ($menus as $m): ?>
      <?php if (isset($m['section'])): ?>
        <div class="sidebar-section-title"><?= $m['section'] ?></div>
      <?php else: ?>
        <a class="nav-link <?= $currentPage === basename($m['url']) ? 'active' : '' ?>" href="<?= $m['url'] ?>">
          <i class="bi bi-<?= $m['icon'] ?>"></i>
          <span><?= $m['label'] ?></span>
        </a>
      <?php endif; ?>
    <?php endforeach; ?>
  </nav>
  
  <div class="sidebar-footer">
    <div class="user-info">
      <div class="user-avatar">
        <?= strtoupper(substr($_SESSION['username'] ?? 'U', 0, 1)) ?>
      </div>
      <div class="user-details">
        <div class="user-name"><?= htmlspecialchars($_SESSION['username'] ?? 'User') ?></div>
        <div class="user-role"><?= $isSuper ? 'Super Admin' : 'Branch Staff' ?></div>
      </div>
    </div>
    <a href="/logout.php" class="btn-logout" onclick="return confirm('Yakin ingin logout?')">
      <i class="bi bi-box-arrow-right"></i>
      <span>Logout</span>
    </a>
  </div>
</div>

<!-- CSS Khusus Logo -->
<style>
.sidebar-brand-logo {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    padding: 10px 0;
}

.sidebar-logo-img {
    width: auto;
    height: auto;
    max-width: 100%;
    object-fit: contain;
    <?php if ($logoSize === 'small'): ?>
        max-height: 35px;
    <?php elseif ($logoSize === 'medium'): ?>
        max-height: 50px;
    <?php elseif ($logoSize === 'large'): ?>
        max-height: 70px;
    <?php elseif ($logoSize === 'auto'): ?>
        max-height: none;
        width: 80%;
    <?php elseif (preg_match('/^\d+px$/', $logoSize)): ?>
        max-height: <?= $logoSize ?>;
    <?php else: ?>
        max-height: 50px;
    <?php endif; ?>
}

.sidebar-brand-fallback {
    margin: 0;
    font-size: 1.2rem;
    font-weight: 700;
    color: #fff;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    padding: 0 10px;
}

.sidebar-header {
    min-height: 80px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px;
}
</style>

<!-- JavaScript Toggle Sidebar -->
<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    const body = document.body;
    
    if (!sidebar) return;
    
    const isMobile = window.innerWidth <= 768;
    
    if (isMobile) {
        sidebar.classList.toggle('active');
        if (overlay) overlay.classList.toggle('active');
        body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    } else {
        body.classList.toggle('sidebar-hidden');
    }
}

window.addEventListener('resize', function() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    const body = document.body;
    
    if (window.innerWidth > 768) {
        sidebar.classList.remove('active');
        if (overlay) overlay.classList.remove('active');
        body.style.overflow = '';
    } else {
        body.classList.remove('sidebar-hidden');
    }
});

document.addEventListener('click', function(e) {
    if (window.innerWidth <= 768 && e.target.closest('.sidebar-nav .nav-link')) {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebarOverlay');
        sidebar.classList.remove('active');
        if (overlay) overlay.classList.remove('active');
        document.body.style.overflow = '';
    }
});
</script>