<?php
// Koneksi database
include 'koneksi.php';

$data = json_decode(file_get_contents('php://input'), true);

$no_po = $data['no_po'];
$supplier = $data['id_supplier'];
$items = $data['items']; // Array item
$subtotal = $data['subtotal'];
$ppn = $data['ppn'];
$total = $data['total'];

// 1. Simpan ke tabel header
$sql_header = "INSERT INTO purchase_orders (no_po, id_supplier, tanggal, subtotal, ppn, total) VALUES ('$no_po', '$supplier', NOW(), '$subtotal', '$ppn', '$total')";
mysqli_query($conn, $sql_header);
$id_po = mysqli_insert_id($conn);

// 2. Simpan setiap item ke detail
foreach ($items as $item) {
    $desc = $item['deskripsi'];
    $qty = $item['qty'];
    $harga = $item['harga'];
    $total_baris = $item['total'];
    
    $sql_item = "INSERT INTO po_items (id_po, deskripsi, qty, harga, total_baris) VALUES ('$id_po', '$desc', '$qty', '$harga', '$total_baris')";
    mysqli_query($conn, $sql_item);
}

echo json_encode(['status' => 'success', 'message' => 'PO berhasil dirilis']);
?>