<?php
include "../../root.class.php";

$db = new db_safeguard();
// var_dump($_POST);

$date_done = str_replace("T", " ", $_POST['date_to_be_done']);
$date_created = str_replace("T", " ", $_POST['date_created']);
$user_id_created = $_POST['user_id_created'];

$stock_take_id = $db->query("stock_takes", "INSERT INTO `stock_takes`(`date_created`, `user_id_created`, `date_to_be_done`) VALUES ('$date_created','$user_id_created','$date_done')");

// stock items
$stock_items_res = $db->query("stock", "SELECT * FROM `stock` WHERE stock_type != 3 AND stock_type != 2 AND stock_type != 1 ORDER BY record_id ASC");
while ($stock_item = $stock_items_res->fetch_assoc()) {
    // find if there is currently stock of that item.
    $stock_item_amount_res = $db->query("order_trans", "SELECT SUM(amount) AS total_stock FROM order_trans WHERE stock_id = " . $stock_item['record_id'] . " ORDER BY record_id ASC");
    $stock_item_amount = $stock_item_amount_res->fetch_assoc()['total_stock'] ?? 0;
    $db->query("stock_take_stock", "INSERT INTO `stock_take_stock`(`stock_take_id`, `item_id`, `amount_in_stock`, `amount_counted`) VALUES ($stock_take_id," . $stock_item['record_id'] . "," . $stock_item_amount . ",0)");
}
