<?php
require_once __DIR__ . '/../config/secure_bootstrap.php';
include __DIR__ . '/includes/header.php';

// Helper
if (!function_exists('e')) {
  function e($v) { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
}

// ================== PENCARIAN + PAGINASI ==================
$search = trim($_GET['search'] ?? '');
$status_filter = $_GET['status'] ?? '';
$per_page = 10;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $per_page;

$params = [];
$sql_from = "FROM pengumuman p";
$where = [];

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

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

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

$total_stmt = $pdo->prepare("SELECT COUNT(*) $sql_from $where_sql");
$total_stmt->execute($params);
$total = (int)$total_stmt->fetchColumn();
$total_pages = $total > 0 ? ceil($total / $per_page) : 1;

$stmt = $pdo->prepare("
  SELECT p.*
  $sql_from
  $where_sql
  ORDER BY 
    FIELD(p.prioritas, 'urgent','tinggi','normal','rendah') ASC,
    p.tanggal_mulai DESC
  LIMIT $per_page OFFSET $offset
");
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Direktori lampiran
$lampiran_dir = __DIR__ . '/../uploads/pengumuman/';
if (!is_dir($lampiran_dir)) mkdir($lampiran_dir, 0755, true);

// Fungsi hapus file
function delete_file_lampiran($dir, $filename) {
  if ($filename && file_exists($dir . $filename)) {
    @unlink($dir . $filename);
  }
}
?>

<div class="container-fluid">
  <div class="card shadow p-3 mb-4">
    <h4 class="mb-3">
      <i class="fa-solid fa-bullhorn text-success me-2"></i>Manajemen Pengumuman
    </h4>

    <div class="d-flex justify-content-between flex-wrap mb-3 gap-2">
      <!-- Search + filter status -->
      <div class="d-flex flex-wrap gap-2">
        <div class="input-group">
          <input type="text" id="search" class="form-control" placeholder="Cari pengumuman..."
                 value="<?= e($search) ?>">
          <button class="btn btn-outline-success" id="btn-search" type="button" title="Cari">
            <i class="fa-solid fa-magnifying-glass"></i>
          </button>
          <?php if ($search !== '' || $status_filter !== ''): ?>
            <button class="btn btn-outline-secondary" id="btn-reset" type="button" title="Reset">
              <i class="fa-solid fa-rotate-left"></i>
            </button>
          <?php endif; ?>
        </div>

        <select id="status_filter" class="form-select w-auto">
          <option value="">Semua Status</option>
          <option value="active"   <?= $status_filter==='active'   ? 'selected' : '' ?>>Active</option>
          <option value="inactive" <?= $status_filter==='inactive' ? 'selected' : '' ?>>Inactive</option>
          <option value="expired"  <?= $status_filter==='expired'  ? 'selected' : '' ?>>Expired</option>
        </select>
      </div>

      <!-- Tombol tambah -->
      <a href="pengumuman_form.php?mode=add" class="btn btn-success">
        <i class="fa-solid fa-plus me-1"></i> Tambah Pengumuman
      </a>
    </div>

    <!-- Table -->
    <div class="table-responsive shadow-sm rounded">
      <table class="table table-bordered align-middle">
        <thead class="table-success text-center">
          <tr>
            <th>No</th>
            <th>Judul</th>
            <th>Periode</th>
            <th>Prioritas</th>
            <th>Status</th>
            <th>Sasaran</th>
            <th>Lampiran</th>
            <th>Views</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($rows): foreach ($rows as $i => $row): ?>
          <tr>
            <td class="text-center"><?= $offset + $i + 1 ?></td>
            <td><?= e($row['judul']) ?></td>
            <td>
              <?= e($row['tanggal_mulai']) ?> s.d <?= e($row['tanggal_selesai']) ?>
            </td>
            <td class="text-center">
              <span class="badge bg-prioritas-<?= e($row['prioritas']) ?>">
                <?= strtoupper($row['prioritas']) ?>
              </span>
            </td>
            <td class="text-center">
              <span class="badge bg-status-<?= e($row['status']) ?>">
                <?= strtoupper($row['status']) ?>
              </span>
            </td>
            <td><?= e($row['target_audience']) ?></td>
            <td class="text-center">
              <?php if ($row['file_lampiran']): ?>
                <a href="../uploads/pengumuman/<?= e($row['file_lampiran']) ?>" 
                   target="_blank" class="btn btn-sm btn-outline-primary">
                  <i class="fa-solid fa-paperclip"></i>
                </a>
              <?php else: ?>
                <span class="text-muted">-</span>
              <?php endif; ?>
            </td>
            <td class="text-center"><?= (int)$row['views'] ?></td>
            <td class="text-center">
              <button class="btn btn-sm btn-info text-white detail-btn" type="button"
                      data-row='<?= htmlspecialchars(json_encode($row), ENT_QUOTES, "UTF-8") ?>'
                      title="Detail">
                <i class="fa-solid fa-circle-info"></i>
              </button>

              <a href="pengumuman_form.php?mode=edit&id=<?= e($row['id']) ?>"
                 class="btn btn-sm btn-primary" title="Edit">
                <i class="fa-solid fa-pen-to-square"></i>
              </a>

              <button class="btn btn-sm btn-danger delete-btn" type="button"
                      data-id="<?= e($row['id']) ?>" title="Hapus">
                <i class="fa-solid fa-trash"></i>
              </button>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="9" class="text-center text-muted">Belum ada pengumuman.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <!-- Pagination -->
    <nav>
      <ul class="pagination justify-content-center">
        <?php for ($p = 1; $p <= $total_pages; $p++): ?>
          <li class="page-item <?= $p == $page ? 'active' : '' ?>">
            <a class="page-link" href="?search=<?= urlencode($search) ?>&status=<?= urlencode($status_filter) ?>&page=<?= $p ?>">
              <?= $p ?>
            </a>
          </li>
        <?php endfor; ?>
      </ul>
    </nav>
  </div>
</div>

<!-- Modal Detail -->
<div class="modal fade" id="detailModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title">
          <i class="fa-solid fa-circle-info me-2"></i>Detail Pengumuman
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="detail-content"></div>
    </div>
  </div>
</div>


<?php
// ================== PROSES CRUD ==================

/* ===== TAMBAH ===== */
if (isset($_POST['add'])) {

  // Upload lampiran
  $lampiran_name = null;
  if (!empty($_FILES['file_lampiran']['name'])) {
    $allowed = ['pdf','doc','docx'];
    $ext  = strtolower(pathinfo($_FILES['file_lampiran']['name'], PATHINFO_EXTENSION));
    $size = $_FILES['file_lampiran']['size'];

    if (!in_array($ext, $allowed)) {
      echo "<script>Swal.fire('Gagal', 'Format lampiran tidak diizinkan!', 'error');</script>";
      exit;
    }
    if ($size > 5 * 1024 * 1024) {
      echo "<script>Swal.fire('Gagal', 'Lampiran maksimal 5MB!', 'error');</script>";
      exit;
    }

    $lampiran_name = time() . '_lamp_' . uniqid() . '.' . $ext;
    move_uploaded_file($_FILES['file_lampiran']['tmp_name'], $lampiran_dir . $lampiran_name);
  }

  // buat slug sederhana
  $judul = $_POST['judul'] ?? '';
  $slug = strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $judul), '-'));

  $stmt = $pdo->prepare("
    INSERT INTO pengumuman 
      (judul, slug, isi, file_lampiran, tanggal_mulai, tanggal_selesai, prioritas, target_audience, status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  ");
  $stmt->execute([
    $judul,
    $slug,
    $_POST['isi'] ?? '',
    $lampiran_name,
    $_POST['tanggal_mulai'] ?? date('Y-m-d'),
    $_POST['tanggal_selesai'] ?? date('Y-m-d'),
    $_POST['prioritas'] ?? 'normal',
    $_POST['target_audience'] ?: 'umum',
    $_POST['status'] ?? 'active',
  ]);

  echo "<script>Swal.fire('Berhasil', 'Pengumuman berhasil ditambahkan', 'success')
        .then(()=>location.href='pengumuman.php');</script>";
  exit;
}

/* ===== UPDATE ===== */
if (isset($_POST['update'])) {
  $id = (int)($_POST['edit_id'] ?? 0);
  if (!$id) exit;

  // ambil lampiran lama
  $stmt_old = $pdo->prepare("SELECT file_lampiran FROM pengumuman WHERE id=?");
  $stmt_old->execute([$id]);
  $old = $stmt_old->fetch(PDO::FETCH_ASSOC);
  $lampiran_old = $old['file_lampiran'] ?? null;
  $lampiran_name = $lampiran_old;

  // upload lampiran baru jika ada
  if (!empty($_FILES['edit_file_lampiran']['name'])) {

    delete_file_lampiran($lampiran_dir, $lampiran_old);

    $allowed = ['pdf','doc','docx'];
    $ext  = strtolower(pathinfo($_FILES['edit_file_lampiran']['name'], PATHINFO_EXTENSION));
    $size = $_FILES['edit_file_lampiran']['size'];

    if (!in_array($ext, $allowed)) {
      echo "<script>Swal.fire('Gagal', 'Format lampiran tidak diizinkan!', 'error');</script>";
      exit;
    }
    if ($size > 5 * 1024 * 1024) {
      echo "<script>Swal.fire('Gagal', 'Lampiran maksimal 5MB!', 'error');</script>";
      exit;
    }

    $lampiran_name = time() . '_lamp_' . uniqid() . '.' . $ext;
    move_uploaded_file($_FILES['edit_file_lampiran']['tmp_name'], $lampiran_dir . $lampiran_name);
  }

  $judul = $_POST['edit_judul'] ?? '';
  $slug  = strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $judul), '-'));

  $stmt = $pdo->prepare("
    UPDATE pengumuman
    SET judul=?, slug=?, isi=?, file_lampiran=?,
        tanggal_mulai=?, tanggal_selesai=?,
        prioritas=?, target_audience=?, status=?
    WHERE id=?
  ");
  $stmt->execute([
    $judul,
    $slug,
    $_POST['edit_isi'] ?? '',
    $lampiran_name,
    $_POST['edit_tanggal_mulai'] ?? date('Y-m-d'),
    $_POST['edit_tanggal_selesai'] ?? date('Y-m-d'),
    $_POST['edit_prioritas'] ?? 'normal',
    $_POST['edit_target_audience'] ?: 'umum',
    $_POST['edit_status'] ?? 'active',
    $id
  ]);

  echo "<script>Swal.fire('Berhasil', 'Pengumuman diperbarui', 'success')
        .then(()=>location.href='pengumuman.php');</script>";
  exit;
}

/* ===== HAPUS ===== */
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];

  if ($id) {
    $stmt = $pdo->prepare("SELECT file_lampiran FROM pengumuman WHERE id=?");
    $stmt->execute([$id]);
    $file = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($file && $file['file_lampiran']) {
      delete_file_lampiran($lampiran_dir, $file['file_lampiran']);
    }

    $stmt = $pdo->prepare("DELETE FROM pengumuman WHERE id=?");
    $stmt->execute([$id]);
  }

  echo "<script>Swal.fire('Dihapus', 'Pengumuman berhasil dihapus', 'success')
        .then(()=>location.href='pengumuman.php');</script>";
  exit;
}
?>

<style>
.bg-prioritas-rendah  { background-color: #6c757d !important; }
.bg-prioritas-normal  { background-color: #198754 !important; }
.bg-prioritas-tinggi  { background-color: #fd7e14 !important; }
.bg-prioritas-urgent  { background-color: #dc3545 !important; }

.bg-status-active   { background-color: #198754 !important; }
.bg-status-inactive { background-color: #6c757d !important; }
.bg-status-expired  { background-color: #dc3545 !important; }
</style>


<script>
document.addEventListener('DOMContentLoaded', () => {
  const qInput = document.getElementById('search');
  const btnSearch = document.getElementById('btn-search');
  const statusSel = document.getElementById('status_filter');

  const goSearch = () => {
    const q = qInput ? qInput.value.trim() : '';
    const st = statusSel ? statusSel.value : '';
    const url = new URL(window.location.href);
    url.searchParams.set('search', q);
    url.searchParams.set('status', st);
    url.searchParams.delete('page');
    window.location = url.toString();
  };

  if (btnSearch && qInput) {
    btnSearch.addEventListener('click', goSearch);
    qInput.addEventListener('keypress', e => {
      if (e.key === 'Enter') {
        e.preventDefault();
        goSearch();
      }
    });
  }

  if (statusSel) {
    statusSel.addEventListener('change', goSearch);
  }

  const resetBtn = document.getElementById('btn-reset');
  if (resetBtn) {
    resetBtn.addEventListener('click', () => {
      window.location = 'pengumuman.php';
    });
  }

  // DETAIL
  document.querySelectorAll('.detail-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const raw = btn.getAttribute('data-row') || '{}';
      let data = {};

      try {
        data = JSON.parse(raw);
      } catch (e) {
        Swal.fire('Error', 'Data detail tidak valid.', 'error');
        return;
      }

      const s = v => {
        if (v === null || v === undefined) return '-';
        return String(v)
          .replace(/&/g,'&amp;')
          .replace(/</g,'&lt;')
          .replace(/>/g,'&gt;')
          .replace(/"/g,'&quot;');
      };

      let lampiranHtml = '-';
      if (data.file_lampiran) {
        lampiranHtml = `<a href="../uploads/pengumuman/${encodeURIComponent(data.file_lampiran)}" target="_blank">
                          ${s(data.file_lampiran)}
                        </a>`;
      }

      const html = `
        <table class="table table-bordered">
          <tr><th style="width:25%">Judul</th><td>${s(data.judul)}</td></tr>
          <tr><th>Isi</th><td>${s(data.isi)}</td></tr>
          <tr><th>Periode</th><td>${s(data.tanggal_mulai)} s.d ${s(data.tanggal_selesai)}</td></tr>
          <tr><th>Prioritas</th><td>${s(data.prioritas)}</td></tr>
          <tr><th>Status</th><td>${s(data.status)}</td></tr>
          <tr><th>Sasaran</th><td>${s(data.target_audience)}</td></tr>
          <tr><th>Lampiran</th><td>${lampiranHtml}</td></tr>
          <tr><th>Views</th><td>${s(data.views)}</td></tr>
        </table>
      `;

      document.getElementById('detail-content').innerHTML = html;
      new bootstrap.Modal(document.getElementById('detailModal')).show();
    });
  });

  // DELETE
  document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      Swal.fire({
        title: 'Hapus Pengumuman?',
        text: 'Data akan dihapus permanen!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Ya, hapus!',
        cancelButtonText: 'Batal'
      }).then(result => {
        if (result.isConfirmed) {
          window.location = 'pengumuman.php?delete=' + encodeURIComponent(btn.dataset.id);
        }
      });
    });
  });
});
</script>

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