<?php
$conn = new mysqli("localhost", "root", "", "stock_opname");

// Cek dan upload foto jika ada
$foto = "";
if (!empty($_FILES['foto']['name'])) {
    $targetDir = "uploads/foto_barang/";
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    $fotoName = time() . "_" . basename($_FILES["foto"]["name"]);
    $targetFile = $targetDir . $fotoName;
    move_uploaded_file($_FILES["foto"]["tmp_name"], $targetFile);
    $foto = $targetFile;
}

// Simpan data ke tabel barang
$stmt = $conn->prepare("INSERT INTO barang (part_number, nama_barang, satuan, barcode, foto, keterangan) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $_POST['part_number'], $_POST['nama_barang'], $_POST['satuan'], $_POST['barcode'], $foto, $_POST['keterangan']);
$stmt->execute();

if ($stmt->affected_rows > 0) {
    echo "Barang berhasil disimpan. <a href='form_barang.php'>Kembali</a>";
} else {
    echo "Gagal menyimpan. <a href='form_barang.php'>Coba lagi</a>";
}
