<?php
include 'koneksi.php';

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

    // Validasi input
    if (empty($id_stok)) {
        echo "<script>alert('❌ Data tidak valid!'); window.location='stok.php';</script>";
        exit;
    }

    // Ambil informasi stok sebelum dihapus
    $query_info = "SELECT s.jumlah, o.nama_obat, o.kode_obat, o.satuan, g.nama_gudang,
                   (SELECT COALESCE(SUM(jumlah), 0) FROM stok WHERE id_obat = o.id_obat) as total_stok_sebelum
                   FROM stok s
                   JOIN obat o ON s.id_obat = o.id_obat
                   JOIN gudang g ON s.id_gudang = g.id_gudang
                   WHERE s.id_stok = '$id_stok'";
    $result_info = mysqli_query($conn, $query_info);
    
    if (mysqli_num_rows($result_info) == 0) {
        echo "<script>alert('❌ Data stok tidak ditemukan!'); window.location='stok.php';</script>";
        exit;
    }
    
    $info = mysqli_fetch_assoc($result_info);
    $total_stok_setelah = $info['total_stok_sebelum'] - $info['jumlah'];

    // Hapus stok
    $query = "DELETE FROM stok WHERE id_stok = '$id_stok'";
    
    if (mysqli_query($conn, $query)) {
        echo "<script>
            alert('✓ Stok berhasil dihapus!\\n\\n📦 Info:\\nObat: {$info['nama_obat']}\\nGudang: {$info['nama_gudang']}\\nJumlah Dihapus: {$info['jumlah']} {$info['satuan']}\\n\\nTotal Stok Sebelum: {$info['total_stok_sebelum']} {$info['satuan']}\\nTotal Stok Setelah: $total_stok_setelah {$info['satuan']}');
            window.location='stok.php';
        </script>";
    } else {
        echo "<script>alert('❌ Gagal menghapus stok: " . mysqli_error($conn) . "'); window.location='stok.php';</script>";
    }
}
?>