<?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: produk");
    exit();
}

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

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

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

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

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

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

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

    $pdo->commit();

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

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