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

if (isset($_POST['edit'])) {
    $id_pembelian = mysqli_real_escape_string($conn, $_POST['id_pembelian']);
    $id_supplier = mysqli_real_escape_string($conn, $_POST['id_supplier']);
    $tanggal_pembelian = mysqli_real_escape_string($conn, $_POST['tanggal_pembelian']);
    $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan']);
    
    $items_data = json_decode($_POST['items_data'], true);
    
    if (empty($items_data)) {
        echo "<script>alert('Item pembelian tidak boleh kosong!'); window.history.back();</script>";
        exit;
    }

    $total_harga = 0;
    foreach ($items_data as $item) {
        $total_harga += $item['subtotal'];
    }

    $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 diedit!'); window.location='pembelianapoteker.php';</script>";
        exit;
    }

    $query_update = "UPDATE pembelian 
                    SET id_supplier = '$id_supplier', tanggal_pembelian = '$tanggal_pembelian', 
                        total_harga = '$total_harga', keterangan = '$keterangan'
                    WHERE id_pembelian = '$id_pembelian'";
    
    if (mysqli_query($conn, $query_update)) {
        $query_delete_detail = "DELETE FROM pembelian_detail WHERE id_pembelian = '$id_pembelian'";
        mysqli_query($conn, $query_delete_detail);

        $all_success = true;
        foreach ($items_data as $item) {
            $id_obat = $item['id'];
            $jumlah = $item['jumlah'];
            $harga = $item['harga'];
            $subtotal = $item['subtotal'];
            
            $query_detail = "INSERT INTO pembelian_detail (id_pembelian, id_obat, jumlah, harga, subtotal)
                           VALUES ('$id_pembelian', '$id_obat', '$jumlah', '$harga', '$subtotal')";
            
            if (!mysqli_query($conn, $query_detail)) {
                $all_success = false;
                break;
            }
        }
        
        if ($all_success) {
            echo "<script>alert('Pembelian berhasil diperbarui!'); window.location='pembelianapoteker.php';</script>";
        } else {
            echo "<script>alert('Gagal memperbarui detail pembelian!'); window.location='pembelianapoteker.php';</script>";
        }
    } else {
        echo "<script>alert('Gagal memperbarui pembelian!'); window.location='pembelianapoteker.php';</script>";
    }
}
?>