<?php
require_once __DIR__ . '/config/secure_public.php';

// ====== FILTER & PAGINATION ======
$search = trim($_GET['q'] ?? '');
$year_filter = $_GET['year'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 6;
$offset = ($page - 1) * $limit;

// ====== QUERY FILTER ======
$where = ["status = 'published'"];
$params = [];

if ($search !== '') {
    $where[] = "(title LIKE ? OR content LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($year_filter !== '') {
    $where[] = "YEAR(published_at) = ?";
    $params[] = $year_filter;
}

$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// ====== COUNT & FETCH DATA ======
$stmt_count = $pdo->prepare("SELECT COUNT(*) FROM news $where_sql");
$stmt_count->execute($params);
$total_rows = $stmt_count->fetchColumn();
$total_pages = ceil($total_rows / $limit);

$stmt = $pdo->prepare("
  SELECT id, title, slug, excerpt, featured_image, published_at
  FROM news
  $where_sql
  ORDER BY published_at DESC
  LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$news = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ====== FILTER TAHUN ======
$stmt_years = $pdo->query("
  SELECT DISTINCT YEAR(published_at) AS year FROM news WHERE published_at IS NOT NULL ORDER BY year DESC
");
$years = $stmt_years->fetchAll(PDO::FETCH_COLUMN);

// ====== META ======
$page_title = "Berita | $site_name";
$page_description = "Kumpulan berita dan informasi terbaru dari Lembaga Penjaminan Mutu (LPM) Universitas Riyadlul Ulum Tasikmalaya.";
$page_url = base_url('berita.php');

include __DIR__ . '/includes/header.php';
?>

<!-- HERO -->
<section class="hero-news d-flex align-items-center justify-content-center text-center text-white position-relative">
  <div class="overlay"></div>
  <div class="content position-relative z-2 px-5">
    <h1 class="fw-bold display-6 mb-2">Berita & Informasi</h1>
    <p class="text-light small">Update kegiatan, kebijakan, dan capaian mutu LPM UNIRU</p>
  </div>
</section>

<div class="container my-5">

  <!-- FILTER FORM -->
  <form method="get" class="mb-4">
    <div class="row g-2 align-items-center justify-content-center">
      <div class="col-md-4">
        <input type="text" name="q" class="form-control" placeholder="Cari berita..." value="<?= e($search); ?>">
      </div>
      <div class="col-md-3">
        <select name="year" class="form-select">
          <option value="">Semua Tahun</option>
          <?php foreach ($years as $y): ?>
            <option value="<?= e($y); ?>" <?= $year_filter == $y ? 'selected' : ''; ?>><?= e($y); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <button class="btn btn-success w-100"><i class="fa fa-search me-1"></i> Filter</button>
      </div>
    </div>
  </form>
  
  <!-- Highlight berita utama -->
<?php
$stmt_featured = $pdo->query("SELECT * FROM news WHERE status='published' ORDER BY published_at DESC LIMIT 1");
$featured = $stmt_featured->fetch(PDO::FETCH_ASSOC);
if ($featured):
?>
<!--<section class="mb-5">-->
<!--  <div class="card border-0 shadow-sm overflow-hidden">-->
<!--    <div class="row g-0">-->
<!--      <div class="col-md-6">-->
<!--        <img src="<?= base_url('uploads/berita/' . e($featured['featured_image'])); ?>" class="img-fluid h-100 object-fit-cover" alt="<?= e($featured['title']); ?>">-->
<!--      </div>-->
<!--      <div class="col-md-6 p-4 d-flex flex-column justify-content-center">-->
<!--        <h3 class="fw-bold"><?= e($featured['title']); ?></h3>-->
<!--        <p class="small text-muted mb-3"><?= indoDate(substr($featured['published_at'],0,10)); ?></p>-->
<!--        <p><?= e(mb_strimwidth(strip_tags($featured['excerpt']), 0, 180, '...')); ?></p>-->
<!--        <a href="<?= base_url('berita_detail.php?slug=' . urlencode($featured['slug'])); ?>" class="btn btn-outline-success btn-sm mt-2">Baca Selengkapnya</a>-->
<!--      </div>-->
<!--    </div>-->
<!--  </div>-->
<!--</section>-->
<?php endif; ?>


  <!-- DAFTAR BERITA -->
  <div class="row g-4">
    <?php if ($news): ?>
      <?php foreach ($news as $item): ?>
        <div class="col-md-4 fade-section">
          <div class="card border-0 shadow-sm h-100 news-card">
            <?php if (!empty($item['featured_image'])): ?>
              <img src="<?= base_url('uploads/berita/' . e($item['featured_image'])); ?>" alt="<?= e($item['title']); ?>" class="card-img-top" loading="lazy">
            <?php endif; ?>
            <div class="card-body">
              <h5 class="fw-semibold mb-1"><?= e($item['title']); ?></h5>
              <p class="text-muted small mb-2"><?= $item['published_at'] ? indoDate(substr($item['published_at'], 0, 10)) : '-'; ?></p>
              <p class="small text-secondary mb-2"><?= e(mb_strimwidth(strip_tags($item['excerpt']), 0, 110, '...')); ?></p>
              <a href="<?= base_url('berita_detail.php?slug=' . urlencode($item['slug'])); ?>" class="stretched-link text-success small">Baca selengkapnya →</a>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    <?php else: ?>
      <p class="text-center text-muted py-4">Tidak ada berita ditemukan.</p>
    <?php endif; ?>
  </div>

  <!-- PAGINATION -->
  <?php if ($total_pages > 1): ?>
    <nav aria-label="Pagination" class="mt-5">
      <ul class="pagination justify-content-center">
        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
          <li class="page-item <?= $i == $page ? 'active' : ''; ?>">
            <a class="page-link" href="?q=<?= urlencode($search); ?>&year=<?= urlencode($year_filter); ?>&page=<?= $i; ?>"><?= $i; ?></a>
          </li>
        <?php endfor; ?>
      </ul>
    </nav>
  <?php endif; ?>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>

<!-- ====== CUSTOM STYLE ====== -->
<style>
.hero-news {
  height: 40vh;
  background: linear-gradient(120deg, var(--green) 0%, var(--brown) 100%);
  position: relative;
  padding-top: 4rem;
}
.hero-news .overlay {
  position: absolute;
  inset: 0;
  background: rgba(0,0,0,0.45);
}
.news-card {
  border-radius: 12px;
  transition: transform .3s ease, box-shadow .3s ease;
}
.news-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0,0,0,.15);
}
.news-card img {
  height: 200px;
  object-fit: cover;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

/* Fade animation */
.fade-section {
  opacity: 0;
  transform: translateY(30px);
  transition: opacity 0.8s ease, transform 0.8s ease;
}
.fade-section.visible {
  opacity: 1;
  transform: translateY(0);
}
</style>

<!-- ====== SCROLL ANIMATION ====== -->
<script>
document.addEventListener("DOMContentLoaded", () => {
  const fadeSections = document.querySelectorAll(".fade-section");
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) entry.target.classList.add("visible");
    });
  }, { threshold: 0.2 });

  fadeSections.forEach(section => observer.observe(section));
});
</script>
