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

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['terima'])) {
    $id_pembelian = mysqli_real_escape_string($conn, $_POST['id_pembelian']);
    $user_id = $_SESSION['id'];
    
    // Validasi pembelian ada dan status APPROVED
    $query_check = "SELECT p.*, s.nama_supplier FROM pembelian p 
                    LEFT JOIN supplier s ON p.id_supplier = s.id_supplier 
                    WHERE p.id_pembelian = '$id_pembelian' AND p.status = 'APPROVED'";
    $result_check = mysqli_query($conn, $query_check);
    
    if (mysqli_num_rows($result_check) == 0) {
        echo "<script>alert('Pembelian tidak ditemukan atau bukan status APPROVED!'); window.location='pembelianapoteker.php';</script>";
        exit;
    }
    
    $pembelian = mysqli_fetch_assoc($result_check);
    
    // Update status menjadi RECEIVED
    $query_update = "UPDATE pembelian SET status = 'RECEIVED' WHERE id_pembelian = '$id_pembelian'";
    
    if (mysqli_query($conn, $query_update)) {
        // Ambil detail pembelian
        $query_detail = "SELECT * FROM pembelian_detail WHERE id_pembelian = '$id_pembelian'";
        $result_detail = mysqli_query($conn, $query_detail);
        
        $all_success = true;
        $tanggal_sekarang = date('Y-m-d H:i:s');
        $id_gudang = 1; // Default gudang utama
        
        // Insert ke mutasi_stok untuk setiap item
        while ($detail = mysqli_fetch_assoc($result_detail)) {
            $id_obat = $detail['id_obat'];
            $jumlah = $detail['jumlah'];
            
            // Insert mutasi stok
            $query_mutasi = "INSERT INTO mutasi_stok (id_obat, id_gudang, tipe, sumber, jumlah, tanggal, keterangan, id_user)
                           VALUES ('$id_obat', '$id_gudang', 'MASUK', 'PEMBELIAN', '$jumlah', '$tanggal_sekarang', 
                                   'Pembelian #$id_pembelian', '$user_id')";
            
            if (!mysqli_query($conn, $query_mutasi)) {
                $all_success = false;
                break;
            }
            
            // Cek apakah obat sudah ada di stok
            $query_stok_check = "SELECT * FROM stok WHERE id_obat = '$id_obat' AND id_gudang = '$id_gudang'";
            $result_stok_check = mysqli_query($conn, $query_stok_check);
            
            if (mysqli_num_rows($result_stok_check) > 0) {
                // Update existing stok
                $query_stok_update = "UPDATE stok SET jumlah = jumlah + $jumlah 
                                     WHERE id_obat = '$id_obat' AND id_gudang = '$id_gudang'";
                if (!mysqli_query($conn, $query_stok_update)) {
                    $all_success = false;
                    break;
                }
            } else {
                // Insert new stok
                $query_stok_insert = "INSERT INTO stok (id_obat, id_gudang, jumlah) 
                                     VALUES ('$id_obat', '$id_gudang', '$jumlah')";
                if (!mysqli_query($conn, $query_stok_insert)) {
                    $all_success = false;
                    break;
                }
            }
        }
        
        if ($all_success) {
            echo "<script>alert('Pembelian berhasil diterima dan stok diperbarui!'); window.location='pembelianapoteker.php';</script>";
        } else {
            echo "<script>alert('Gagal memproses penerimaan pembelian!'); window.location='pembelianapoteker.php';</script>";
        }
    } else {
        echo "<script>alert('Gagal mengupdate status pembelian!'); window.location='pembelianapoteker.php';</script>";
    }
}
?>