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

// ====== Konfigurasi dasar ======
$upload_dir = __DIR__ . '/../uploads/berita/';
$per_page = 10;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $per_page;
$search = trim($_GET['search'] ?? '');
$status_filter = $_GET['status'] ?? '';

// ====== Query dinamis dengan pencarian dan filter ======
$where = [];
$params = [];

if ($search !== '') {
    $where[] = "(n.title LIKE ? OR n.excerpt LIKE ? OR n.content LIKE ?)";
    $params = array_fill(0, 3, "%$search%");
}

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

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

$total_stmt = $pdo->prepare("SELECT COUNT(*) FROM news n $where_sql");
$total_stmt->execute($params);
$total = $total_stmt->fetchColumn();
$total_pages = ceil($total / $per_page);

$stmt = $pdo->prepare("SELECT n.*, u.full_name AS author 
                       FROM news n 
                       LEFT JOIN users u ON n.author_id = u.id 
                       $where_sql 
                       ORDER BY n.created_at DESC 
                       LIMIT $per_page OFFSET $offset");
$stmt->execute($params);
$news = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ====== Fungsi bantu slug ======
function generateSlug($pdo, $title) {
    $slug_base = strtolower(trim(preg_replace('/[^a-z0-9]+/', '-', $title), '-'));
    if ($slug_base === '') $slug_base = 'berita-' . time();
    $slug = $slug_base;
    $counter = 1;
    while (true) {
        $check = $pdo->prepare("SELECT COUNT(*) FROM news WHERE slug = ?");
        $check->execute([$slug]);
        if ($check->fetchColumn() == 0) break;
        $slug = $slug_base . '-' . $counter++;
    }
    return $slug;
}
?>

<div class="container-fluid mt-4">
  <div class="card shadow border-0 rounded-4">
    <div class="card-body">

      <!-- Header -->
      <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-4">
        <div class="mb-3 mb-md-0">
          <h4 class="fw-bold mb-0 text-success">
            <i class="fa-solid fa-newspaper me-2"></i>Manajemen Berita & Pengumuman
          </h4>
          <small class="text-muted">Kelola daftar berita dan pengumuman kampus di sini.</small>
        </div>

        <!-- Form Pencarian -->
        <form method="get" class="d-flex flex-wrap gap-2 align-items-center">
          <input type="text" name="search" class="form-control" placeholder="Cari berita..." 
                 value="<?= htmlspecialchars($search) ?>" style="min-width:220px;">
          <select name="status" class="form-select" style="min-width:150px;">
            <option value="">Semua Status</option>
            <option value="published" <?= $status_filter=='published'?'selected':'' ?>>Published</option>
            <option value="draft" <?= $status_filter=='draft'?'selected':'' ?>>Draft</option>
          </select>
          <button class="btn btn-success" title="Cari"><i class="fa-solid fa-search"></i></button>
          <a href="berita.php" class="btn btn-outline-secondary" title="Reset"><i class="fa-solid fa-rotate-left me-1"></i>Reset</a>
        </form>
      </div>

      <!-- Tombol Tambah -->
      <div class="d-flex justify-content-between align-items-center mb-3">
        <a href="berita_form.php?mode=add" class="btn btn-success px-4">
          <i class="fa-solid fa-plus me-1"></i> Tambah Berita
        </a>
      </div>

      <!-- Tabel Berita -->
      <div class="table-responsive">
        <table class="table table-bordered align-middle mb-0">
          <thead class="table-success text-center align-middle">
            <tr>
              <th style="width:5%;">No</th>
              <th>Judul</th>
              <th style="width:10%;">Status</th>
              <th style="width:10%;">Gambar</th>
              <th style="width:15%;">Penulis</th>
              <th style="width:12%;">Dibuat</th>
              <th style="width:15%;">Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($news): foreach ($news as $i => $n): ?>
            <tr>
              <td class="text-center"><?= $offset + $i + 1 ?></td>
              <td><?= htmlspecialchars($n['title']) ?></td>
              <td class="text-center">
                <span class="badge rounded-pill bg-<?= $n['status']=='published'?'success':'secondary' ?>">
                  <?= ucfirst($n['status']) ?>
                </span>
              </td>
              <td class="text-center">
                <?php if ($n['featured_image']): ?>
                  <img src="../uploads/berita/<?= htmlspecialchars($n['featured_image']) ?>"
                       onerror="this.src='../assets/img/no-image.png';"
                       width="50" height="50" class="rounded shadow-sm object-fit-cover">
                <?php else: ?>
                  <span class="text-muted">-</span>
                <?php endif; ?>
              </td>
              <td><?= htmlspecialchars($n['author'] ?? '-') ?></td>
              <td class="text-center"><?= date('d M Y', strtotime($n['created_at'])) ?></td>
              <td class="text-center">
                <div class="btn-group">
                  <button class="btn btn-sm btn-info text-white detail-btn" title="Detail"
                          data-title="<?= htmlspecialchars($n['title']) ?>"
                          data-excerpt="<?= htmlspecialchars($n['excerpt']) ?>"
                          data-content="<?= htmlspecialchars($n['content']) ?>"
                          data-status="<?= ucfirst($n['status']) ?>"
                          data-author="<?= htmlspecialchars($n['author']) ?>"
                          data-date="<?= date('d M Y', strtotime($n['created_at'])) ?>">
                    <i class="fa-solid fa-circle-info"></i>
                  </button>
                  <a href="berita_form.php?mode=edit&id=<?= $n['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" title="Hapus" data-id="<?= $n['id'] ?>">
                    <i class="fa-solid fa-trash"></i>
                  </button>
                </div>
              </td>
            </tr>
            <?php endforeach; else: ?>
            <tr>
              <td colspan="7" class="text-center text-muted py-3">Belum ada berita yang tersedia.</td>
            </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <nav class="mt-4">
        <ul class="pagination justify-content-center mb-0">
          <?php for ($p = 1; $p <= $total_pages; $p++): ?>
            <li class="page-item <?= $p==$page?'active':'' ?>">
              <a class="page-link" href="?page=<?= $p ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status_filter) ?>">
                <?= $p ?>
              </a>
            </li>
          <?php endfor; ?>
        </ul>
      </nav>
    </div>
  </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 Berita</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
// ====== CRUD ======

// Tambah berita
if (isset($_POST['add'])) {
    $file_name = null;
    if (!empty($_FILES['featured_image']['name'])) {
        $clean_name = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', basename($_FILES['featured_image']['name']));
        $file_name = time() . '_' . $clean_name;
        move_uploaded_file($_FILES['featured_image']['tmp_name'], $upload_dir . $file_name);
    }

    $slug = generateSlug($pdo, $_POST['title']);

    $stmt = $pdo->prepare("INSERT INTO news (title, slug, excerpt, content, featured_image, status, author_id, published_at) 
                           VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $_POST['title'], $slug, $_POST['excerpt'], $_POST['content'], $file_name,
        $_POST['status'], $_SESSION['user_id'] ?? null,
        ($_POST['status'] == 'published' ? date('Y-m-d H:i:s') : null)
    ]);

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

// Update berita
if (isset($_POST['update'])) {
    $id = $_POST['edit_id'];
    $file_name = null;

    // Upload baru?
    if (!empty($_FILES['edit_image']['name'])) {
        $clean_name = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', basename($_FILES['edit_image']['name']));
        $file_name = time() . '_' . $clean_name;
        move_uploaded_file($_FILES['edit_image']['tmp_name'], $upload_dir . $file_name);
    } else {
        $file_name = $pdo->query("SELECT featured_image FROM news WHERE id=$id")->fetchColumn();
    }

    $slug = generateSlug($pdo, $_POST['edit_title']);

    $stmt = $pdo->prepare("UPDATE news 
                           SET title=?, slug=?, excerpt=?, content=?, featured_image=?, status=?, 
                               updated_at=NOW(), published_at=? 
                           WHERE id=?");
    $stmt->execute([
        $_POST['edit_title'], $slug, $_POST['edit_excerpt'], $_POST['edit_content'],
        $file_name, $_POST['edit_status'],
        ($_POST['edit_status'] == 'published' ? date('Y-m-d H:i:s') : null),
        $id
    ]);

    echo "<script>Swal.fire('Berhasil', 'Berita berhasil diperbarui', 'success').then(()=>location.href='berita.php');</script>";
}

// Hapus berita
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM news WHERE id=?");
    $stmt->execute([$id]);
    echo "<script>Swal.fire('Dihapus', 'Berita berhasil dihapus', 'success').then(()=>location.href='berita.php');</script>";
}
?>

<script>
document.addEventListener('DOMContentLoaded', () => {
  // Detail
  document.querySelectorAll('.detail-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const content = `
        <h5>${btn.dataset.title}</h5>
        <p><b>Status:</b> ${btn.dataset.status}</p>
        <p><b>Penulis:</b> ${btn.dataset.author || '-'}</p>
        <p><b>Tanggal:</b> ${btn.dataset.date}</p>
        <hr>
        <p><b>Ringkasan:</b> ${btn.dataset.excerpt || '-'}</p>
        <hr>
        <div>${btn.dataset.content}</div>
      `;
      document.getElementById('detail-content').innerHTML = content;
      new bootstrap.Modal(document.getElementById('detailModal')).show();
    });
  });

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

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