<?php
$info = model('App\Models\SchoolInfoModel')->find(1);

$logo = !empty($info['logo_path']) ? base_url($info['logo_path']) : base_url('assets/images/logo1.png');
$schoolName = !empty($info['school_name']) ? esc($info['school_name']) : 'SMAS SENTOSA BHAKTI';

$kategori = strtolower(trim((string)($_GET['kategori'] ?? 'all'))); // all|pengumuman|kegiatan|prestasi
$allowed  = ['all','pengumuman','kegiatan','prestasi'];
if (!in_array($kategori, $allowed, true)) $kategori = 'all';

$beritaModel = model('App\Models\BeritaModel');

// pagination
$perPage = 9;
$page    = max(1, (int)($_GET['page'] ?? 1));
$offset  = ($page - 1) * $perPage;

$builder = $beritaModel->orderBy('created_at', 'DESC');

if ($kategori !== 'all') {
    $builder->where('kategori', $kategori);
}

$totalRows = $builder->countAllResults(false); // false: jangan reset builder
$rows      = $builder->findAll($perPage, $offset);

$totalPages = (int)ceil($totalRows / $perPage);

function tabClass($cur, $val) { return $cur === $val ? 'active' : ''; }
function qurl($kategori, $page = 1) {
    $q = ['kategori' => $kategori];
    if ($page > 1) $q['page'] = $page;
    return base_url('berita') . '?' . http_build_query($q);
}
function badgeText($k) {
    $k = strtolower((string)$k);
    if ($k === 'pengumuman') return 'PENGUMUMAN';
    if ($k === 'kegiatan')   return 'KEGIATAN';
    if ($k === 'prestasi')   return 'PRESTASI';
    return strtoupper($k);
}

// helper gambar
function beritaImage($row) {
    if (!empty($row['gambar'])) return base_url($row['gambar']);
    return 'https://via.placeholder.com/400x300/4A90C7/ffffff?text=Berita';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= $schoolName ?></title>

  <link rel="stylesheet" href="<?= base_url('assets/css/.css') ?>">
  <link rel="stylesheet" href="<?= base_url('assets/fontawesome/css/all.css') ?>">
  <link rel="icon" href="<?= base_url('assets/images/logo1.png') ?>" type="image/png">
</head>
<body>

<nav>
  <div class="left-box">
    <img src="<?= $logo ?>" alt="Logo">
    <span class="school-name"><?= $schoolName ?></span>
  </div>

  <ul>
    <a href="<?= base_url() ?>">Beranda</a>
    <a href="<?= base_url('berita') ?>">Berita</a>
    <a href="<?= base_url('galeri') ?>">Galeri</a>
    <a href="<?= base_url('tentang') ?>">Tentang</a>
  </ul>
</nav>

<!-- BERITA SECTION -->
<section class="berita-section">
  <div class="berita-header">
    <h1>Berita Terkini</h1>
    <p>Informasi dan kabar terbaru dari SMAS Sentosa Bhakti</p>
  </div>

  <!-- CATEGORY TABS -->
  <div class="category-tabs">
    <a class="category-tab <?= tabClass($kategori,'all') ?>" href="<?= qurl('all', 1) ?>">Semua</a>
    <a class="category-tab <?= tabClass($kategori,'pengumuman') ?>" href="<?= qurl('pengumuman', 1) ?>">Pengumuman</a>
    <a class="category-tab <?= tabClass($kategori,'kegiatan') ?>" href="<?= qurl('kegiatan', 1) ?>">Kegiatan</a>
    <a class="category-tab <?= tabClass($kategori,'prestasi') ?>" href="<?= qurl('prestasi', 1) ?>">Prestasi</a>
  </div>

  <!-- NEWS GRID -->
  <div class="news-grid">
    <?php if (empty($rows)): ?>
      <div style="padding:20px;">Belum ada berita.</div>
    <?php else: ?>
      <?php foreach ($rows as $b): ?>
        <div class="news-card">
          <div class="news-image">
            <span class="news-badge"><?= esc(badgeText($b['kategori'] ?? '')) ?></span>
            <img src="<?= esc(beritaImage($b)) ?>" alt="<?= esc($b['judul'] ?? 'Berita') ?>">
          </div>
          <div class="news-content">
            <div class="news-meta">
              <span>📅 <?= !empty($b['tanggal_publish']) ? date('d M Y', strtotime($b['tanggal_publish'])) : '-' ?></span>
              <span>👤 Admin</span>
            </div>
            <h3 class="news-title"><?= esc($b['judul'] ?? '') ?></h3>
            <p class="news-excerpt"><?= esc($b['ringkas'] ?? '') ?></p>
            <a href="<?= base_url('berita/' . ($b['slug'] ?? '')) ?>" class="news-link">
              Baca Selengkapnya →
            </a>
          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <!-- PAGINATION -->
  <?php if ($totalPages > 1): ?>
    <div class="pagination">
      <a class="page-btn" href="<?= qurl($kategori, max(1, $page-1)) ?>">‹</a>

      <?php
        $start = max(1, $page - 2);
        $end   = min($totalPages, $page + 2);
        if ($start > 1) {
          echo '<a class="page-btn" href="'.esc(qurl($kategori,1)).'">1</a>';
          if ($start > 2) echo '<span class="page-btn disabled">...</span>';
        }
        for ($i=$start; $i<=$end; $i++):
      ?>
        <a class="page-btn <?= $i === $page ? 'active' : '' ?>" href="<?= qurl($kategori, $i) ?>"><?= $i ?></a>
      <?php endfor;
        if ($end < $totalPages) {
          if ($end < $totalPages - 1) echo '<span class="page-btn disabled">...</span>';
          echo '<a class="page-btn" href="'.esc(qurl($kategori,$totalPages)).'">'.$totalPages.'</a>';
        }
      ?>

      <a class="page-btn" href="<?= qurl($kategori, min($totalPages, $page+1)) ?>">›</a>
    </div>
  <?php endif; ?>
</section>

<script>
// Hamburger Menu Toggle
document.addEventListener('DOMContentLoaded', function() {
    // Buat elemen hamburger button
    const hamburger = document.createElement('div');
    hamburger.className = 'hamburger';
    hamburger.innerHTML = '<span></span><span></span><span></span>';
    
    // Tambahkan hamburger ke dalam nav
    const nav = document.querySelector('nav');
    nav.appendChild(hamburger);
    
    // Get menu ul
    const navMenu = document.querySelector('nav ul');
    
    // Toggle menu saat hamburger diklik
    hamburger.addEventListener('click', function() {
        this.classList.toggle('active');
        navMenu.classList.toggle('active');
    });
    
    // Close menu saat link diklik
    const navLinks = document.querySelectorAll('nav ul a');
    navLinks.forEach(link => {
        link.addEventListener('click', function() {
            hamburger.classList.remove('active');
            navMenu.classList.remove('active');
        });
    });
    
    // Close menu saat klik di luar
    document.addEventListener('click', function(e) {
        if (!nav.contains(e.target)) {
            hamburger.classList.remove('active');
            navMenu.classList.remove('active');
        }
    });
});
</script>

</body>
</html>
