<?php
// FILE: hapuspembelian.php
include 'koneksi.php';

if (isset($_POST['hapus'])) {
    $id_pembelian = $_POST['id_pembelian'];

    // Cek apakah pembelian ada
    $cek_query = "SELECT * FROM pembelian WHERE id_pembelian = '$id_pembelian'";
    $cek_result = mysqli_query($conn, $cek_query);

    if (mysqli_num_rows($cek_result) == 0) {
        echo "<script>alert('Data pembelian tidak ditemukan!'); window.location='pembelian.php';</script>";
    } else {
        // Mulai transaksi
        mysqli_begin_transaction($conn);

        try {
            // Hapus detail pembelian terlebih dahulu
            $hapus_detail = "DELETE FROM pembelian_detail WHERE id_pembelian = '$id_pembelian'";
            mysqli_query($conn, $hapus_detail);

            // Hapus data pembelian
            $hapus_pembelian = "DELETE FROM pembelian WHERE id_pembelian = '$id_pembelian'";
            mysqli_query($conn, $hapus_pembelian);

            // Commit transaksi jika semua berhasil
            mysqli_commit($conn);
            echo "<script>alert('Pembelian berhasil dihapus!'); window.location='pembelian.php';</script>";
        } catch (Exception $e) {
            // Rollback jika ada error
            mysqli_rollback($conn);
            echo "<script>alert('Gagal menghapus pembelian.'); window.location='pembelian.php';</script>";
        }
    }
}
?>