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

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

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

$params = [];
$sql = "FROM activities a LEFT JOIN users u ON a.created_by = u.id";
$where = "";

if ($search !== '') {
  $where = " WHERE a.title LIKE ? OR a.description LIKE ? OR a.organizer LIKE ? OR a.location LIKE ?";
  $like = "%$search%";
  $params = [$like, $like, $like, $like];
}

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

$stmt = $pdo->prepare("SELECT a.*, u.full_name AS creator $sql $where ORDER BY a.date_start DESC LIMIT $per_page OFFSET $offset");
$stmt->execute($params);
$activities = $stmt->fetchAll(PDO::FETCH_ASSOC);

$upload_dir = __DIR__ . '/../uploads/kegiatan/';
?>

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

    <div class="d-flex justify-content-between flex-wrap mb-3 gap-2">
      <!-- Form search -->
      <div class="input-group w-auto">
        <input type="text" id="search" class="form-control" placeholder="Cari kegiatan..." 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 !== ''): ?>
          <button class="btn btn-outline-secondary" id="btn-reset" type="button" title="Reset pencarian">
            <i class="fa-solid fa-rotate-left"></i>
          </button>
        <?php endif; ?>
      </div>

      <!-- Tombol Export -->
      <div class="btn-group">
        <form action="export/kegiatan_export_excel.php" method="post" class="me-2">
          <input type="hidden" name="search_export" value="<?= e($search) ?>">
          <button class="btn btn-outline-success" type="submit"><i class="fa-solid fa-file-excel me-1"></i> Excel</button>
        </form>
        <form action="export/kegiatan_export_pdf.php" method="post">
          <input type="hidden" name="search_export" value="<?= e($search) ?>">
          <button class="btn btn-outline-danger" type="submit"><i class="fa-solid fa-file-pdf me-1"></i> PDF</button>
        </form>
      </div>

      <!-- Tombol tambah -->
      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal" type="button">
        <i class="fa-solid fa-plus me-1"></i> Tambah Kegiatan
      </button>
    </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>Tanggal</th>
            <th>Tempat</th>
            <th>Penyelenggara</th>
            <th>Gambar</th>
            <th>Dokumen</th>
            <th>Dibuat Oleh</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($activities): foreach ($activities as $i => $row): ?>
          <tr>
            <td class="text-center"><?= $offset + $i + 1 ?></td>
            <td><?= e($row['title']) ?></td>
            <td><?= e($row['date_start']) ?> s.d <?= e($row['date_end']) ?></td>
            <td><?= e($row['location'] ?? '-') ?></td>
            <td><?= e($row['organizer'] ?? '-') ?></td>
            <td class="text-center">
          <?php if ($row['image']): ?>
            <img src="../uploads/kegiatan/images/<?= e($row['image']) ?>" 
                 style="height:40px;border-radius:4px;object-fit:cover;">
          <?php else: ?>
            <span class="text-muted">-</span>
          <?php endif; ?>
        </td>
        
        <td class="text-center">
          <?php if ($row['document']): ?>
            <a href="../uploads/kegiatan/docs/<?= e($row['document']) ?>" 
               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><?= e($row['creator'] ?? '-') ?></td>
            <td class="text-center">
              <!-- NOTE: json data-row DI-ESCAPE supaya valid di HTML attribute -->
              <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>

              <button class="btn btn-sm btn-primary edit-btn"
                      type="button"
                      data-id="<?= e($row['id']) ?>"
                      data-title="<?= e($row['title']) ?>"
                      data-description="<?= e($row['description']) ?>"
                      data-start="<?= e($row['date_start']) ?>"
                      data-end="<?= e($row['date_end']) ?>"
                      data-location="<?= e($row['location']) ?>"
                      data-organizer="<?= e($row['organizer']) ?>"
                      data-attachment="<?= e($row['attachment']) ?>"
                      title="Edit">
                <i class="fa-solid fa-pen-to-square"></i>
              </button>

              <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="8" class="text-center text-muted">Belum ada kegiatan.</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) ?>&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 Kegiatan
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="detail-content"></div>
    </div>
  </div>
</div>


<!-- Modal Tambah -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form method="post" enctype="multipart/form-data" class="modal-content">

      <div class="modal-header bg-success text-white">
        <h5 class="modal-title">
          <i class="fa-solid fa-plus me-2"></i>Tambah Kegiatan
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">

        <label class="form-label">Judul Kegiatan</label>
        <input type="text" name="title" class="form-control" required>

        <label class="form-label mt-2">Deskripsi</label>
        <textarea name="description" class="form-control" rows="3"></textarea>

        <div class="row mt-2">
          <div class="col-md-6">
            <label class="form-label">Tanggal Mulai</label>
            <input type="date" name="date_start" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Tanggal Selesai</label>
            <input type="date" name="date_end" class="form-control">
          </div>
        </div>

        <div class="row mt-2">
          <div class="col-md-6">
            <label class="form-label">Tempat</label>
            <input type="text" name="location" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Penyelenggara</label>
            <input type="text" name="organizer" class="form-control">
          </div>
        </div>

        <label class="form-label mt-3">Gambar Kegiatan (Opsional)</label>
        <input type="file" name="image" class="form-control" accept=".jpg,.jpeg,.png,.webp">

        <label class="form-label mt-3">Dokumen (PDF/DOC, Opsional)</label>
        <input type="file" name="document" class="form-control" accept=".pdf,.doc,.docx">

      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" name="add" class="btn btn-success">Simpan</button>
      </div>

    </form>
  </div>
</div>


<!-- Modal Edit -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form method="post" enctype="multipart/form-data" class="modal-content">

      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">
          <i class="fa-solid fa-pen-to-square me-2"></i>Edit Kegiatan
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">

        <input type="hidden" name="edit_id" id="edit_id">

        <label class="form-label">Judul</label>
        <input type="text" name="edit_title" id="edit_title" class="form-control" required>

        <label class="form-label mt-2">Deskripsi</label>
        <textarea name="edit_description" id="edit_description" class="form-control" rows="3"></textarea>

        <div class="row mt-2">
          <div class="col-md-6">
            <label class="form-label">Tanggal Mulai</label>
            <input type="date" name="edit_start" id="edit_start" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Tanggal Selesai</label>
            <input type="date" name="edit_end" id="edit_end" class="form-control">
          </div>
        </div>

        <div class="row mt-2">
          <div class="col-md-6">
            <label class="form-label">Tempat</label>
            <input type="text" name="edit_location" id="edit_location" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Penyelenggara</label>
            <input type="text" name="edit_organizer" id="edit_organizer" class="form-control">
          </div>
        </div>

        <!-- PREVIEW FILE LAMA -->
        <div class="mt-3" id="edit-file-preview"></div>

        <!-- File input baru -->
        <label class="form-label mt-3">Gambar Baru (Opsional)</label>
        <input type="file" name="edit_image" class="form-control" accept=".jpg,.jpeg,.png,.webp">

        <label class="form-label mt-3">Dokumen Baru (Opsional)</label>
        <input type="file" name="edit_document" class="form-control" accept=".pdf,.doc,.docx">

      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" name="update" class="btn btn-primary">Perbarui</button>
      </div>

    </form>
  </div>
</div>


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

// Folder upload
$image_dir = __DIR__ . '/../uploads/kegiatan/images/';
$doc_dir   = __DIR__ . '/../uploads/kegiatan/docs/';

if (!is_dir($image_dir)) mkdir($image_dir, 0755, true);
if (!is_dir($doc_dir)) mkdir($doc_dir, 0755, true);

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

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

  // Upload IMAGE
  $image_name = null;
  if (!empty($_FILES['image']['name'])) {
    $allowed_img = ['jpg','jpeg','png','webp'];
    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    $size = $_FILES['image']['size'];

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

    $image_name = time() . "_img_" . uniqid() . "." . $ext;
    move_uploaded_file($_FILES['image']['tmp_name'], $image_dir . $image_name);
  }

  // Upload DOCUMENT
  $document_name = null;
  if (!empty($_FILES['document']['name'])) {
    $allowed_doc = ['pdf','doc','docx'];
    $ext = strtolower(pathinfo($_FILES['document']['name'], PATHINFO_EXTENSION));
    $size = $_FILES['document']['size'];

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

    $document_name = time() . "_doc_" . uniqid() . "." . $ext;
    move_uploaded_file($_FILES['document']['tmp_name'], $doc_dir . $document_name);
  }

  // Insert
  $stmt = $pdo->prepare("
    INSERT INTO activities 
    (title, description, date_start, date_end, location, organizer, image, document, created_by)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  ");

  $stmt->execute([
    $_POST['title'] ?? '',
    $_POST['description'] ?? '',
    $_POST['date_start'] ?? null,
    $_POST['date_end'] ?? null,
    $_POST['location'] ?? '',
    $_POST['organizer'] ?? '',
    $image_name,
    $document_name,
    $_SESSION['user_id'] ?? null
  ]);

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


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

  // Ambil file lama
  $stmt_old = $pdo->prepare("SELECT image, document FROM activities WHERE id=?");
  $stmt_old->execute([$id]);
  $old = $stmt_old->fetch(PDO::FETCH_ASSOC);

  $image_old = $old['image'];
  $document_old = $old['document'];

  $image_name = $image_old;
  $document_name = $document_old;

  // Update IMAGE
  if (!empty($_FILES['edit_image']['name'])) {

    // hapus file lama
    delete_old_file($image_dir, $image_old);

    $allowed_img = ['jpg','jpeg','png','webp'];
    $ext = strtolower(pathinfo($_FILES['edit_image']['name'], PATHINFO_EXTENSION));
    $size = $_FILES['edit_image']['size'];

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

    $image_name = time() . "_img_" . uniqid() . "." . $ext;
    move_uploaded_file($_FILES['edit_image']['tmp_name'], $image_dir . $image_name);
  }

  // Update DOCUMENT
  if (!empty($_FILES['edit_document']['name'])) {

    // hapus file lama
    delete_old_file($doc_dir, $document_old);

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

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

    $document_name = time() . "_doc_" . uniqid() . "." . $ext;
    move_uploaded_file($_FILES['edit_document']['tmp_name'], $doc_dir . $document_name);
  }

  // Update ke DB
  $stmt = $pdo->prepare("
    UPDATE activities
    SET title=?, description=?, date_start=?, date_end=?, location=?, organizer=?, image=?, document=?
    WHERE id=?
  ");

  $stmt->execute([
    $_POST['edit_title'] ?? '',
    $_POST['edit_description'] ?? '',
    $_POST['edit_start'] ?? null,
    $_POST['edit_end'] ?? null,
    $_POST['edit_location'] ?? '',
    $_POST['edit_organizer'] ?? '',
    $image_name,
    $document_name,
    $id
  ]);

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


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

  if ($id) {
    // Ambil file lama
    $stmt = $pdo->prepare("SELECT image, document FROM activities WHERE id=?");
    $stmt->execute([$id]);
    $file = $stmt->fetch(PDO::FETCH_ASSOC);

    // hapus file
    if ($file['image']) delete_old_file($image_dir, $file['image']);
    if ($file['document']) delete_old_file($doc_dir, $file['document']);

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

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

<script>
document.addEventListener('DOMContentLoaded', () => {

  const safeGet = (selector) => document.querySelector(selector);

  // === EDIT BUTTON ===
  document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      // isi field dasar
      safeGet('#edit_id').value = btn.dataset.id || '';
      safeGet('#edit_title').value = btn.dataset.title || '';
      safeGet('#edit_description').value = btn.dataset.description || '';
      safeGet('#edit_start').value = btn.dataset.start || '';
      safeGet('#edit_end').value = btn.dataset.end || '';
      safeGet('#edit_location').value = btn.dataset.location || '';
      safeGet('#edit_organizer').value = btn.dataset.organizer || '';

      // ambil data image/document dari data- attributes (fallback ke attachment jika belum diupdate server-side)
      const dataImage = btn.dataset.image ?? btn.dataset.attachment ?? '';
      const dataDocument = btn.dataset.document ?? btn.dataset.attachment ?? '';

      // pastikan hidden inputs untuk old files ada (edit_image_old, edit_document_old)
      let formEl = document.querySelector('#editModal form');
      if (formEl) {
        if (!document.getElementById('edit_image_old')) {
          const hiddenImg = document.createElement('input');
          hiddenImg.type = 'hidden';
          hiddenImg.name = 'edit_image_old';
          hiddenImg.id = 'edit_image_old';
          formEl.appendChild(hiddenImg);
        }
        if (!document.getElementById('edit_document_old')) {
          const hiddenDoc = document.createElement('input');
          hiddenDoc.type = 'hidden';
          hiddenDoc.name = 'edit_document_old';
          hiddenDoc.id = 'edit_document_old';
          formEl.appendChild(hiddenDoc);
        }
        document.getElementById('edit_image_old').value = dataImage;
        document.getElementById('edit_document_old').value = dataDocument;
      }

      // optionally show preview inside modal (if you want)
      const previewWrap = document.getElementById('edit-file-preview');
      if (previewWrap) {
        let html = '';
        if (dataImage) {
          html += `<div class="mb-2"><strong>Gambar saat ini:</strong><br>
                   <img src="../uploads/kegiatan/images/${encodeURIComponent(dataImage)}" 
                        style="max-width:160px; max-height:120px; object-fit:cover; border-radius:6px;" 
                        alt="preview"></div>`;
        }
        if (dataDocument) {
          html += `<div><strong>Dokumen saat ini:</strong><br>
                   <a href="../uploads/kegiatan/docs/${encodeURIComponent(dataDocument)}" target="_blank">${dataDocument}</a></div>`;
        }
        previewWrap.innerHTML = html || '<span class="text-muted">Tidak ada file saat ini.</span>';
      }

      // show modal
      const editModalEl = document.getElementById('editModal');
      const modalObj = new bootstrap.Modal(editModalEl);
      modalObj.show();
    });
  });


  // === DETAIL BUTTON ===
  document.querySelectorAll('.detail-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      // ambil attribute data-row (sudah di-escape di server)
      const raw = btn.getAttribute('data-row') || '{}';
      let data = {};
      try {
        data = JSON.parse(raw);
      } catch (err) {
        console.error('JSON parse error in data-row', err, raw);
        Swal.fire('Error', 'Gagal membuka detail (format data tidak valid).', 'error');
        return;
      }

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

      // bangun bagian lampiran (gambar + dokumen)
      let lampiranHtml = '-';
      const img = data.image ?? data.attachment ?? null;
      const doc = data.document ?? data.attachment ?? null;
      const parts = [];
      if (img) {
        parts.push(`<div class="mb-2">
                      <strong>Gambar:</strong><br>
                      <img src="../uploads/kegiatan/images/${encodeURIComponent(img)}" 
                           alt="${sanitize(data.title)}" 
                           style="max-width:220px; max-height:160px; object-fit:cover; border-radius:6px;">
                    </div>`);
      }
      if (doc) {
        parts.push(`<div>
                      <strong>Dokumen:</strong><br>
                      <a href="../uploads/kegiatan/docs/${encodeURIComponent(doc)}" target="_blank">${sanitize(doc)}</a>
                    </div>`);
      }
      if (parts.length) lampiranHtml = parts.join('');

      // tabel detail
      let html = `
        <table class="table table-bordered">
          <tr><th style="width:25%">Judul</th><td>${sanitize(data.title)}</td></tr>
          <tr><th>Deskripsi</th><td>${sanitize(data.description) || '-'}</td></tr>
          <tr><th>Tanggal</th><td>${sanitize(data.date_start)} s.d ${sanitize(data.date_end)}</td></tr>
          <tr><th>Tempat</th><td>${sanitize(data.location) || '-'}</td></tr>
          <tr><th>Penyelenggara</th><td>${sanitize(data.organizer) || '-'}</td></tr>
          <tr><th>Lampiran</th><td>${lampiranHtml}</td></tr>
          <tr><th>Dibuat Oleh (ID)</th><td>${sanitize(data.created_by || '-')}</td></tr>
        </table>
      `;
      const detailContent = document.getElementById('detail-content');
      if (detailContent) detailContent.innerHTML = html;

      const detailModalEl = document.getElementById('detailModal');
      const modalObj = new bootstrap.Modal(detailModalEl);
      modalObj.show();
    });
  });


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


  // === SEARCH BUTTON & ENTER KEY ===
  const inputSearch = document.getElementById('search');
  const btnSearch = document.getElementById('btn-search');
  if (btnSearch && inputSearch) {
    btnSearch.addEventListener('click', () => {
      const q = inputSearch.value.trim();
      window.location = 'kegiatan.php?search=' + encodeURIComponent(q);
    });

    inputSearch.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        const q = inputSearch.value.trim();
        window.location = 'kegiatan.php?search=' + encodeURIComponent(q);
      }
    });
  }


  // === AUTOCOMPLETE (jQuery UI) - hanya jika tersedia ===
  if (window.jQuery && jQuery.ui && jQuery.fn.autocomplete) {
    $('#search').autocomplete({
      source: 'kegiatan_autocomplete.php',
      minLength: 2,
      select: function(e, ui) {
        $('#search').val(ui.item.value);
        window.location = 'kegiatan.php?search=' + encodeURIComponent(ui.item.value);
      }
    }).autocomplete('instance')._renderItem = function(ul, item) {
      const title = $('<div>').text(item.value).html();
      const meta = $('<small>').text((item.location ? ' • ' + item.location : '') + (item.organizer ? ' • ' + item.organizer : '')).html();
      return $('<li>')
        .append(`<div>${title}<br><small class="text-muted">${meta}</small></div>`)
        .appendTo(ul);
    };
  } else {
    console.warn('jQuery UI Autocomplete tidak tersedia: fallback ke search biasa.');
  }

  // === RESET SEARCH BUTTON ===
  const resetBtn = document.getElementById('btn-reset');
  if (resetBtn) {
    resetBtn.addEventListener('click', () => {
      window.location = 'kegiatan.php'; // kembali ke daftar penuh
    });
  }

});
</script>


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