<?php
header('content-type:application/json');
include($_SERVER['DOCUMENT_ROOT'] . "/API/connection/conn.php");
$stock_id = addslashes(isset($_POST['id']) ? $_POST['id'] : '');
$warehouse = addslashes(isset($_POST['warehouse']) ? $_POST['warehouse'] : '');

$query1 = mysqli_query($conn, "SELECT * FROM stocklist WHERE id = '$stock_id'");
$affected_row = mysqli_affected_rows($conn);
if ($affected_row > 0) {
    while ($spec1 = mysqli_fetch_assoc($query1)) {
        $category = $spec1["category"];
        $item = $spec1["item"];
        $unitofmeasurement = $spec1["unitofmeasurement"];
        $quantity = $spec1["quantity"];
        $date = DATE("Y-m-d");
        $time = DATE("H:i:s");

        $query2 = mysqli_query($conn, "SELECT * FROM stockwarehouses WHERE category = '$category' AND item = '$item'");
        $affected_row1 = mysqli_affected_rows($conn);
        if ($affected_row1 == 0) {
            $sql = "INSERT INTO stockwarehouses (warehouse, category, item, unitofmeasurement, quantity, date, time) VALUES ('$warehouse','$category','$item','$unitofmeasurement','$quantity', '$date', '$time')";
            if (mysqli_query($conn, $sql)) {
            } else {
                echo "Error: " . mysqli_error($conn);
            }

            $sql = ("UPDATE stocklist SET status = 'Warehoused' WHERE id = '$stock_id'");
            if (mysqli_query($conn, $sql)) {
                $statusCode = 200;
                $statusMessage = "Updated Successfully.";
            } else {
                $statusCode = 1042;
                $statusMessage = mysqli_error($conn);
            }
        } else {
            $sql = "UPDATE stockwarehouses SET quantity = quantity + '$quantity', date = '$date', time = '$time' WHERE category = '$category' AND item = '$item'";
            if (mysqli_query($conn, $sql)) {
            } else {
                echo "Error: " . mysqli_error($conn);
            }

            $sql = ("UPDATE stocklist SET status = 'Warehoused' WHERE id = '$stock_id'");
            if (mysqli_query($conn, $sql)) {
                $statusCode = 200;
                $statusMessage = "Updated Successfully.";
            } else {
                $statusCode = 1042;
                $statusMessage = mysqli_error($conn);
            }
        }
    }
}

$resultData = array('code' => $statusCode, 'message' => $statusMessage);
echo json_encode($resultData);
