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

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['hapus'])) {
    $id_pembelian = mysqli_real_escape_string($conn, $_POST['id_pembelian']);
    
    // Validasi hanya DRAFT yang bisa dihapus
    $query_check = "SELECT * FROM pembelian WHERE id_pembelian = '$id_pembelian' AND status = 'DRAFT'";
    $result_check = mysqli_query($conn, $query_check);
    
    if (mysqli_num_rows($result_check) == 0) {
        echo "<script>alert('Hanya pembelian DRAFT yang bisa dihapus!'); window.location='pembelianapoteker.php';</script>";
        exit;
    }
    
    // Hapus detail terlebih dahulu
    $query_delete_detail = "DELETE FROM pembelian_detail WHERE id_pembelian = '$id_pembelian'";
    
    if (mysqli_query($conn, $query_delete_detail)) {
        // Hapus pembelian
        $query_delete = "DELETE FROM pembelian WHERE id_pembelian = '$id_pembelian'";
        
        if (mysqli_query($conn, $query_delete)) {
            echo "<script>alert('Pembelian berhasil dihapus!'); window.location='pembelianapoteker.php';</script>";
        } else {
            echo "<script>alert('Gagal menghapus pembelian!'); window.location='pembelianapoteker.php';</script>";
        }
    } else {
        echo "<script>alert('Gagal menghapus detail pembelian!'); window.location='pembelianapoteker.php';</script>";
    }
}
?>