<?php
include "../../root.class.php";
$db = new db_safeguard();
$index = 1;
$fail = 0;
$date = date("Y-m-d H:i", strtotime("+ 2 Hours"));

while ($fail == 0) {

    if (isset($_POST["stock_id_$index"])) {

        $db->query("stock_take_stock",  "UPDATE stock_take_stock SET amount_counted = {$_POST["stock_amount_$index"]} WHERE item_id = {$_POST["stock_id_$index"]} AND stock_take_id = {$_GET['stock_take_id']}");

        // get current stock to make adjustments
        $current_stock_count = $db->query("order_trans", "SELECT sum(amount) as total_stock FROM order_trans WHERE stock_id = {$_POST["stock_id_$index"]}");
        $current_stock = $current_stock_count->fetch_assoc();
        $diff = $_POST["stock_amount_$index"] * 1 - $current_stock['total_stock'] * 1;
        // echo "<br> approved amount : ". $_POST["stock_amount_$index"]. " system stock : ". $current_stock['total_stock']." diff: ".$diff;
        $db->query("order_trans", "INSERT INTO order_trans (stock_id,non_stock_id,amount,date_time,order_id,user_id) VALUES ({$_POST["stock_id_$index"]},0,$diff,'$date',0,0)");

    } else {
        $fail = 1;
    }
    $index++;
}


if ($_GET['save'] == 0) {
    $db->query("stock_takes", "UPDATE stock_takes SET date_assesed = '$date', user_id_assesed = {$_SESSION['user_id']}, disision = 'APPROVED' WHERE record_id = {$_GET['stock_take_id']}");
}

echo "1";