<?php
// ====== BOOTSTRAP (tanpa output HTML) ======
require_once __DIR__ . '/../config/helpers.php';
require_once __DIR__ . '/../config/db.php';

require_login();

$pdo = db();

/* =========================================================
   SCHEMA SETUP + SAFE MIGRATION (untuk skema lama)
   ========================================================= */

// Buat tabel news (kalau belum ada)
$pdo->exec("
  CREATE TABLE IF NOT EXISTS news (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content LONGTEXT,
    category VARCHAR(120),
    author VARCHAR(120),
    photo_path VARCHAR(255),
    source VARCHAR(255),
    publish_date DATETIME NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// Buat tabel news_comments (kolom minimal)
$pdo->exec("
  CREATE TABLE IF NOT EXISTS news_comments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    news_id INT NOT NULL,
    name VARCHAR(120) NOT NULL,
    email VARCHAR(160) DEFAULT NULL,
    comment TEXT NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    is_approved TINYINT(1) NOT NULL DEFAULT 0
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// Tambahkan FK/index bila belum ada (opsional)
try { $pdo->exec("ALTER TABLE news_comments ADD INDEX idx_news_id (news_id)"); } catch (Throwable $e) {}
try {
  $pdo->exec("
    ALTER TABLE news_comments
    ADD CONSTRAINT fk_news_comments_news
    FOREIGN KEY (news_id) REFERENCES news(id)
    ON DELETE CASCADE
  ");
} catch (Throwable $e) {}

// ====== MIGRASI KOLOM HILANG (hindari error kolom) ======
function table_has_column(PDO $pdo, string $table, string $col): bool {
  $st = $pdo->prepare("SHOW COLUMNS FROM `$table` LIKE ?");
  $st->execute([$col]);
  return (bool)$st->fetch();
}

$needAlter = [];
if (!table_has_column($pdo, 'news_comments', 'is_spam')) {
  $needAlter[] = "ADD COLUMN is_spam TINYINT(1) NOT NULL DEFAULT 0 AFTER is_approved";
}
if (!table_has_column($pdo, 'news_comments', 'ip')) {
  $needAlter[] = "ADD COLUMN ip VARCHAR(45) DEFAULT NULL AFTER comment";
}
if (!table_has_column($pdo, 'news_comments', 'user_agent')) {
  $needAlter[] = "ADD COLUMN user_agent TEXT DEFAULT NULL AFTER ip";
}
if ($needAlter) {
  try { $pdo->exec("ALTER TABLE news_comments ".implode(", ", $needAlter)); } catch (Throwable $e) {}
}

// ====== Kolom parent_id untuk fitur BALAS ======
if (!table_has_column($pdo, 'news_comments', 'parent_id')) {
  try { $pdo->exec("ALTER TABLE news_comments ADD COLUMN parent_id INT NULL DEFAULT 0 AFTER news_id"); } catch (Throwable $e) {}
}
try { $pdo->exec("ALTER TABLE news_comments ADD INDEX idx_parent_id (parent_id)"); } catch (Throwable $e) {}

/* =========================================================
   HELPERS & FLASH
   ========================================================= */
function qint($v){ return max(0, (int)$v); }
$OK  = flash('ok');
$ERR = flash('err');

/* =========================================================
   ACTIONS (POST)
   ========================================================= */
if (is_post()){
  csrf_check();
  $action = trim($_POST['action'] ?? '');
  $id     = qint($_POST['id'] ?? 0);

  try {
    if ($action === 'delete') {
      if ($id <= 0) throw new RuntimeException('ID tidak valid.');
      $st = $pdo->prepare("DELETE FROM news_comments WHERE id=?");
      $st->execute([$id]);
      flash('ok','Komentar dihapus.');
      header('Location: coment.php'); exit;
    }

    if ($action === 'approve') {
      if ($id <= 0) throw new RuntimeException('ID tidak valid.');
      $pdo->prepare("UPDATE news_comments SET is_approved=1, is_spam=0 WHERE id=?")->execute([$id]);
      flash('ok','Komentar disetujui (tampil di publik).');
      header('Location: coment.php?read='.$id); exit;
    }

    if ($action === 'unapprove') {
      if ($id <= 0) throw new RuntimeException('ID tidak valid.');
      $pdo->prepare("UPDATE news_comments SET is_approved=0 WHERE id=?")->execute([$id]);
      flash('ok','Persetujuan dibatalkan (disembunyikan).');
      header('Location: coment.php?read='.$id); exit;
    }

    if ($action === 'spam') {
      if ($id <= 0) throw new RuntimeException('ID tidak valid.');
      $pdo->prepare("UPDATE news_comments SET is_spam=1, is_approved=0 WHERE id=?")->execute([$id]);
      flash('ok','Komentar ditandai spam.');
      header('Location: coment.php?read='.$id); exit;
    }

    if ($action === 'unspam') {
      if ($id <= 0) throw new RuntimeException('ID tidak valid.');
      $pdo->prepare("UPDATE news_comments SET is_spam=0 WHERE id=?")->execute([$id]);
      flash('ok','Tanda spam dihapus.');
      header('Location: coment.php?read='.$id); exit;
    }

    // ====== FITUR BALAS KOMENTAR ======
    if ($action === 'reply') {
      $newsId   = qint($_POST['news_id'] ?? 0);
      $parentId = qint($_POST['parent_id'] ?? 0);
      $name     = trim($_POST['reply_name'] ?? '');
      $email    = trim($_POST['reply_email'] ?? '');
      $comment  = trim($_POST['reply_comment'] ?? '');

      if ($newsId <= 0 || $parentId <= 0) throw new RuntimeException('Data balasan tidak valid.');
      if ($name === '' || $comment === '') throw new RuntimeException('Nama dan isi balasan wajib diisi.');

      // validasi berita & parent
      $cekNews = $pdo->prepare("SELECT 1 FROM news WHERE id=?");
      $cekNews->execute([$newsId]);
      if (!$cekNews->fetch()) throw new RuntimeException('Berita tidak ditemukan.');

      $cekPar = $pdo->prepare("SELECT 1 FROM news_comments WHERE id=? AND news_id=?");
      $cekPar->execute([$parentId, $newsId]);
      if (!$cekPar->fetch()) throw new RuntimeException('Komentar induk tidak ditemukan.');

      if (mb_strlen($name)  > 120) $name  = mb_substr($name, 0, 120);
      if (mb_strlen($email) > 160) $email = mb_substr($email, 0, 160);

      $ins = $pdo->prepare("
        INSERT INTO news_comments (news_id, parent_id, name, email, comment, is_approved, is_spam, ip, user_agent)
        VALUES (?,?,?,?,?,1,0,?,?)
      ");
      $ip  = $_SERVER['REMOTE_ADDR'] ?? null;
      $ua  = $_SERVER['HTTP_USER_AGENT'] ?? null;
      $ins->execute([$newsId, $parentId, $name, $email ?: null, $comment, $ip, $ua]);

      flash('ok','Balasan berhasil dikirim.');
      header('Location: coment.php?read='.$parentId.'#replies'); exit;
    }

    if (!in_array($action, ['delete','approve','unapprove','spam','unspam','reply'], true)) {
      flash('err','Aksi tidak dikenali.');
      header('Location: coment.php'); exit;
    }

  } catch (Throwable $t){
    flash('err','Gagal memproses aksi: '.$t->getMessage());
    header('Location: coment.php'); exit;
  }
}

/* =========================================================
   READ SINGLE (GET ?read=ID)
   ========================================================= */
$view = null;
$readId = isset($_GET['read']) ? qint($_GET['read']) : 0;
if ($readId > 0){
  $st = $pdo->prepare("
    SELECT c.*, n.title AS news_title
    FROM news_comments c
    JOIN news n ON n.id = c.news_id
    WHERE c.id=?
  ");
  $st->execute([$readId]);
  $view = $st->fetch();
  if (!$view){
    flash('err', 'Komentar tidak ditemukan.');
    header('Location: coment.php'); exit;
  }
}

/* =========================================================
   LIST + SEARCH + FILTER + PAGINATION
   ========================================================= */
$kw     = trim($_GET['q'] ?? '');
$filter = trim($_GET['f'] ?? 'all'); // all|pending|approved|spam
$page   = max(1, (int)($_GET['page'] ?? 1));
$pp     = 10;
$off    = ($page - 1) * $pp;

$where = [];
$args  = [];

if ($kw !== ''){
  $where[] = "(c.name LIKE ? OR c.email LIKE ? OR c.comment LIKE ? OR n.title LIKE ?)";
  $like = '%'.$kw.'%';
  array_push($args, $like, $like, $like, $like);
}

if ($filter === 'pending') {
  $where[] = "c.is_approved=0 AND c.is_spam=0";
} elseif ($filter === 'approved') {
  $where[] = "c.is_approved=1 AND c.is_spam=0";
} elseif ($filter === 'spam') {
  $where[] = "c.is_spam=1";
}

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

$cntSt = $pdo->prepare("
  SELECT COUNT(*)
  FROM news_comments c
  JOIN news n ON n.id = c.news_id
  $sqlWhere
");
$cntSt->execute($args);
$total = (int)$cntSt->fetchColumn();
$pages = max(1, (int)ceil($total / $pp));

$listSt = $pdo->prepare("
  SELECT 
    c.id, c.news_id, c.name, c.email, c.is_approved, c.is_spam, c.created_at,
    LEFT(c.comment, 180) AS snippet,
    n.title AS news_title
  FROM news_comments c
  JOIN news n ON n.id = c.news_id
  $sqlWhere
  ORDER BY 
    c.is_spam ASC, 
    c.is_approved ASC, 
    c.created_at DESC, 
    c.id DESC
  LIMIT $pp OFFSET $off
");
$listSt->execute($args);
$rows = $listSt->fetchAll();

/* =========================================================
   OUTPUT
   ========================================================= */
require_once __DIR__ . '/_layout_top.php';
?>
<div class="container py-4">

  <?php if($OK): ?>
    <div class="alert alert-success d-flex align-items-center">
      <i class="bi bi-check-circle me-2"></i><div><?php echo e($OK) ?></div>
    </div>
  <?php endif; ?>
  <?php if($ERR): ?>
    <div class="alert alert-danger d-flex align-items-center">
      <i class="bi bi-exclamation-triangle me-2"></i><div><?php echo e($ERR) ?></div>
    </div>
  <?php endif; ?>

  <div class="card shadow-sm mb-4">
    <div class="card-header d-flex flex-wrap gap-2 justify-content-between align-items-center">
      <h5 class="mb-0"><i class="bi bi-chat-square-dots me-2"></i>Komentar Masuk</h5>

      <div class="d-flex gap-2 flex-wrap">
        <form class="d-flex" method="get" action="coment.php" role="search">
          <input class="form-control form-control-sm me-2" type="search" name="q" placeholder="Cari nama/email/komentar/berita…" value="<?php echo e($kw) ?>">
          <select class="form-select form-select-sm me-2" name="f" onchange="this.form.submit()">
            <option value="all" <?php echo ($filter==='all'?'selected':'') ?>>Semua</option>
            <option value="pending" <?php echo ($filter==='pending'?'selected':'') ?>>Pending</option>
            <option value="approved" <?php echo ($filter==='approved'?'selected':'') ?>>Disetujui</option>
            <option value="spam" <?php echo ($filter==='spam'?'selected':'') ?>>Spam</option>
          </select>
          <button class="btn btn-sm btn-outline-primary"><i class="bi bi-search"></i></button>
        </form>
      </div>
    </div>

    <div class="table-responsive">
      <table class="table table-sm align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th style="width:60px;">#</th>
            <th>Berita</th>
            <th>Pengirim</th>
            <th>Komentar</th>
            <th style="width:160px;">Waktu</th>
            <th style="width:320px;">Aksi</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($rows as $r): ?>
          <?php
            $rowClass = '';
            if ((int)$r['is_spam'] === 1)        $rowClass = 'table-danger';
            else if ((int)$r['is_approved']===0) $rowClass = 'table-warning';
          ?>
          <tr class="<?php echo $rowClass; ?>">
            <td><?php echo (int)$r['id']; ?></td>
            <td>
              <div class="fw-semibold text-truncate" style="max-width:280px;" title="<?php echo e($r['news_title']) ?>">
                <?php echo e($r['news_title']); ?>
              </div>
            </td>
            <td>
              <div class="fw-semibold"><?php echo e($r['name']); ?></div>
              <div class="text-muted small"><?php echo e($r['email'] ?: '—'); ?></div>
            </td>
            <td>
              <div class="text-muted small text-truncate" style="max-width:420px;">
                <?php echo e($r['snippet']); ?><?php echo (strlen($r['snippet'])>=180?'…':''); ?>
              </div>
              <div class="mt-1">
                <?php if((int)$r['is_spam']===1): ?>
                  <span class="badge text-bg-danger">Spam</span>
                <?php elseif((int)$r['is_approved']===1): ?>
                  <span class="badge text-bg-success">Disetujui</span>
                <?php else: ?>
                  <span class="badge text-bg-warning text-dark">Pending</span>
                <?php endif; ?>
              </div>
            </td>
            <td class="text-muted small"><?php echo e($r['created_at']); ?></td>
            <td>
              <div class="d-flex flex-wrap gap-2">
                <a class="btn btn-sm btn-outline-primary" href="coment.php?read=<?php echo (int)$r['id']; ?>">
                  <i class="bi bi-eye me-1"></i>Lihat
                </a>
                <a class="btn btn-sm btn-outline-secondary" href="coment.php?read=<?php echo (int)$r['id']; ?>#reply">
                  <i class="bi bi-reply"></i> Balas
                </a>

                <?php if((int)$r['is_spam']===1): ?>
                  <form method="post" class="d-inline">
                    <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="unspam">
                    <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                    <button class="btn btn-sm btn-warning"><i class="bi bi-shield-slash me-1"></i>Batal spam</button>
                  </form>
                <?php else: ?>
                  <?php if((int)$r['is_approved']===0): ?>
                    <form method="post" class="d-inline">
                      <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                      <input type="hidden" name="action" value="approve">
                      <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                      <button class="btn btn-sm btn-success"><i class="bi bi-check2-circle me-1"></i>Setujui</button>
                    </form>
                  <?php else: ?>
                    <form method="post" class="d-inline">
                      <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                      <input type="hidden" name="action" value="unapprove">
                      <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                      <button class="btn btn-sm btn-secondary"><i class="bi bi-eye-slash me-1"></i>Batalkan</button>
                    </form>
                  <?php endif; ?>

                  <form method="post" class="d-inline">
                    <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="spam">
                    <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                    <button class="btn btn-sm btn-outline-danger"><i class="bi bi-shield-exclamation me-1"></i>Tandai spam</button>
                  </form>
                <?php endif; ?>

                <form method="post" class="d-inline" onsubmit="return confirm('Hapus komentar ini?')">
                  <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                  <input type="hidden" name="action" value="delete">
                  <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                  <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash me-1"></i>Hapus</button>
                </form>
              </div>
            </td>
          </tr>
        <?php endforeach; if(empty($rows)): ?>
          <tr><td colspan="6" class="text-center text-muted py-4">Belum ada komentar.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>

    <?php if($pages > 1): ?>
      <div class="card-footer d-flex justify-content-between align-items-center">
        <div class="text-muted small">Total: <?php echo (int)$total; ?> komentar</div>
        <nav>
          <ul class="pagination pagination-sm mb-0">
            <?php
            $base = 'coment.php';
            $qs = $_GET; unset($qs['page']);
            $baseQs = http_build_query($qs);
            $mk = function($p) use ($base, $baseQs){ return $base.'?'.($baseQs ? $baseQs.'&' : '').'page='.$p; };
            ?>
            <li class="page-item <?php echo ($page<=1?'disabled':''); ?>">
              <a class="page-link" href="<?php echo e($mk(max(1,$page-1))); ?>">&laquo;</a>
            </li>
            <?php
              $start = max(1, $page-2);
              $end   = min($pages, $page+2);
              for($i=$start;$i<=$end;$i++):
            ?>
              <li class="page-item <?php echo ($i===$page?'active':''); ?>">
                <a class="page-link" href="<?php echo e($mk($i)); ?>"><?php echo $i; ?></a>
              </li>
            <?php endfor; ?>
            <li class="page-item <?php echo ($page>=$pages?'disabled':''); ?>">
              <a class="page-link" href="<?php echo e($mk(min($pages,$page+1))); ?>">&raquo;</a>
            </li>
          </ul>
        </nav>
      </div>
    <?php endif; ?>
  </div>

  <!-- Detail Viewer -->
  <?php if($view): ?>
    <div class="card shadow-sm">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-chat-square-text me-2"></i>Detail Komentar</h5>
        <a href="coment.php" class="btn btn-sm btn-outline-secondary"><i class="bi bi-x-lg me-1"></i>Tutup</a>
      </div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-6">
            <div class="mb-2">
              <span class="text-muted">Berita</span>
              <div class="fw-semibold"><?php echo e($view['news_title']); ?></div>
            </div>
            <div class="mb-2">
              <span class="text-muted">Nama</span>
              <div class="fw-semibold"><?php echo e($view['name']); ?></div>
            </div>
            <div class="mb-2">
              <span class="text-muted">Email</span>
              <div class="fw-semibold">
                <?php if(!empty($view['email'])): ?>
                  <a href="mailto:<?php echo e($view['email']); ?>"><?php echo e($view['email']); ?></a>
                <?php else: ?> — <?php endif; ?>
              </div>
            </div>
          </div>
          <div class="col-md-6 text-md-end">
            <div class="mb-2"><span class="text-muted">Waktu</span><div class="fw-semibold"><?php echo e($view['created_at']); ?></div></div>
            <div class="mb-2"><span class="text-muted">Status</span>
              <div class="d-flex gap-2 justify-content-md-end flex-wrap">
                <?php if((int)$view['is_spam']===1): ?>
                  <span class="badge text-bg-danger">Spam</span>
                <?php elseif((int)$view['is_approved']===1): ?>
                  <span class="badge text-bg-success">Disetujui</span>
                <?php else: ?>
                  <span class="badge text-bg-warning text-dark">Pending</span>
                <?php endif; ?>
              </div>
            </div>
          </div>
        </div>

        <?php if(!empty($view['ip']) || !empty($view['user_agent'])): ?>
          <hr>
          <div class="row g-3">
            <div class="col-md-4">
              <div class="text-muted">IP</div>
              <div class="small"><?php echo e($view['ip'] ?: '—'); ?></div>
            </div>
            <div class="col-md-8">
              <div class="text-muted">User Agent</div>
              <div class="small" style="word-break:break-all"><?php echo e($view['user_agent'] ?: '—'); ?></div>
            </div>
          </div>
        <?php endif; ?>

        <hr>
        <div class="mb-2">
          <span class="text-muted">Komentar</span>
          <div class="border rounded p-3" style="white-space:pre-line"><?php echo e($view['comment']); ?></div>
        </div>

        <!-- ===== Form Balas Komentar ===== -->
        <hr id="reply">
        <h6 class="mb-2"><i class="bi bi-reply me-2"></i>Balas Komentar</h6>
        <form method="post" class="card card-body border-0 shadow-sm">
          <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
          <input type="hidden" name="action" value="reply">
          <input type="hidden" name="news_id" value="<?php echo (int)$view['news_id']; ?>">
          <input type="hidden" name="parent_id" value="<?php echo (int)$view['id']; ?>">

          <div class="row g-2">
            <div class="col-md-4">
              <label class="form-label">Nama *</label>
              <input class="form-control" name="reply_name" value="Admin" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Email (opsional)</label>
              <input type="email" class="form-control" name="reply_email" placeholder="admin@example.com">
            </div>
          </div>
          <div class="mt-2">
            <label class="form-label">Balasan *</label>
            <textarea class="form-control" name="reply_comment" rows="3" required></textarea>
          </div>
          <div class="mt-3 d-flex gap-2">
            <button class="btn btn-primary btn-sm"><i class="bi bi-send me-1"></i>Kirim Balasan</button>
            <a href="#replies" class="btn btn-outline-secondary btn-sm">Lihat Balasan</a>
          </div>
        </form>

        <!-- ===== Daftar Balasan ===== -->
        <?php
          $repSt = $pdo->prepare("
            SELECT id, name, email, comment, created_at, is_approved, is_spam
            FROM news_comments
            WHERE parent_id=?
            ORDER BY created_at ASC, id ASC
          ");
          $repSt->execute([(int)$view['id']]);
          $replies = $repSt->fetchAll();
        ?>
        <?php if(!empty($replies)): ?>
          <hr id="replies">
          <h6 class="mb-2"><i class="bi bi-chat-left-text me-2"></i>Balasan</h6>
          <div class="list-group">
            <?php foreach($replies as $rp): ?>
              <div class="list-group-item">
                <div class="d-flex justify-content-between">
                  <div>
                    <strong><?php echo e($rp['name']); ?></strong>
                    <?php if(!empty($rp['email'])): ?>
                      <span class="text-muted small ms-2"><?php echo e($rp['email']); ?></span>
                    <?php endif; ?>
                    <?php if((int)$rp['is_spam']===1): ?>
                      <span class="badge text-bg-danger ms-2">Spam</span>
                    <?php elseif((int)$rp['is_approved']===0): ?>
                      <span class="badge text-bg-warning text-dark ms-2">Pending</span>
                    <?php else: ?>
                      <span class="badge text-bg-success ms-2">Disetujui</span>
                    <?php endif; ?>
                  </div>
                  <small class="text-muted"><?php echo e($rp['created_at']); ?></small>
                </div>
                <div class="mt-1" style="white-space:pre-line"><?php echo e($rp['comment']); ?></div>
                <div class="mt-2 d-flex gap-2">
                  <a class="btn btn-sm btn-outline-primary" href="coment.php?read=<?php echo (int)$rp['id']; ?>">
                    <i class="bi bi-eye"></i> Lihat
                  </a>
                  <?php if((int)$rp['is_spam']===1): ?>
                    <form method="post" class="d-inline">
                      <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                      <input type="hidden" name="action" value="unspam">
                      <input type="hidden" name="id" value="<?php echo (int)$rp['id']; ?>">
                      <button class="btn btn-sm btn-warning">Batal spam</button>
                    </form>
                  <?php else: ?>
                    <?php if((int)$rp['is_approved']===0): ?>
                      <form method="post" class="d-inline">
                        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                        <input type="hidden" name="action" value="approve">
                        <input type="hidden" name="id" value="<?php echo (int)$rp['id']; ?>">
                        <button class="btn btn-sm btn-success">Setujui</button>
                      </form>
                    <?php else: ?>
                      <form method="post" class="d-inline">
                        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                        <input type="hidden" name="action" value="unapprove">
                        <input type="hidden" name="id" value="<?php echo (int)$rp['id']; ?>">
                        <button class="btn btn-sm btn-secondary">Batalkan</button>
                      </form>
                    <?php endif; ?>
                    <form method="post" class="d-inline">
                      <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                      <input type="hidden" name="action" value="spam">
                      <input type="hidden" name="id" value="<?php echo (int)$rp['id']; ?>">
                      <button class="btn btn-sm btn-outline-danger">Spam</button>
                    </form>
                  <?php endif; ?>
                  <form method="post" class="d-inline" onsubmit="return confirm('Hapus balasan ini?')">
                    <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?php echo (int)$rp['id']; ?>">
                    <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i> Hapus</button>
                  </form>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php else: ?>
          <hr id="replies">
          <div class="alert alert-secondary mb-0">Belum ada balasan.</div>
        <?php endif; ?>

      </div>

      <div class="card-footer d-flex gap-2 flex-wrap">
        <?php if((int)$view['is_spam']===1): ?>
          <form method="post">
            <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
            <input type="hidden" name="action" value="unspam">
            <input type="hidden" name="id" value="<?php echo (int)$view['id']; ?>">
            <button class="btn btn-warning btn-sm"><i class="bi bi-shield-slash me-1"></i>Batal spam</button>
          </form>
        <?php else: ?>
          <?php if((int)$view['is_approved']===0): ?>
            <form method="post">
              <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
              <input type="hidden" name="action" value="approve">
              <input type="hidden" name="id" value="<?php echo (int)$view['id']; ?>">
              <button class="btn btn-success btn-sm"><i class="bi bi-check2-circle me-1"></i>Setujui</button>
            </form>
          <?php else: ?>
            <form method="post">
              <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
              <input type="hidden" name="action" value="unapprove">
              <input type="hidden" name="id" value="<?php echo (int)$view['id']; ?>">
              <button class="btn btn-secondary btn-sm"><i class="bi bi-eye-slash me-1"></i>Batalkan</button>
            </form>
          <?php endif; ?>

          <form method="post" onsubmit="return confirm('Tandai komentar ini sebagai spam?')">
            <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
            <input type="hidden" name="action" value="spam">
            <input type="hidden" name="id" value="<?php echo (int)$view['id']; ?>">
            <button class="btn btn-outline-danger btn-sm"><i class="bi bi-shield-exclamation me-1"></i>Tandai spam</button>
          </form>
        <?php endif; ?>

        <form method="post" onsubmit="return confirm('Hapus komentar ini?')">
          <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" value="<?php echo (int)$view['id']; ?>">
          <button class="btn btn-outline-danger btn-sm"><i class="bi bi-trash me-1"></i>Hapus</button>
        </form>
      </div>
    </div>
  <?php endif; ?>

</div>

<?php require __DIR__ . '/_layout_bottom.php'; ?>
