<?php include('includes/config/config.php');
include('includes/functions.php');
include('log_entry.php');
error_log("Start Printing Request Attributes");
$requestStr = "";
foreach ($_REQUEST as $key => $value) {
	$requestStr .= $key . " : " . $value . "\n";
	error_log($key . " : " . $value . "<br />\r\n");
}
error_log("End Printing Request Attributes");
save_log($requestStr, 'Nearing Expiry', 'SAVE', 'save_pending_expiry_item.php');

header('Content-type: application/json');
$item_stock_id = $_POST['item_stock_id'];
$cleanup_qty = $_POST['cleanup_qty'];
$cleanup_date = date('Y-m-d');
$user = $_SESSION['user_id'];
$ohc_id = $_SESSION['current_ohcttype'];
$query = "";
$response_array = array();
if ($item_stock_id != null && $item_stock_id != "") {
	$sql = "select item_stock_id, item_id,item_batch_no,expiry_date from item_stock where item_stock_id='" . $item_stock_id . "' and ohc_type_id='" . $ohc_id . "'";
	$result_sql = mysqli_query($conn, $sql);
	while ($row = mysqli_fetch_assoc($result_sql)) {
		extract($row);

		$sql2 = "select * from cleanup_item_stock where item_stock_id = '" . $item_stock_id . "' and ohc_type_id='" . $ohc_id . "'";

		$result_sql2 = mysqli_query($conn, $sql2);

		if (!(mysqli_num_rows($result_sql2) > 0)) {
			$query = "insert into cleanup_item_stock set item_stock_id = '" . $row['item_stock_id'] . "',item_id='" . $row['item_id'] . "', batch_no='" . $row['item_batch_no'] . "',cleanup_qty='" . $cleanup_qty . "',expiry_date='" . $row['expiry_date'] . "',cleanup_date='" . $cleanup_date . "',modified_by = '" . $user . "' ,ohc_type_id='" . $ohc_id . "' ";
		} else {

			$query = "update cleanup_item_stock set item_stock_id = '" . $row['item_stock_id'] . "',item_id='" . $row['item_id'] . "', batch_no='" . $row['item_batch_no'] . "',cleanup_qty='" . $cleanup_qty . "',expiry_date='" . $row['expiry_date'] . "',modified_by = '" . $user . "',ohc_type_id='" . $ohc_id . "' where item_stock_id = '" . $item_stock_id . "' and ohc_type_id='" . $ohc_id . "' ";
		}
	}
}

error_log("clean query: " . $query . "  " . $sql);
if ($result = @mysqli_query($conn, $query)) {
	updateStockAtStoreLevel($_POST['item_id'], $_POST['batch_no'], $cleanup_qty, $ohc_id);

	$response_array['status'] = 'success';

	//$message = "Excel Data Imported Into the Database";
} else {
	$response_array['status'] = 'error';
	//$message = "Problem In Importing Excel Data";
}

echo json_encode($response_array);