<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");

require_once "../adm_control_api/koneksi.php";

// Gunakan php://input dengan titik dua dan dua garis miring
$input = file_get_contents("php://input");
$data = json_decode($input, true);

if (!$data || !isset($data['items']) || empty($data['items'])) {
    echo json_encode([
        "status" => false,
        "message" => "Data stok tidak boleh kosong."
    ]);
    exit();
}

$id_karyawan = $conn->real_escape_string($data['id_karyawan'] ?? '');
$id_distributor = $conn->real_escape_string($data['id_distributor'] ?? '');
$tanggal_stok = $conn->real_escape_string($data['tanggal_stok'] ?? '');

if (empty($id_karyawan) || empty($id_distributor) || empty($tanggal_stok)) {
    echo json_encode([
        "status" => false,
        "message" => "Parameter id_karyawan, id_distributor, atau tanggal_stok tidak lengkap."
    ]);
    exit();
}

// Gunakan Transaction
$conn->begin_transaction();

try {
    $stmt = $conn->prepare("INSERT INTO riwayat_stok_opname 
        (id_produk_master, id_distributor, id_karyawan, tanggal_stok, stok_kemaren, stok_terbaru, keterangan) 
        VALUES (?, ?, ?, ?, ?, ?, ?)");

    foreach ($data['items'] as $item) {
        $id_produk_master = intval($item['id_produk_master']);
        $stok_kemaren = intval($item['stok_kemaren'] ?? 0);
        $stok_terbaru = intval($item['stok_terbaru']);
        $keterangan = $item['keterangan'] ?? 'Stok Opname Mobile';

        $stmt->bind_param(
            "iissiis", 
            $id_produk_master, 
            $id_distributor, 
            $id_karyawan, 
            $tanggal_stok, 
            $stok_kemaren, 
            $stok_terbaru, 
            $keterangan
        );
        $stmt->execute();
    }

    $conn->commit();
    echo json_encode([
        "status" => true,
        "message" => "Berhasil menyimpan riwayat stok opname!"
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        "status" => false,
        "message" => "Gagal menyimpan ke database: " . $e->getMessage()
    ]);
}

$conn->close();
?>