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

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

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

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

// Path untuk upload gambar
$upload_dir = '../upload/blog/';
$base_url = 'http://' . $_SERVER['HTTP_HOST'] . '/upload/blog/';

try {
    // Cek apakah post ada
    $stmt = $pdo->prepare("SELECT judul, gambar FROM blog_posts WHERE id = ?");
    $stmt->execute([$id]);
    $post = $stmt->fetch();

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

    // Proses penghapusan
    $pdo->beginTransaction();

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

    // Hapus gambar jika ada
    if (!empty($post['gambar'])) {
        $image_path = str_replace($base_url, $upload_dir, $post['gambar']);
        if (file_exists($image_path)) {
            unlink($image_path);
        }
    }

    $pdo->commit();

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

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