<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'A') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once '../database/koneksi.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$id = $_POST['id'] ?? 0;
$tanggal_perolehan = $_POST['tanggal_perolehan'] ?? '';
$kategori = $_POST['kategori'] ?? 'Peralatan';
$sumber_dana = $_POST['sumber_dana'] ?? '';
$kantor = $_POST['kantor'] ?? '';
$jenis_barang = $_POST['jenis_barang'] ?? '';
$jenis_inventory = $_POST['jenis_inventory'] ?? '';
$harga_perolehan = $_POST['harga_perolehan'] ?? 0;

// Validasi
if (empty($id) || empty($tanggal_perolehan) || empty($sumber_dana) || 
    empty($kantor) || empty($jenis_barang) || empty($jenis_inventory)) {
    echo json_encode(['success' => false, 'message' => 'Semua field harus diisi']);
    exit;
}

$sql = "UPDATE inventory SET 
        tanggal_perolehan = ?, 
        kategori = ?, 
        sumber_dana = ?, 
        kantor = ?, 
        jenis_barang = ?, 
        jenis_inventory = ?, 
        harga_perolehan = ?
        WHERE id = ?";

$stmt = $koneksi->prepare($sql);
$stmt->bind_param("ssssssd", $tanggal_perolehan, $kategori, $sumber_dana, 
                  $kantor, $jenis_barang, $jenis_inventory, $harga_perolehan, $id);

if ($stmt->execute()) {
    echo json_encode([
        'success' => true,
        'message' => 'Data berhasil diupdate'
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Gagal mengupdate data: ' . $stmt->error
    ]);
}

$stmt->close();
$koneksi->close();
?>