<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

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

// ====== AMBIL SLUG ======
$slug = $_GET['slug'] ?? '';
$slug = trim($slug);

// Jika tidak ada slug, redirect ke list
if ($slug === '') {
    header('Location: pengumuman.php');
    exit;
}

// ====== QUERY DETAIL ======
$sql = "
  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 p.slug = ?
  LIMIT 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute([$slug]);
$pengumuman = $stmt->fetch(PDO::FETCH_ASSOC);

// Jika tidak ketemu
if (!$pengumuman) {
  $page_title       = "Pengumuman tidak ditemukan | $site_name";
  $page_description = "Pengumuman tidak ditemukan.";
  $page_url         = base_url('pengumuman_detail.php');
  include __DIR__ . '/includes/header.php';
  ?>

  <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-0">Pengumuman tidak ditemukan</p>
    </div>
  </section>

  <div class="container my-5">
    <div class="text-center py-5">
      <i class="fa fa-exclamation-triangle fa-4x text-muted mb-3"></i>
      <h4 class="text-muted mb-2">Pengumuman tidak ditemukan</h4>
      <p class="text-muted">Pengumuman yang Anda cari mungkin sudah dihapus atau slug tidak valid.</p>
      <a href="pengumuman.php" class="btn btn-success mt-2">
        <i class="fa fa-arrow-left me-1"></i> Kembali ke daftar pengumuman
      </a>
    </div>
  </div>

  <?php
  include __DIR__ . '/includes/footer.php';
  exit;
}

// ====== UPDATE VIEW COUNT ======
$update = $pdo->prepare("UPDATE pengumuman SET views = views + 1 WHERE id = ?");
$update->execute([$pengumuman['id']]);

// ====== META ======
$page_title       = $pengumuman['judul'] . " | $site_name";
$page_description = mb_strimwidth(strip_tags($pengumuman['isi']), 0, 160, '...');
$page_url         = base_url('pengumuman_detail.php?slug=' . urlencode($pengumuman['slug']));

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

// Mapping prioritas
$priority_colors = [
  'urgent' => 'badge-prio-urgent',
  'tinggi' => 'badge-prio-tinggi',
  'normal' => 'badge-prio-normal',
  'rendah' => 'badge-prio-rendah'
];
$priority_labels = [
  'urgent' => 'URGENT',
  'tinggi' => 'PENTING',
  'normal' => 'NORMAL',
  'rendah' => 'INFO'
];

$prio_class = $priority_colors[$pengumuman['prioritas']] ?? 'badge-prio-normal';
$prio_label = $priority_labels[$pengumuman['prioritas']] ?? 'NORMAL';

// Share URL
$share_url  = base_url('pengumuman_detail.php?slug=' . urlencode($pengumuman['slug']));
$share_text = $pengumuman['judul'];
?>

<!-- HERO DETAIL -->
<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">
    <span class="badge px-3 py-2 mb-3 <?= $prio_class ?>">
      <i class="fa fa-bullhorn me-1"></i><?= $prio_label ?>
    </span>

    <h1 class="fw-bold display-6 mb-3">
      <?= e($pengumuman['judul']) ?>
    </h1>

    <div class="d-flex flex-wrap justify-content-center gap-3 small text-light">
      <div>
        <i class="fa fa-calendar me-1"></i>
        <span>
          <?= indoDate($pengumuman['tanggal_mulai']) ?>
          <?php if ($pengumuman['tanggal_mulai'] != $pengumuman['tanggal_selesai']): ?>
            s/d <?= indoDate($pengumuman['tanggal_selesai']) ?>
          <?php endif; ?>
        </span>
      </div>
      <div>
        <i class="fa fa-users me-1"></i>
        <span><?= e(ucwords(str_replace('_', ' ', $pengumuman['target_audience']))) ?></span>
      </div>
      <div>
        <i class="fa fa-eye me-1"></i>
        <span><?= (int)$pengumuman['views'] ?> kali dibaca</span>
      </div>
    </div>
  </div>
</section>

<div class="container my-5">
  <div class="row g-4">

    <!-- KONTEN UTAMA -->
    <div class="col-lg-8 fade-section">
      <div class="card border-0 shadow-sm rounded-4 mb-4">
        <div class="card-body p-4 p-md-5">

          <!-- Isi Pengumuman -->
          <div class="content-text mb-4">
<?php
$content = $pengumuman['isi'];

// whitelist tag aman
$content = strip_tags(
    $content,
    '<p><ul><ol><li><strong><em><br><b><i><h1><h2><h3><h4><h5><a>'
);

// perbaiki link agar clickable + aman
$content = preg_replace_callback(
    '/<a\s+href="([^"]+)">(.*?)<\/a>/i',
    function ($matches) {
        $url = htmlspecialchars($matches[1], ENT_QUOTES, 'UTF-8');
        $text = $matches[2];

        return '<a href="' . $url . '" target="_blank" rel="noopener noreferrer">' . $text . '</a>';
    },
    $content
);

// tampilkan isi
echo $content;
?>
</div>

          <!-- Lampiran -->
            <?php if (!empty($pengumuman['file_lampiran'])): 
              // Path dari admin: uploads/pengumuman/namafile.ext
              $file_path = base_url('uploads/pengumuman/' . $pengumuman['file_lampiran']); 
              $file_ext  = strtolower(pathinfo($pengumuman['file_lampiran'], PATHINFO_EXTENSION));
            ?>

            <div class="mt-4">
              <h5 class="text-success mb-3">
                <i class="fa fa-paperclip me-2"></i>File Lampiran
              </h5>

              <?php if ($file_ext === 'pdf'): ?>
                <!-- PREVIEW PDF -->
                <div class="document-preview mb-3">
                  <div class="pdf-preview-container border rounded-4 overflow-hidden">
                    <iframe src="<?= $file_path ?>" class="pdf-iframe" frameborder="0"></iframe>
                    <div class="pdf-overlay">
                      <button class="btn btn-light btn-sm shadow-sm" onclick="toggleFullPreview('<?= $file_path ?>')">
                        <i class="fa fa-expand"></i> Lihat Penuh
                      </button>
                    </div>
                  </div>
                </div>
              <?php else: ?>
                <!-- PREVIEW LINK (mis. Google Sheet / Docs) -->
                <div class="p-3 rounded-3 bg-light border d-flex align-items-start mb-3">
                  <div class="me-2 mt-1">
                    <i class="fa fa-link text-success fs-4"></i>
                  </div>
                  <div class="flex-grow-1">
                    <div class="small text-muted mb-1">Link Lampiran</div>
                    <a href="<?= $file_path ?>" target="_blank" class="text-decoration-none">
                      <?= htmlspecialchars($file_path) ?>
                    </a>
                  </div>
                </div>
              <?php endif; ?>

              <a href="<?= $file_path ?>" target="_blank" class="btn btn-success">
                <i class="fa fa-download me-2"></i>Download File
              </a>
            </div>
          <?php endif; ?>

          <!-- Share -->
<div class="mt-5 pt-4 border-top">
  <h6 class="mb-3 text-muted">Bagikan Pengumuman:</h6>
  <div class="d-flex flex-wrap gap-2">
    <a href="https://wa.me/?text=<?= urlencode($share_text . ' - ' . $share_url) ?>"
       target="_blank" class="btn btn-success btn-sm">
      <i class="bi bi-whatsapp me-1"></i>WhatsApp
    </a>
    <a href="https://t.me/share/url?url=<?= urlencode($share_url) ?>&text=<?= urlencode($share_text) ?>"
       target="_blank" class="btn btn-info btn-sm text-white">
      <i class="bi bi-telegram me-1"></i>Telegram
    </a>
    <button type="button" onclick="copyToClipboard('<?= $share_url ?>')" 
            class="btn btn-outline-secondary btn-sm">
      <i class="bi bi-link-45deg me-1"></i>Copy Link
    </button>
  </div>
</div>


        </div>
      </div>

      <div class="text-center mt-3">
        <a href="pengumuman.php" class="btn btn-outline-success px-4">
          <i class="fa fa-arrow-left me-1"></i>Kembali ke Daftar Pengumuman
        </a>
      </div>
    </div>

    <!-- SIDEBAR: Pengumuman Lain -->
    <div class="col-lg-4 fade-section">
      <div class="sticky-sidebar">

        <div class="card border-0 shadow-sm rounded-4 mb-4">
          <div class="card-header bg-white border-0 pb-0">
            <h6 class="fw-bold mb-0">
              <i class="fa fa-bullhorn me-2 text-success"></i>Pengumuman Lainnya
            </h6>
          </div>
          <div class="card-body p-0 mt-2">

            <?php
            $stmt_other = $pdo->prepare("
              SELECT id, judul, slug, prioritas, tanggal_mulai
              FROM pengumuman
              WHERE status IN ('active','expired')
                AND id != ?
              ORDER BY 
                CASE status
                  WHEN 'active' THEN 1
                  WHEN 'expired' THEN 2
                END,
                tanggal_mulai DESC
              LIMIT 5
            ");
            $stmt_other->execute([$pengumuman['id']]);
            $others = $stmt_other->fetchAll(PDO::FETCH_ASSOC);
            ?>

            <?php if ($others): ?>
              <?php foreach ($others as $o): 
                $cls = $priority_colors[$o['prioritas']] ?? 'badge-prio-normal';
              ?>
                <div class="sidebar-item border-bottom px-3 py-3">
                  <a href="pengumuman_detail.php?slug=<?= urlencode($o['slug']) ?>" 
                     class="text-decoration-none d-block">
                    <span class="badge <?= $cls ?> badge-sm mb-1">
                      <?= strtoupper($o['prioritas']) ?>
                    </span>
                    <h6 class="mb-1 text-dark text-truncate-2">
                      <?= e($o['judul']) ?>
                    </h6>
                    <div class="text-muted small">
                      <i class="fa fa-calendar me-1"></i>
                      <?= indoDate($o['tanggal_mulai']) ?>
                    </div>
                  </a>
                </div>
              <?php endforeach; ?>
            <?php else: ?>
              <div class="p-4 text-center text-muted">
                <i class="fa fa-inbox fa-2x d-block mb-2"></i>
                <small>Belum ada pengumuman lainnya</small>
              </div>
            <?php endif; ?>

          </div>
          <div class="card-footer bg-white text-center border-0 pt-0 pb-3">
            <a href="pengumuman.php" class="btn btn-sm btn-outline-success">
              Lihat Semua Pengumuman
            </a>
          </div>
        </div>

        <!-- Widget CTA kecil -->
        <div class="card border-0 shadow-sm rounded-4">
          <div class="card-body text-center p-4">
            <i class="fa fa-question-circle fa-3x text-success mb-3"></i>
            <h6 class="mb-2">Butuh Informasi Lebih?</h6>
            <p class="text-muted small mb-3">
              Hubungi LPM UNIRU untuk informasi lebih lanjut.
            </p>
            <a href="kontak.php" class="btn btn-success btn-sm">
              <i class="fa fa-phone me-1"></i>Hubungi Kami
            </a>
          </div>
        </div>

      </div>
    </div>

  </div>
</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);
}

/* Badge prioritas detail */
.badge-prio-urgent {
  background-color: #dc3545;
  color: #fff;
}
.badge-prio-tinggi {
  background-color: #ffc107;
  color: #212529;
}
.badge-prio-normal {
  background-color: #0d6efd;
  color: #fff;
}
.badge-prio-rendah {
  background-color: #6c757d;
  color: #fff;
}

.sticky-sidebar {
  position: sticky;
  top: 100px;
}

.sidebar-item {
  transition: background-color .2s ease;
}
.sidebar-item:hover {
  background-color: #f8f9fa;
}
.badge-sm {
  font-size: .7rem;
  padding: 0.25rem 0.5rem;
}
.text-truncate-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* PDF preview */
.pdf-preview-container {
  position: relative;
  width: 100%;
  height: 500px;
  background: #f8f9fa;
  overflow: hidden;
}
.pdf-iframe {
  width: 100%;
  height: 100%;
  border: none;
}
.pdf-overlay {
  position: absolute;
  bottom: 10px;
  right: 10px;
}

/* Fullscreen PDF */
.pdf-fullscreen {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.95);
  z-index: 9999;
  display: none;
  padding: 20px;
}
.pdf-fullscreen.active {
  display: block;
}
.pdf-fullscreen iframe {
  width: 100%;
  height: 100%;
  border: none;
}
.pdf-close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
}

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

@media (max-width: 991px) {
  .sticky-sidebar {
    position: static;
    top: 0;
    margin-top: 2rem;
  }
  .pdf-preview-container {
    height: 400px;
  }
}
@media (max-width: 576px) {
  .pdf-preview-container {
    height: 300px;
  }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
  // Fade
  const fadeSections = document.querySelectorAll('.fade-section');
  const observer = new IntersectionObserver(entries => {
    entries.forEach(e => {
      if (e.isIntersecting) e.target.classList.add('visible');
    });
  }, { threshold: 0.1 });
  fadeSections.forEach(s => observer.observe(s));

  // Full PDF preview
  window.toggleFullPreview = function (pdfUrl) {
    if (document.querySelector('.pdf-fullscreen')) return;

    const modal = document.createElement('div');
    modal.className = 'pdf-fullscreen active';
    modal.innerHTML = `
      <button class="btn btn-light pdf-close-btn">
        <i class="fa fa-times"></i> Tutup
      </button>
      <iframe src="${pdfUrl}" frameborder="0"></iframe>
    `;

    document.body.appendChild(modal);
    document.body.style.overflow = 'hidden';

    function closeModal() {
      modal.remove();
      document.body.style.overflow = '';
      document.removeEventListener('keydown', handleEscape);
    }
    function handleEscape(e) {
      if (e.key === 'Escape') closeModal();
    }

    document.addEventListener('keydown', handleEscape);
    modal.querySelector('.pdf-close-btn').addEventListener('click', closeModal);
  };

  // Copy to clipboard
  window.copyToClipboard = function (text) {
    navigator.clipboard.writeText(text).then(() => {
      const toast = document.createElement('div');
      toast.className = 'alert alert-success position-fixed';
      toast.style.cssText = `
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 260px;
      `;
      toast.innerHTML = `
        <i class="fa fa-check-circle me-1"></i>
        Link berhasil disalin!
      `;
      document.body.appendChild(toast);
      setTimeout(() => toast.remove(), 3000);
    }).catch(err => {
      console.error('Clipboard error:', err);
    });
  };
});
</script>
