<?php
session_start();
require 'koneksi.php';

if (!isset($_SESSION['admin_id'])) {
    header("Location: index");
    exit();
}

if (!isset($_GET['id'])) {
    $_SESSION['error'] = "ID komentar tidak valid";
    header("Location: comment");
    exit();
}

$comment_id = (int)$_GET['id'];

try {
    // Cek apakah komentar ada dan milik admin (kecuali super admin)
    $query = "SELECT c.*, a.username
              FROM blog_comments c
              LEFT JOIN ngadmin a ON c.comment_by = a.id
              WHERE c.id = ?";

    $stmt = $pdo->prepare($query);
    $stmt->execute([$comment_id]);
    $comment = $stmt->fetch();

    if (!$comment) {
        $_SESSION['error'] = "Komentar tidak ditemukan";
        header("Location: comment");
        exit();
    }


    $pdo->beginTransaction();

    // Hapus komentar
    $stmt = $pdo->prepare("DELETE FROM blog_comments WHERE id = ?");
    $stmt->execute([$comment_id]);

    $pdo->commit();

    $_SESSION['success'] = "Komentar berhasil dihapus";
} catch (PDOException $e) {
    $pdo->rollBack();
    $_SESSION['error'] = "Gagal menghapus komentar: " . $e->getMessage();
}

header("Location: comment");
exit();
