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

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

// ====== WHERE CLAUSE ======
// Tampilkan dokumen yang published DAN public
$where = ["d.status = 'published'", "d.visibility = 'public'"];
$params = [];

if ($search !== '') {
  $where[] = "(d.title LIKE ? OR d.unit_owner LIKE ?)";
  $params[] = "%$search%";
  $params[] = "%$search%";
}
if ($category_filter !== '') {
  $where[] = "d.category = ?";
  $params[] = $category_filter;
}

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

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

// Query dokumen langsung dari tabel documents (tanpa document_versions)
$stmt = $pdo->prepare("
  SELECT 
    d.id, 
    d.title, 
    d.slug,
    d.category, 
    d.unit_owner, 
    d.file_path,
    d.file_name_original,
    d.file_size,
    d.effective_date,
    d.notes,
    d.created_at,
    d.updated_at,
    u.full_name AS author
  FROM documents d
  LEFT JOIN users u ON d.created_by = u.id
  $where_sql
  ORDER BY d.updated_at DESC
  LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$docs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Ambil semua kategori unik untuk filter (hanya yang published & public)
$stmt_cats = $pdo->query("
  SELECT DISTINCT category 
  FROM documents 
  WHERE status = 'published' AND visibility = 'public'
  ORDER BY category ASC
");
$categories = $stmt_cats->fetchAll(PDO::FETCH_COLUMN);

// Hitung statistik untuk ditampilkan
$stmt_stats = $pdo->query("
  SELECT 
    COUNT(*) as total,
    COUNT(DISTINCT category) as total_categories
  FROM documents 
  WHERE status = 'published' AND visibility = 'public'
");
$stats = $stmt_stats->fetch(PDO::FETCH_ASSOC);

// ====== META ======
$page_title = "Dokumen Mutu | $site_name";
$page_description = "Daftar dokumen mutu Lembaga Penjaminan Mutu (LPM) STID Sirnarasa — mencakup standar, pedoman, dan laporan SPMI & SPME.";
$page_url = base_url('dokumen.php');

include __DIR__ . '/includes/header.php';
?>
<!-- HERO -->
<section class="hero-docs 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">Dokumen Mutu</h1>
    <p class="text-light small">Standar, pedoman, dan laporan mutu Universitas Riyadlul Ulum</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 dokumen..." value="<?= e($search); ?>">
      </div>
      <div class="col-md-3">
        <select name="category" class="form-select">
          <option value="">Semua Kategori</option>
          <?php foreach ($categories as $cat): ?>
            <option value="<?= e($cat); ?>" <?= $category_filter == $cat ? 'selected' : ''; ?>>
              <?= e(ucwords(str_replace('_', ' ', $cat))); ?>
            </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>

  <!-- DOKUMEN LIST -->
  <div class="row g-4">
    <?php if ($docs): ?>
      <?php foreach ($docs as $doc): ?>
        <div class="col-md-4 fade-section">
          <div class="card border-0 shadow-sm h-100 doc-card">
            <div class="card-body d-flex flex-column">
              <h5 class="fw-semibold mb-2 text-success"><?= e($doc['title']); ?></h5>
              <p class="small text-muted mb-2">
                <i class="fa fa-folder-open me-1 text-success"></i> <?= e(ucwords(str_replace('_', ' ', $doc['category']))); ?><br>
                <i class="fa fa-code-branch me-1 text-success"></i> Versi <?= e($doc['version_number'] ?? '-'); ?>
              </p>
              <p class="small text-secondary flex-grow-1">
                Pemilik: <?= e($doc['unit_owner'] ?: '-'); ?><br>
                Diperbarui: <?= indoDate(substr($doc['updated_at'], 0, 10)); ?>
              </p>

              <?php if (!empty($doc['file_path'])): ?>
                <a href="<?= base_url(e($doc['file_path'])); ?>" target="_blank" class="btn btn-outline-success mt-auto">
                  <i class="fa fa-download me-1"></i> Unduh
                </a>
              <?php else: ?>
                <button class="btn btn-outline-secondary mt-auto" disabled><i class="fa fa-ban me-1"></i> Tidak tersedia</button>
              <?php endif; ?>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    <?php else: ?>
      <p class="text-center text-muted py-4">Tidak ada dokumen 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); ?>&category=<?= urlencode($category_filter); ?>&page=<?= $i; ?>"><?= $i; ?></a>
          </li>
        <?php endfor; ?>
      </ul>
    </nav>
  <?php endif; ?>

</div>

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

<!-- ===== CUSTOM STYLE ===== -->
<style>
.hero-docs {
  height: 40vh;
  background: linear-gradient(120deg, var(--green) 0%, var(--brown) 100%);
  position: relative;
  padding-top: 4rem;
}
.hero-docs .overlay {
  position: absolute;
  inset: 0;
  background: rgba(0,0,0,0.45);
}

.doc-card {
  border-radius: 12px;
  transition: transform .3s ease, box-shadow .3s ease;
}
.doc-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0,0,0,.15);
}

/* 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>

<!-- ===== FADE ANIMATION SCRIPT ===== -->
<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>
