<?php
// includes/sidebar.php
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
require_once __DIR__ . '/auth.php';

/* PHP 7 compatibility for str_starts_with used below */
if (!function_exists('str_starts_with')) {
  function str_starts_with($haystack, $needle) {
    $haystack = (string)$haystack; $needle = (string)$needle;
    return $needle === '' || strpos($haystack, $needle) === 0;
  }
}

$A   = $ACTIVE ?? '';
$me  = ec_user();

/* figure out app base (/edenrms) from the current script */
$scriptDir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/'), '/'); // e.g. /edenrms/pages
$BASE      = preg_replace('#/pages(?:/.*)?$#', '', $scriptDir);   // -> /edenrms
if ($BASE === '') { $BASE = '/'; }

/* href builder that works on localhost and prod */
function ec_href(string $path): string {
  global $BASE;
  return $BASE . '/' . ltrim($path, '/');
}

/** Menu item helper (permission-gated) */
function ec_item(string $require, string $path, string $label, string $icon, string $slug): string {
  $ok = false;
  if ($require === '*') $ok = true;
  elseif (str_starts_with($require,'perm:')) $ok = ec_can(substr($require,5));
  elseif (str_starts_with($require,'role:')) $ok = (ec_role()===substr($require,5));
  if (!$ok) return '';

  // CORRECTED: Use local $A variable instead of $GLOBALS['A']
  $active = (($A ?? '') === $slug) ? ' active' : '';
  $href   = htmlspecialchars(ec_href($path), ENT_QUOTES, 'UTF-8');
  $label  = htmlspecialchars($label, ENT_QUOTES, 'UTF-8');
  $icon   = htmlspecialchars($icon,  ENT_QUOTES, 'UTF-8');

  return <<<HTML
    <li class="nav-item">
      <a class="nav-link{$active}" href="{$href}">
        <i class="bi {$icon} me-2"></i> {$label}
      </a>
    </li>
  HTML;
}

?>
<style>
:root{
  /* falls back if header didn't set it yet */
  --ec-topbar-h: 20px;
  --ec-sidebar-w: 260px;
}

/* ===== Overlay for mobile slide-over ===== */
#ecOverlay{
  position: fixed; inset: 0;
  background: rgba(2,6,23,.45);
  display: none; z-index: 1035;
}

/* ===== Sidebar (fixed; docks on desktop) ===== */
#ecSidebar{
  position: fixed;
  left: 0;
  top: var(--ec-topbar-h);
  height: calc(100vh - var(--ec-topbar-h));
  width: var(--ec-sidebar-w);
  background: linear-gradient(135deg, #0b1654 10%,  #e62e2e 100%);
  color: #e7efff;
  box-shadow: 2px 0 12px rgba(0,0,0,.12);
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  z-index: 1040;
  transform: translateX(-100%);
  transition: transform .25s ease;
}
.ec-sidebar .menu-title { 
  font-size:.75rem; 
  letter-spacing:.06em; 
  text-transform:uppercase; 
  color:#d6e0ff; 
  margin:.25rem .5rem .35rem; 
}
.ec-sidebar .nav-link { 
  font-size:.88rem; 
  padding:.55rem .70rem; 
  color:#e7efff; 
  border-radius:12px; 
  margin:2px 6px; 
  display:flex; 
  align-items:center; 
  gap:.55rem; 
  text-shadow: 0 0 2px rgba(0,0,0,0.3);
}
.ec-sidebar .nav-link:hover, .ec-sidebar .nav-link.active {
  background: linear-gradient(135deg, #cc2a2a 0%, #0a144a 100%) !important;
  color: #ffffff !important;
  font-weight: 600 !important;
  border-left: 3px solid #0d6efd !important;
  box-shadow: inset 4px 0 0 #0d6efd !important;
  transition: all 0.2s ease;
}



/* When mobile menu is open */
body.ec-sidebar-open #ecSidebar{ transform:none; }
body.ec-sidebar-open #ecOverlay{ display:block; }

/* ===== Desktop: docked and content pushed ===== */
@media (min-width: 992px){
  #ecSidebar{ transform:none; }                       /* always visible unless collapsed */
  .ec-main{ margin-left: var(--ec-sidebar-w); }       /* push content */
  body.ec-sidebar-collapsed #ecSidebar{ transform:translateX(-100%); }
  body.ec-sidebar-collapsed .ec-main{ margin-left:0; }
}

/* avatar tweak */
#ecSidebar .avatar { width:28px; height:28px; border-radius:50%; object-fit:cover; }
</style>
<style>
  /* === Ultra-compact topbar (32px) === */
  :root { --ec-topbar-h: 20px; }

  .ec-topbar .container-fluid{
    min-height: var(--ec-topbar-h) !important;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
    padding-left: .50rem !important;
    padding-right: .50rem !important;
  }

  .ec-topbar .navbar-brand{
    font-size: .90rem !important;
    line-height: 2 !important;
    padding: 0 !important;
    margin: 0 !important;
    display: flex; align-items: center;
    height: var(--ec-topbar-h) !important;
    padding-right: .90rem !important;
  }

  .ec-topbar .btn{
    padding: .07rem .32rem !important;
    font-size: .74rem !important;
    border-radius: .30rem !important;
    line-height: 1 !important;
  }

  /* avatar inside the user dropdown button */
  .ec-avatar{ width: 18px !important; height: 18px !important; }

  /* keep sidebar & notifications panel perfectly aligned with the new height */
  .ec-sidebar{ top: var(--ec-topbar-h) !important; height: calc(100vh - var(--ec-topbar-h)) !important; }
  .ec-notify-panel{ top: var(--ec-topbar-h) !important; height: calc(100vh - var(--ec-topbar-h)) !important; }
</style>


<div id="ecOverlay"></div>

<aside class="ec-sidebar small" id="ecSidebar">
  <div class="p-3">
    <div class="menu-title">Menu</div>
    <ul class="nav flex-column gap-1">

      <?= ec_item('*',                      'pages/dashboard.php',            'Dashboard',            'bi-speedometer2',        'dashboard'); ?>
      <?= ec_item('perm:students.manage',   'pages/students.php',             'Students',             'bi-people',              'students'); ?>
      <?= ec_item('perm:students.manage',   'pages/new_registration.php',     'New Registration',     'bi-person-plus',         'registrations'); ?>
      <?= ec_item('perm:courses.manage',    'pages/courses.php',              'Courses',              'bi-journal-text',        'courses'); ?>

      <?= ec_item('perm:batches.view',      'pages/batches.php',              'Batches',              'bi-diagram-3',           'batches'); ?>
      <?= ec_item('perm:payments.manage',   'pages/payment_manager.php',      'Payment Manager',      'bi-cash-coin',           'payments'); ?>
      <?= ec_item('perm:marks.verify',      'pages/marks_validation.php',     'Marks Validation',     'bi-clipboard-check',     'marks_validation'); ?>

      <li class="mt-2 menu-title">Finance & Reports</li>
      <?= ec_item('perm:reports.view',      'pages/dues.php?tab=pending&view=lines',  'Pending Dues',   'bi-journal-x',           'dues'); ?>
      <?= ec_item('perm:reports.view',      'pages/montly_due.php',                      'Monthly Due',  'bi-calendar2-x',         'montly_due'); ?>

      <?= ec_item('perm:targets.manage',    'pages/targets.php',              'Revenue Targets',      'bi-bullseye',            'targets'); ?>
      <?= ec_item('perm:branches.manage',   'pages/branches.php',             'Branches',             'bi-diagram-3',           'branches'); ?>
      <?= ec_item('perm:reports.view',      'pages/approvals.php',            'Approvals',            'bi-check2-circle',       'approvals'); ?>

      <?php if (ec_can('users.manage') || ec_can('roles.manage') || ec_can('settings.manage')): ?>
        <li class="mt-2 menu-title">Administration</li>
        <?= ec_item('perm:users.manage',    'pages/users.php',                'Users',                'bi-person-badge',        'users'); ?>
        <?= ec_item('perm:roles.manage',    'pages/roles.php',                'Roles & Permissions',  'bi-shield-lock',         'roles'); ?>
        <?= ec_item('perm:roles.manage',    'pages/feature_toggles.php',      'Feature Toggles',      'bi-toggle2-on',          'feature_toggles'); ?>
        <?= ec_item('perm:settings.manage', 'pages/settings.php',             'System Settings',      'bi-gear',                'settings'); ?>
        <?= ec_item('perm:settings.manage', 'pages/settings_sms.php',         'SMS Settings',         'bi-chat-dots',           'sms'); ?>
      <?php endif; ?>

    </ul>

    <hr class="text-white-50 my-3">
    <div class="small d-flex align-items-center gap-2 text-white-50">
      <?php
        $avatar = $me['avatar_url'] ?? '';
        if ($avatar === '' || $avatar === '0') $avatar = ec_href('assets/img/avatar-default.jpg');
        $name   = htmlspecialchars($me['name'] ?? 'User', ENT_QUOTES, 'UTF-8');
      ?>
      <img src="<?= htmlspecialchars($avatar, ENT_QUOTES, 'UTF-8') ?>" class="avatar"
           alt="" onerror="this.onerror=null;this.src='<?= ec_href('assets/img/avatar-default.jpg') ?>'">
      <div><div class="text-white"><?= $name ?></div></div>
    </div>
  </div>
</aside>

<script>
/* Sidebar toggle + remember state + correct top offset */
(function(){
  // ensure top offset equals actual topbar height
  var topbar = document.querySelector('.ec-topbar');
  if (topbar) {
    var h = topbar.offsetHeight || 56;
    document.documentElement.style.setProperty('--ec-topbar-h', h + 'px');
  }

  var toggleBtn = document.getElementById('ecSidebarToggle'); // from header.php
  var overlay   = document.getElementById('ecOverlay');

  function openMobile(){ document.body.classList.add('ec-sidebar-open'); }
  function closeMobile(){ document.body.classList.remove('ec-sidebar-open'); }

  function toggle(){
    if (window.matchMedia('(min-width: 992px)').matches){
      var collapsed = document.body.classList.toggle('ec-sidebar-collapsed');
      try { localStorage.setItem('ecSidebarCollapsed', collapsed ? '1' : '0'); } catch(e){}
    } else {
      if (document.body.classList.contains('ec-sidebar-open')) closeMobile(); else openMobile();
    }
  }

  if (toggleBtn) toggleBtn.addEventListener('click', function(e){ e.preventDefault(); toggle(); });
  if (overlay) overlay.addEventListener('click', closeMobile);
  document.addEventListener('keyup', function(e){ if (e.key === 'Escape') closeMobile(); });

  // restore collapsed state on desktop
  try {
    if (localStorage.getItem('ecSidebarCollapsed') === '1' &&
        window.matchMedia('(min-width: 992px)').matches){
      document.body.classList.add('ec-sidebar-collapsed');
    }
  } catch(e){}
})();
</script>
