<?php
/**
 * SisPen Snesaka - Header Template
 */
if (!isset($pageTitle)) $pageTitle = 'Dashboard';
if (!isset($activeMenu)) $activeMenu = '';
$isAdmin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
$pengaturan = getPengaturan();
$B = BASE_URL; // shorthand

// Cek apakah guru ini adalah pembina ekskul (untuk kontrol menu)
$_isPembina = false;
if (!$isAdmin && !empty($_SESSION['guru_id'])) {
    $_eksBina = db_fetch(
        "SELECT id FROM ekstrakurikuler WHERE pembina_id=? AND status='aktif' LIMIT 1",
        [$_SESSION['guru_id']]
    );
    $_isPembina = !empty($_eksBina);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= htmlspecialchars($pageTitle) ?> - SisPen Snesaka</title>
  <link rel="stylesheet" href="<?= $B ?>/style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
<div class="wrapper">

<!-- SIDEBAR -->
<aside class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-icon">S</div>
    <div class="brand-text">
      <div class="brand-name">SisPen Snesaka</div>
      <div class="brand-sub">Manajemen Nilai Rapor</div>
    </div>
  </div>

  <nav class="sidebar-menu">
    <div class="menu-section">Menu Utama</div>
    <a href="<?= $B ?>/<?= $isAdmin ? 'admin.php' : 'guru.php' ?>" class="menu-item <?= $activeMenu === 'dashboard' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-home"></i></span> Dashboard
    </a>

    <?php if ($isAdmin): ?>
    <div class="menu-section">Manajemen Data</div>
    <a href="<?= $B ?>/modules/guru/list.php" class="menu-item <?= $activeMenu === 'guru' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-chalkboard-teacher"></i></span> Data Guru
    </a>
    <a href="<?= $B ?>/modules/siswa/list.php" class="menu-item <?= $activeMenu === 'siswa' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-users"></i></span> Data Siswa
    </a>
    <a href="<?= $B ?>/modules/kelas/list.php" class="menu-item <?= $activeMenu === 'kelas' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-door-open"></i></span> Data Kelas
    </a>
    <a href="<?= $B ?>/modules/mapel/list.php" class="menu-item <?= $activeMenu === 'mapel' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-book"></i></span> Mata Pelajaran
    </a>
    <a href="<?= $B ?>/modules/guru/bk_kelas.php" class="menu-item <?= $activeMenu === 'bk-kelas' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-user-md"></i></span> Setting Kelas BK
    </a>
    <a href="<?= $B ?>/modules/siswa/akun_siswa.php" class="menu-item <?= $activeMenu === 'akun-siswa' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-user-graduate"></i></span> Akun Siswa
    </a>
    <?php endif; ?>

    <div class="menu-section">Penilaian</div>
    <a href="<?= $B ?>/modules/nilai/input.php" class="menu-item <?= $activeMenu === 'nilai-input' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-edit"></i></span> Input Nilai
    </a>
    <a href="<?= $B ?>/modules/nilai/report.php" class="menu-item <?= $activeMenu === 'nilai-report' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-chart-bar"></i></span> Laporan Nilai
    </a>

    <div class="menu-section">Absensi</div>
    <a href="<?= $B ?>/modules/absensi/input.php" class="menu-item <?= $activeMenu === 'absensi' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-calendar-check"></i></span> Input Absensi
    </a>
    <a href="<?= $B ?>/modules/absensi/report.php" class="menu-item <?= $activeMenu === 'absensi-report' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-clipboard-list"></i></span> Rekap Absensi
    </a>

    <?php if ($isAdmin || $_isPembina): ?>
    <div class="menu-section">Ekstrakurikuler</div>
    <a href="<?= $B ?>/modules/ekstra/nilai.php" class="menu-item <?= $activeMenu === 'ekstra' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-trophy"></i></span> Nilai Ekstrakurikuler
    </a>
    <?php if ($isAdmin): ?>
    <a href="<?= $B ?>/modules/ekstra/list.php" class="menu-item <?= $activeMenu === 'ekstra-list' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-list-ul"></i></span> Kelola Ekstrakurikuler
    </a>
    <?php endif; ?>
    <?php endif; ?>

    <div class="menu-section">Cetak</div>
    <a href="<?= $B ?>/<?= $isAdmin ? 'cetak_nilai.php' : 'cetak_nilai_guru.php' ?>" class="menu-item <?= $activeMenu === 'cetak' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-print"></i></span> Cetak Daftar Nilai
    </a>

    <div class="menu-section">PSAJ Kelas 9</div>
    <a href="<?= $B ?>/modules/psaj/input.php" class="menu-item <?= $activeMenu === 'psaj-input' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-graduation-cap"></i></span> Input Nilai PSAJ
    </a>
    <a href="<?= $B ?>/modules/psaj/cetak.php" class="menu-item <?= $activeMenu === 'psaj-cetak' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-print"></i></span> Cetak Nilai PSAJ
    </a>

    <?php if ($isAdmin): ?>
    <div class="menu-section">Pengaturan</div>
    <a href="<?= $B ?>/modules/pengaturan.php" class="menu-item <?= $activeMenu === 'pengaturan' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-cog"></i></span> Pengaturan Sekolah
    </a>
    <a href="<?= $B ?>/modules/backup/index.php" class="menu-item <?= $activeMenu === 'backup' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-database"></i></span> Backup & Restore
    </a>
    <?php endif; ?>

    <div class="menu-section">Akun</div>
    <?php if (!$isAdmin): ?>
    <a href="<?= $B ?>/modules/guru/profil.php" class="menu-item <?= $activeMenu === 'profil' ? 'active' : '' ?>">
      <span class="icon"><i class="fas fa-user-edit"></i></span> Profil Saya
    </a>
    <?php endif; ?>
    <a href="<?= $B ?>/logout.php" class="menu-item" onclick="return confirm('Yakin ingin keluar?')">
      <span class="icon"><i class="fas fa-sign-out-alt"></i></span> Logout
    </a>
  </nav>
</aside>

<!-- MAIN -->
<div class="main-content">
  <header class="topbar">
    <div class="topbar-left">
      <button id="toggleSidebar" style="cursor:pointer;font-size:15px;padding:0;">
        <i class="fas fa-bars"></i>
      </button>
      <div>
        <div class="topbar-title"><?= htmlspecialchars($pageTitle) ?></div>
        <?php if (isset($breadcrumb)): ?>
        <div class="topbar-breadcrumb">
          <i class="fas fa-home" style="font-size:10px;"></i>
          <span style="opacity:.4;">/</span>
          <?= $breadcrumb ?>
        </div>
        <?php endif; ?>
      </div>
    </div>
    <div class="topbar-right">

      <!-- Tanggal & Jam -->
      <div class="topbar-datetime">
        <div class="td-date" id="tb-date">—</div>
        <div class="td-time" id="tb-time">—</div>
      </div>

      <div class="topbar-divider"></div>

      <!-- User badge: guru → klik ke profil, admin → tidak bisa klik -->
      <?php if (!$isAdmin): ?>
      <a href="<?= $B ?>/modules/guru/profil.php"
         class="user-badge" style="text-decoration:none;" title="Edit Profil Saya">
        <div class="avatar"><?= strtoupper(substr($_SESSION['nama'] ?? 'U', 0, 1)) ?></div>
        <div class="user-info">
          <div class="name"><?= htmlspecialchars($_SESSION['nama'] ?? '') ?></div>
          <div class="role">
            <?= ucfirst($_SESSION['role'] ?? '') ?>
            <i class="fas fa-pen" style="font-size:9px;opacity:.6;margin-left:3px;"></i>
          </div>
        </div>
      </a>
      <?php else: ?>
      <div class="user-badge">
        <div class="avatar"><?= strtoupper(substr($_SESSION['nama'] ?? 'U', 0, 1)) ?></div>
        <div class="user-info">
          <div class="name"><?= htmlspecialchars($_SESSION['nama'] ?? '') ?></div>
          <div class="role"><?= ucfirst($_SESSION['role'] ?? '') ?></div>
        </div>
      </div>
      <?php endif; ?>

      <div class="topbar-divider"></div>

      <!-- Logout -->
      <a href="<?= $B ?>/logout.php"
         onclick="return confirm('Yakin ingin keluar?')"
         style="display:flex;align-items:center;gap:7px;padding:0 14px;height:36px;border-radius:8px;background:rgba(220,38,38,.25);border:1px solid rgba(220,38,38,.4);color:#fca5a5;transition:all .2s;text-decoration:none;font-size:13px;font-weight:600;white-space:nowrap;"
         onmouseover="this.style.background='rgba(220,38,38,.5)';this.style.borderColor='rgba(220,38,38,.7)';this.style.color='#fff';"
         onmouseout="this.style.background='rgba(220,38,38,.25)';this.style.borderColor='rgba(220,38,38,.4)';this.style.color='#fca5a5';">
        <i class="fas fa-sign-out-alt" style="font-size:13px;"></i>
        <span>Logout</span>
      </a>

    </div>
  </header>

  <main class="page-content">
    <?php
    $flash = getFlash();
    if ($flash): ?>
    <div class="alert alert-<?= $flash['type'] ?>">
      <i class="fas <?= $flash['type'] === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?>"></i>
      <?= htmlspecialchars($flash['message']) ?>
    </div>
    <?php endif; ?>

<script>
// ── Jam & tanggal real-time ──────────────────────────────
(function(){
  var hr = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
  var bl = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
  function pad(n){ return n < 10 ? '0'+n : n; }
  function tick(){
    var d = new Date();
    var tgl = hr[d.getDay()] + ', ' + d.getDate() + ' ' + bl[d.getMonth()] + ' ' + d.getFullYear();
    var jam = pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
    var de = document.getElementById('tb-date');
    var te = document.getElementById('tb-time');
    if(de) de.textContent = tgl;
    if(te) te.textContent = jam;
  }
  tick();
  setInterval(tick, 1000);
})();

// ── Sidebar toggle (desktop & mobile) ───────────────────
(function(){
  var sidebar  = document.getElementById('sidebar');
  var btn      = document.getElementById('toggleSidebar');
  var isMobile = function(){ return window.innerWidth <= 768; };

  // Buat overlay sekali
  var overlay = document.createElement('div');
  overlay.className = 'sidebar-overlay';
  document.body.appendChild(overlay);

  function openSidebar(){
    sidebar.classList.add('open');
    if(isMobile()) overlay.classList.add('show');
  }
  function closeSidebar(){
    sidebar.classList.remove('open');
    overlay.classList.remove('show');
  }
  function toggleSidebar(){
    if(sidebar.classList.contains('open')) closeSidebar();
    else openSidebar();
  }

  // Desktop: sembunyikan/tampilkan sidebar dengan geser main-content
  function desktopToggle(){
    var main = document.querySelector('.main-content');
    if(sidebar.style.transform === 'translateX(-100%)'){
      sidebar.style.transform = '';
      if(main) main.style.marginLeft = '';
    } else {
      sidebar.style.transform = 'translateX(-100%)';
      if(main) main.style.marginLeft = '0';
    }
  }

  if(btn){
    btn.addEventListener('click', function(){
      if(isMobile()) toggleSidebar();
      else desktopToggle();
    });
  }

  // Tutup saat klik overlay
  overlay.addEventListener('click', closeSidebar);

  // Tutup saat klik menu item di mobile
  var menuItems = document.querySelectorAll('.menu-item');
  menuItems.forEach(function(item){
    item.addEventListener('click', function(){
      if(isMobile()) closeSidebar();
    });
  });

  // Swipe kanan untuk buka, swipe kiri untuk tutup
  var touchStartX = 0;
  document.addEventListener('touchstart', function(e){
    touchStartX = e.touches[0].clientX;
  }, {passive:true});
  document.addEventListener('touchend', function(e){
    var diff = e.changedTouches[0].clientX - touchStartX;
    if(!isMobile()) return;
    if(diff > 60 && touchStartX < 30) openSidebar();   // swipe kanan dari tepi
    if(diff < -60) closeSidebar();                       // swipe kiri
  }, {passive:true});

  // Tutup sidebar saat resize ke desktop
  window.addEventListener('resize', function(){
    if(!isMobile()){
      overlay.classList.remove('show');
      sidebar.classList.remove('open');
      sidebar.style.transform = '';
      var main = document.querySelector('.main-content');
      if(main) main.style.marginLeft = '';
    }
  });
})();
</script>
