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

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

// ====== WHERE CLAUSE ======
$today = date('Y-m-d');
$where = [
  "p.status = 'active'",
];
$params = [];

if ($search !== '') {
  $where[]  = "(p.judul LIKE ? OR p.isi LIKE ?)";
  $params[] = "%$search%";
  $params[] = "%$search%";
}

if ($audience_filter !== '') {
  $where[]  = "p.target_audience = ?";
  $params[] = $audience_filter;
}

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

// ====== TOTAL & DATA ======
$sql_count = "SELECT COUNT(*) FROM pengumuman p $where_sql";
$stmt_count = $pdo->prepare($sql_count);
$stmt_count->execute($params);
$total_rows  = (int)$stmt_count->fetchColumn();
$total_pages = max(1, ceil($total_rows / $limit));

// Data pengumuman
$sql_data = "
  SELECT
    p.id,
    p.judul,
    p.slug,
    p.isi,
    p.file_lampiran,
    p.tanggal_mulai,
    p.tanggal_selesai,
    p.prioritas,
    p.target_audience,
    p.status,
    p.views,
    p.created_at,
    p.updated_at
  FROM pengumuman p
  $where_sql
  ORDER BY 
    FIELD(p.prioritas, 'urgent','tinggi','normal','rendah') ASC,
    p.tanggal_mulai DESC
  LIMIT $limit OFFSET $offset
";
$stmt = $pdo->prepare($sql_data);
$stmt->execute($params);
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Ambil semua target_audience unik untuk filter
$stmt_aud = $pdo->query("
  SELECT DISTINCT target_audience
  FROM pengumuman
  ORDER BY target_audience ASC
");
$audiences = $stmt_aud->fetchAll(PDO::FETCH_COLUMN);

// Hitung statistik sederhana
$stmt_stats = $pdo->prepare("
  SELECT 
    COUNT(*) AS total,
    SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active_count
  FROM pengumuman
");
$stmt_stats->execute();
$stats = $stmt_stats->fetch(PDO::FETCH_ASSOC);

// ====== META ======
$page_title       = "Pengumuman | $site_name";
$page_description = "Daftar pengumuman resmi Lembaga Penjaminan Mutu (LPM) Universitas Riyadlul Ulum.";
$page_url         = base_url('pengumuman.php');

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

<!-- HERO -->
<section class="hero-contact 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">
      <i class="fa fa-bullhorn me-2"></i>Pengumuman
    </h1>
    <p class="text-light mb-3">Informasi dan pemberitahuan resmi LPM</p>
    <div class="stats-hero d-flex gap-4 justify-content-center flex-wrap small">
      <div class="stat-item text-center">
        <div class="stat-number"><?= (int)$stats['total'] ?></div>
        <div class="stat-label">Total Pengumuman</div>
      </div>
      <div class="stat-item text-center">
        <div class="stat-number"><?= (int)$stats['active_count'] ?></div>
        <div class="stat-label">Sedang Aktif</div>
      </div>
    </div>
  </div>
</section>

<div class="container my-5">

  <!-- INFO BANNER -->
  <?php if ($search || $audience_filter): ?>
    <div class="alert alert-info alert-dismissible fade show d-flex align-items-center" role="alert">
      <i class="fa fa-filter me-2"></i>
      <div>
        <strong>Filter aktif:</strong>
        <?php if ($search): ?>
          Pencarian: "<?= e($search) ?>"
        <?php endif; ?>
        <?php if ($audience_filter): ?>
          | Sasaran: <?= e(ucwords(str_replace('_', ' ', $audience_filter))) ?>
        <?php endif; ?>
        <a href="pengumuman.php" class="alert-link ms-2">Reset Filter</a>
      </div>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>

  <!-- FILTER FORM -->
  <div class="filter-section mb-4 fade-section">
    <form method="get" class="card border-0 shadow-sm rounded-4">
      <div class="card-body">
        <div class="row g-3 align-items-end">
          <div class="col-md-5">
            <label class="form-label small text-muted mb-1">
              <i class="fa fa-search me-1"></i>Pencarian
            </label>
            <input type="text" name="q" class="form-control" 
                   placeholder="Cari pengumuman berdasarkan judul atau isi..." 
                   value="<?= e($search) ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label small text-muted mb-1">
              <i class="fa fa-users me-1"></i>Sasaran
            </label>
            <select name="audience" class="form-select">
              <option value="">Semua Sasaran</option>
              <?php foreach ($audiences as $aud): ?>
                <option value="<?= e($aud) ?>" <?= $audience_filter == $aud ? 'selected' : '' ?>>
                  <?= e(ucwords(str_replace('_', ' ', $aud))) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-3">
            <button type="submit" class="btn btn-success w-100">
              <i class="fa fa-search me-1"></i> Cari Pengumuman
            </button>
          </div>
        </div>
      </div>
    </form>
  </div>

<!-- LIST PENGUMUMAN -->
<div class="row g-4 mb-4">
  <?php if ($items): ?>
    <?php foreach ($items as $row): ?>
      <div class="col-md-6 col-lg-4 fade-section">
        <a href="pengumuman_detail.php?slug=<?= urlencode($row['slug']) ?>" class="text-decoration-none">
          <div class="card border-0 shadow-sm h-100 pengumuman-card rounded-4">
            <div class="card-body d-flex flex-column">

              <!-- Badge prioritas & sasaran -->
              <div class="mb-2 d-flex justify-content-between">
                <span class="badge bg-prioritas-<?= e($row['prioritas']) ?>">
                  <?= strtoupper($row['prioritas']) ?>
                </span>
                <span class="badge bg-light text-muted">
                  <i class="fa fa-users me-1"></i>
                  <?= e(ucwords(str_replace('_', ' ', $row['target_audience']))) ?>
                </span>
              </div>

              <!-- Judul -->
              <h5 class="fw-semibold mb-2 text-success pengumuman-title">
                <?= e($row['judul']) ?>
              </h5>

              <!-- Meta -->
              <div class="pengumuman-meta small text-muted mb-3">
                <div class="mb-1">
                  <i class="fa fa-calendar me-1 text-success"></i>
                  <span>
                    <?= indoDate($row['tanggal_mulai']) ?> 
                    s/d 
                    <?= indoDate($row['tanggal_selesai']) ?>
                  </span>
                </div>
                <div class="mb-1">
                  <i class="fa fa-eye me-1 text-success"></i>
                  <span><?= (int)$row['views'] ?> kali dibaca</span>
                </div>
              </div>

              <!-- Cuplikan isi -->
              <p class="card-text small flex-grow-1 text-dark">
                <?= e(mb_strimwidth(strip_tags($row['isi']), 0, 160, '...')) ?>
              </p>

              <!-- Lampiran Info -->
              <div class="mt-3">
                <?php if (!empty($row['file_lampiran'])): ?>
                  <div class="d-flex align-items-center text-success small">
                    <i class="fa fa-paperclip me-1"></i>
                    <span>File lampiran tersedia</span>
                  </div>
                <?php else: ?>
                  <div class="text-muted small">
                    <i class="fa fa-paperclip me-1"></i>
                    <span>Tidak ada lampiran</span>
                  </div>
                <?php endif; ?>
              </div>

            </div>
          </div>
        </a>
      </div>
    <?php endforeach; ?>
  <?php else: ?>
    <div class="col-12">
      <div class="text-center py-5">
        <i class="fa fa-bullhorn fa-4x text-muted mb-3"></i>
        <h4 class="text-muted mb-2">Tidak ada pengumuman</h4>
        <p class="text-muted">
          <?php if ($search || $audience_filter): ?>
            Coba ubah kata kunci atau sasaran
          <?php else: ?>
            Belum ada pengumuman aktif saat ini
          <?php endif; ?>
        </p>
        <?php if ($search || $audience_filter): ?>
          <a href="pengumuman.php" class="btn btn-success mt-2">
            <i class="fa fa-refresh me-1"></i> Reset Filter
          </a>
        <?php endif; ?>
      </div>
    </div>
  <?php endif; ?>
</div>

  <!-- PAGINATION -->
  <?php if ($total_pages > 1): ?>
    <nav aria-label="Pagination" class="mt-4">
      <ul class="pagination justify-content-center">
        <!-- Prev -->
        <?php if ($page > 1): ?>
          <li class="page-item">
            <a class="page-link" href="?q=<?= urlencode($search) ?>&audience=<?= urlencode($audience_filter) ?>&page=<?= $page - 1 ?>">
              <i class="fa fa-chevron-left"></i>
            </a>
          </li>
        <?php endif; ?>

        <?php 
        $start_page = max(1, $page - 2);
        $end_page   = min($total_pages, $page + 2);

        if ($start_page > 1): ?>
          <li class="page-item">
            <a class="page-link" href="?q=<?= urlencode($search) ?>&audience=<?= urlencode($audience_filter) ?>&page=1">1</a>
          </li>
          <?php if ($start_page > 2): ?>
            <li class="page-item disabled"><span class="page-link">...</span></li>
          <?php endif; ?>
        <?php endif; ?>

        <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
          <li class="page-item <?= $i == $page ? 'active' : '' ?>">
            <a class="page-link" href="?q=<?= urlencode($search) ?>&audience=<?= urlencode($audience_filter) ?>&page=<?= $i ?>"><?= $i ?></a>
          </li>
        <?php endfor; ?>

        <?php if ($end_page < $total_pages): ?>
          <?php if ($end_page < $total_pages - 1): ?>
            <li class="page-item disabled"><span class="page-link">...</span></li>
          <?php endif; ?>
          <li class="page-item">
            <a class="page-link" href="?q=<?= urlencode($search) ?>&audience=<?= urlencode($audience_filter) ?>&page=<?= $total_pages ?>"><?= $total_pages ?></a>
          </li>
        <?php endif; ?>

        <!-- Next -->
        <?php if ($page < $total_pages): ?>
          <li class="page-item">
            <a class="page-link" href="?q=<?= urlencode($search) ?>&audience=<?= urlencode($audience_filter) ?>&page=<?= $page + 1 ?>">
              <i class="fa fa-chevron-right"></i>
            </a>
          </li>
        <?php endif; ?>
      </ul>
    </nav>
  <?php endif; ?>

</div>

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

<style>
.hero-contact {
  height: 40vh;
  background: linear-gradient(120deg, var(--green) 0%, var(--brown) 100%);
  position: relative;
  padding-top: 4rem;
}
.hero-contact .overlay {
  position: absolute;
  inset: 0;
  background: rgba(0,0,0,0.45);
}
.stats-hero .stat-number {
  font-size: 1.4rem;
  font-weight: 700;
}
.stats-hero .stat-label {
  font-size: .8rem;
  opacity: .9;
}

/* Card pengumuman */
.pengumuman-card {
  transition: all .3s ease;
  border: 1px solid #e8e8e8 !important;
}
.pengumuman-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 1rem 2rem rgba(0,0,0,.1) !important;
  border-color: var(--green) !important;
}

/* Judul pengumuman */
.pengumuman-title {
  font-size: 1.1rem;
  line-height: 1.4;
  transition: color .2s ease;
}
a:hover .pengumuman-title {
  color: #084d36 !important;
}

/* Badge prioritas */
.bg-prioritas-urgent {
  background-color: #dc3545 !important;
  color: #fff;
  font-size: 0.7rem;
  font-weight: 600;
}
.bg-prioritas-tinggi {
  background-color: #ffc107 !important;
  color: #212529;
  font-size: 0.7rem;
  font-weight: 600;
}
.bg-prioritas-normal {
  background-color: #0d6efd !important;
  color: #fff;
  font-size: 0.7rem;
  font-weight: 600;
}
.bg-prioritas-rendah {
  background-color: #6c757d !important;
  color: #fff;
  font-size: 0.7rem;
  font-weight: 600;
}

/* Meta info */
.pengumuman-meta {
  font-size: 0.85rem;
  line-height: 1.6;
}

/* Form search */
form .form-control, form .form-select {
  border-radius: 10px;
  border-color: #dcdcdc;
  box-shadow: none;
  transition: all .2s ease;
}
form .form-control:focus, form .form-select:focus {
  border-color: var(--green);
  box-shadow: 0 0 0 0.2rem rgba(8, 77, 54, 0.1);
}

/* Fade Animation */
.fade-section {
  opacity: 0;
  transform: translateY(30px);
  transition: opacity .8s, transform .8s;
}
.fade-section.visible {
  opacity: 1;
  transform: translateY(0);
}

/* Card text cuplikan */
.card-text {
  color: #6c757d !important;
  line-height: 1.6;
}

/* Responsive */
@media (max-width: 768px) {
  .pengumuman-title {
    font-size: 1rem;
  }
  .hero-contact {
    height: 35vh;
  }
}
</style>


<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.1 });

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