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

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

// ===== QUERY BUILDER =====
$where = [];
$params = [];

if ($type_filter !== '') {
  $where[] = "type = ?";
  $params[] = $type_filter;
}
if ($search !== '') {
  $where[] = "(program_studi LIKE ? OR institution_name LIKE ? OR decision_number LIKE ?)";
  $params[] = "%$search%";
  $params[] = "%$search%";
  $params[] = "%$search%";
}

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

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

// ===== AMBIL DATA =====
$stmt = $pdo->prepare("
  SELECT id, type, institution_name, program_studi, strata, decision_number, rating, 
         valid_from, valid_until, accreditation_body, document_file
  FROM accreditation
  $where_sql
  ORDER BY valid_until DESC
  LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$accreditations = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ===== Statistik akreditasi =====
$stmt_stats = $pdo->query("
  SELECT rating, COUNT(*) as total FROM accreditation 
  WHERE rating IS NOT NULL AND rating != '' 
  GROUP BY rating ORDER BY total DESC
");
$stats = $stmt_stats->fetchAll(PDO::FETCH_ASSOC);

// Hitung status masa berlaku
$now = new DateTime();
foreach ($accreditations as &$a) {
  if ($a['valid_until']) {
    $valid_until = new DateTime($a['valid_until']);
    $days_left = $now->diff($valid_until)->days;
    $is_expired = $valid_until < $now;
    $a['status_color'] = $is_expired ? 'danger' : ($days_left <= 90 ? 'warning' : 'success');
    $a['status_label'] = $is_expired ? 'Kadaluarsa' : ($days_left <= 90 ? 'Segera Habis' : 'Aktif');
  } else {
    $a['status_color'] = 'secondary';
    $a['status_label'] = 'Tidak diketahui';
  }
}
unset($a);

// ===== META =====
$page_title = "SPME (Akreditasi) | $site_name";
$page_description = "Daftar akreditasi universitas dan program studi Universitas Riyadlul Ulum Tasikmalaya lengkap dengan status masa berlaku dan statistik nilai akreditasi.";
$page_url = base_url('spme.php');

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

<!-- HERO -->
<section class="hero-spme 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">Sistem Penjaminan Mutu Eksternal (SPME)</h1>
    <p class="text-light small">Data Akreditasi Universitas dan Program Studi Universitas Riyadlul Ulum</p>
  </div>
</section>

<div class="container my-5">

  <!-- STATISTIK AKREDITASI -->
  <div class="card shadow-sm mb-5 p-4 fade-section">
    <h5 class="fw-bold text-success mb-3"><i class="fa fa-chart-bar me-2"></i>Statistik Akreditasi</h5>
    <div class="row align-items-center">
      <div class="col-md-7">
        <canvas id="chartAkreditasi" height="180"></canvas>
      </div>
      <div class="col-md-5">
        <ul class="list-group small">
          <?php foreach ($stats as $s): ?>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <span><?= e($s['rating']); ?></span>
              <span class="badge bg-success"><?= e($s['total']); ?></span>
            </li>
          <?php endforeach; ?>
          <?php if (!$stats): ?>
            <li class="list-group-item text-muted text-center">Belum ada data akreditasi</li>
          <?php endif; ?>
        </ul>
      </div>
    </div>
  </div>

  <!-- 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 nama prodi atau lembaga..." value="<?= e($search); ?>">
      </div>
      <div class="col-md-3">
        <select name="type" class="form-select">
          <option value="">Semua Jenis</option>
          <option value="universitas" <?= $type_filter === 'universitas' ? 'selected' : ''; ?>>Universitas</option>
          <option value="prodi" <?= $type_filter === 'prodi' ? 'selected' : ''; ?>>Program Studi</option>
        </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>

  <!-- TABEL AKREDITASI -->
  <div class="table-responsive fade-section">
    <table class="table table-hover align-middle shadow-sm bg-white rounded-3 overflow-hidden">
      <thead class="table-success text-dark">
          <tr>
            <th scope="col">No</th>
            <th scope="col">Jenis</th>
            <th scope="col">Nama / Program Studi</th>
            <th scope="col">Strata</th>
            <th scope="col">Lembaga</th>
            <th scope="col">Nomor SK</th>
            <th scope="col">Nilai</th>
            <th scope="col">Berlaku Hingga</th>
            <th scope="col">Status</th>
            <th scope="col" class="text-center">Dokumen</th>
            <th scope="col" class="text-center">Detail</th>
          </tr>
        </thead>
      <tbody>
        <?php if ($accreditations): ?>
          <?php foreach ($accreditations as $i => $a): ?>
            <tr>
              <td><?= ($offset + $i + 1); ?></td>
              <td><span class="badge bg-success"><?= e(ucfirst($a['type'])); ?></span></td>
              <td><?= e($a['type'] === 'universitas' ? $a['institution_name'] : $a['program_studi']); ?></td>
              <td><?= e($a['strata'] ?? '-'); ?></td>
              <td><?= e($a['accreditation_body'] ?? '-'); ?></td>
              <td><?= e($a['decision_number'] ?? '-'); ?></td>
              <td><strong><?= e($a['rating'] ?? '-'); ?></strong></td>
              <td><?= e(indoDate($a['valid_until'])); ?></td>
              <td>
                <span class="badge bg-<?= e($a['status_color']); ?>">
                  <?= e($a['status_label']); ?>
                </span>
              </td>
              <td class="text-center">
                  <?php if (!empty($a['document_file'])): ?>
                    <a href="<?= base_url('uploads/akreditasi/' . e($a['document_file'])); ?>" target="_blank" class="btn btn-sm btn-outline-success" title="Unduh Sertifikat">
                      <i class="fa fa-download"></i>
                    </a>
                  <?php else: ?>
                    <span class="text-muted"><i class="fa fa-ban"></i></span>
                  <?php endif; ?>
                </td>
                
                <td class="text-center">
                  <a href="<?= base_url('spme_detail.php?id=' . e($a['id'])); ?>" class="btn btn-sm btn-outline-primary" title="Lihat Detail">
                    <i class="fa fa-info-circle"></i>
                  </a>
                </td>
            </tr>
          <?php endforeach; ?>
        <?php else: ?>
          <tr><td colspan="10" class="text-center text-muted py-4">Tidak ada data akreditasi ditemukan.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- PAGINATION -->
  <?php if ($total_pages > 1): ?>
    <nav aria-label="Pagination" class="mt-4">
      <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); ?>&type=<?= urlencode($type_filter); ?>&page=<?= $i; ?>"><?= $i; ?></a>
          </li>
        <?php endfor; ?>
      </ul>
    </nav>
  <?php endif; ?>

</div>

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

<!-- ===== CUSTOM STYLES ===== -->
<style>
.hero-spme {
  height: 40vh;
  background: linear-gradient(120deg, var(--green) 0%, var(--brown) 100%);
  position: relative;
  padding-top: 4rem;
}
.hero-spme .overlay {
  position: absolute;
  inset: 0;
  background: rgba(0,0,0,0.45);
}
.table tbody tr:hover {
  background-color: #f7fdf9;
}
.badge.bg-warning { color: #000; }
.fade-section { opacity: 0; transform: translateY(30px); transition: opacity .8s, transform .8s; }
.fade-section.visible { opacity: 1; transform: translateY(0); }
</style>

<!-- ===== SCRIPT ===== -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", () => {
  // Fade in animation
  const fadeSections = document.querySelectorAll(".fade-section");
  const observer = new IntersectionObserver(entries => {
    entries.forEach(e => { if (e.isIntersecting) e.target.classList.add("visible"); });
  }, { threshold: 0.2 });
  fadeSections.forEach(s => observer.observe(s));

  // Chart Akreditasi
  const ctx = document.getElementById("chartAkreditasi");
  const chartData = {
    labels: <?= json_encode(array_column($stats, 'rating')); ?>,
    datasets: [{
      label: 'Jumlah Prodi',
      data: <?= json_encode(array_column($stats, 'total')); ?>,
      backgroundColor: ['#2E8B57', '#CC9933', '#FFA500', '#B22222', '#6A5ACD']
    }]
  };
  new Chart(ctx, {
    type: 'bar',
    data: chartData,
    options: {
      responsive: true,
      plugins: { legend: { display: false } },
      scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }
    }
  });
});
</script>
