<?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;
}

$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;
$created_by = $_SESSION['user_id'];

// Validasi
if (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;
}

// Get next number
$sqlNo = "SELECT COALESCE(MAX(no), 0) + 1 as next_no FROM inventory";
$resultNo = $koneksi->query($sqlNo);
$rowNo = $resultNo->fetch_assoc();
$no = $rowNo['next_no'];

// Insert data
$sql = "INSERT INTO inventory (no, tanggal_perolehan, kategori, sumber_dana, kantor, 
        jenis_barang, jenis_inventory, harga_perolehan, created_by) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

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

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

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