<?php
include('../session.php');

// Nonaktifkan error agar tidak ganggu header()
error_reporting(0);

// Validasi parameter
if (!isset($_GET['cuid']) || !isset($_GET['jenis'])) {
    header('location:../promo.php?notif=7'); // notif=7 parameter tidak lengkap
    exit();
}

$id    = intval($_GET['cuid']);
$jenis = intval($_GET['jenis']);
$upload_dir = "../../upload/";

// Cek data post yang akan dihapus
$query = mysqli_query($conn, "SELECT image FROM tb_post WHERE cuid = '$id' LIMIT 1");
if ($query && mysqli_num_rows($query) > 0) {
    $row = mysqli_fetch_assoc($query);
    $old_image = $row['image'];

    // Hapus file gambar lama jika bukan default
    if (!empty($old_image) && $old_image != 'no-photo.jpg' && file_exists($upload_dir . $old_image)) {
        unlink($upload_dir . $old_image);
    }

    // Hapus data dari database
    if (mysqli_query($conn, "DELETE FROM tb_post WHERE cuid = '$id'")) {
        // Redirect ke halaman sesuai jenis
        if ($jenis == 0) {
            header('location:../post.php?notif=1'); // berhasil hapus post biasa
        } else {
            header('location:../promo.php?notif=1'); // berhasil hapus promo
        }
        exit();
    } else {
        // Gagal query
        if ($jenis == 0) {
            header('location:../post.php?notif=5'); // error DB
        } else {
            header('location:../promo.php?notif=5');
        }
        exit();
    }
} else {
    // Data tidak ditemukan
    if ($jenis == 0) {
        header('location:../post.php?notif=6'); // tidak ditemukan
    } else {
        header('location:../promo.php?notif=6');
    }
    exit();
}
?>
