<?php
include 'koneksi.php';

if (isset($_POST['hapus'])) {
    $id_obat = mysqli_real_escape_string($conn, $_POST['id_obat']);

    // Ambil data obat sebelum dihapus
    $query_get_obat = "SELECT o.barcode, o.nama_obat, COALESCE(SUM(s.jumlah), 0) as total_stok 
                       FROM obat o 
                       LEFT JOIN stok s ON o.id_obat = s.id_obat 
                       WHERE o.id_obat = '$id_obat' 
                       GROUP BY o.id_obat";
    $result_obat = mysqli_query($conn, $query_get_obat);
    
    if ($result_obat && mysqli_num_rows($result_obat) > 0) {
        $row = mysqli_fetch_assoc($result_obat);
        $barcode_filename = $row['barcode'];
        $nama_obat = $row['nama_obat'];
        $total_stok = $row['total_stok'];
        
        // Mulai transaksi
        mysqli_begin_transaction($conn);
        
        try {
            // 1. Hapus semua data stok terkait obat ini di semua gudang
            if ($total_stok > 0) {
                $query_delete_stok = "DELETE FROM stok WHERE id_obat = '$id_obat'";
                if (!mysqli_query($conn, $query_delete_stok)) {
                    throw new Exception('Gagal menghapus data stok obat');
                }
            }
            
            // 2. Hapus data obat dari database
            $query_delete_obat = "DELETE FROM obat WHERE id_obat = '$id_obat'";
            if (!mysqli_query($conn, $query_delete_obat)) {
                throw new Exception('Gagal menghapus data obat');
            }
            
            // Commit transaksi
            mysqli_commit($conn);
            
            // 3. Hapus file barcode jika ada (path: assets/images/barcode/)
            $barcode_path = 'assets/images/barcode/' . $barcode_filename;
            if (file_exists($barcode_path) && !empty($barcode_filename)) {
                unlink($barcode_path);
            }
            
            // Buat pesan notifikasi
            $message = "✓ Obat '$nama_obat' berhasil dihapus!";
            if ($total_stok > 0) {
                $message .= "\\n\\n📦 Data stok sebanyak $total_stok unit di semua gudang juga telah dihapus.";
            }
            $message .= "\\n🗑️ File barcode '$barcode_filename' telah dihapus.";
            
            echo "<script>alert('$message'); window.location='obat.php';</script>";
            
        } catch (Exception $e) {
            // Rollback jika gagal
            mysqli_rollback($conn);
            echo "<script>alert('❌ Gagal menghapus obat: " . $e->getMessage() . "'); window.location='obat.php';</script>";
        }
        
    } else {
        echo "<script>alert('❌ Data obat tidak ditemukan!'); window.location='obat.php';</script>";
    }
}
?>