<?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;

// ====== BUILD QUERY DASAR ======
$where = [];
$params = [];

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

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

// Hitung total
$stmt_count = $pdo->prepare("SELECT COUNT(*) FROM activities $where_sql");
$stmt_count->execute($params);
$total_rows = $stmt_count->fetchColumn();
$total_pages = ceil($total_rows / $limit);

// Ambil data
$stmt = $pdo->prepare("
  SELECT id, title, description, date_start, date_end, location, organizer, image, document
  FROM activities
  $where_sql
  ORDER BY date_start DESC
  LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$activities = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Ambil tahun unik untuk filter
$stmt_years = $pdo->query("SELECT DISTINCT YEAR(date_start) AS year FROM activities ORDER BY year DESC");
$years = $stmt_years->fetchAll(PDO::FETCH_COLUMN);

// Meta
$page_title = "Kegiatan | $site_name";
$page_description = "Daftar kegiatan terbaru Lembaga Penjaminan Mutu (LPM) Universitas Riyadlul Ulum Tasikmalaya.";
$page_url = base_url('kegiatan.php');
include __DIR__ . '/includes/header.php';
?>

<!-- HERO -->
<section class="hero-activity 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">
    <h1 class="fw-bold display-6 mb-2">Kegiatan LPM UNIRU</h1>
    <p class="text-light small">Kegiatan akademik dan non-akademik dalam penjaminan mutu pendidikan</p>
  </div>
</section>

<div class="container my-5">
  
  <!-- FILTER -->
  <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 kegiatan..." 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>

  <!-- DAFTAR KEGIATAN -->
  <div class="row g-4">
    <?php if ($activities): ?>
      <?php foreach ($activities as $act): ?>
        <div class="col-md-4 fade-section">
          <div class="card border-0 shadow-sm h-100 activity-card">
            <?php if (!empty($act['image'])): ?>
  <img src="<?= base_url('uploads/kegiatan/images/' . e($act['image'])); ?>" 
       alt="<?= e($act['title']); ?>" class="card-img-top" loading="lazy">
<?php endif; ?>

            <div class="card-body">
              <h5 class="fw-semibold mb-1"><?= e($act['title']); ?></h5>
              <p class="text-muted small mb-2">
                <?= indoDate($act['date_start']); ?>
                <?php if ($act['date_end'] && $act['date_end'] !== $act['date_start']): ?>
                  – <?= indoDate($act['date_end']); ?>
                <?php endif; ?>
              </p>
              <p class="small text-secondary mb-2"><?= e(mb_strimwidth(strip_tags($act['description']), 0, 110, '...')); ?></p>
              <a href="<?= base_url('kegiatan_detail.php?id=' . $act['id']); ?>" class="stretched-link text-success small">Lihat kegiatan →</a>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    <?php else: ?>
      <p class="text-center text-muted py-4">Tidak ada kegiatan 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 STYLES ===== -->
<style>
.hero-activity {
  height: 40vh;
  background: linear-gradient(120deg, var(--green) 0%, var(--brown) 100%);
  position: relative;
  padding-top: 4rem;
}
.hero-activity .overlay {
  position: absolute;
  inset: 0;
  background: rgba(0,0,0,0.45);
}
.activity-card {
  border-radius: 12px;
  transition: transform .3s ease, box-shadow .3s ease;
}
.activity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0,0,0,.15);
}
.activity-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>
