<?php
include("../connect.php");
include("../session.php");

$isAdmin = $_SESSION['isAdmin'];
if (!$isAdmin) {
	header("Location: logout.php");
}



$function = $_REQUEST['f'];
if($function == "loadItem"){
	//if parameter undo is set and equals to the string "true", returns true, else false.
	$undo = isset($_REQUEST['undo'])&&$_REQUEST['undo']=="true"?true:false;
    loadItem($_REQUEST['wid'], $_REQUEST['upc'], $undo);
}elseif($function == "getPendingInvoices"){
	getPendingInvoices();
}else{
    die( "Invalid function");
}



function loadItem($wid, $upc, $undo = false){
	global $con;
	$query = "SELECT PRODUCT_UPC.* FROM INVENTORY JOIN PRODUCT_UPC USING(`Line`, `SKU`) WHERE UPC LIKE '$upc' OR SKU LIKE '$upc'";
	$result = mysqli_query($con, $query);
	//echo $query;
	$return = new stdClass();
	//UPC EXISTS
	if(mysqli_num_rows($result)){
		$row = mysqli_fetch_array($result);
		$warehouse = new Warehouse($wid);
		$factor = 1;
		if($undo){
			$factor = -1;
		}
		$item = $warehouse->addItem($row['Line'], $row['SKU'], $row['Qty']*$factor);
		$item = new WarehouseItem($item);
		$item->CurrentLoadedQty = $row['Qty']*$factor;
		// $query2 = "SELECT * FROM PRODUCT_UPC WHERE SKU LIKE '" . $row['SKU'] . "' AND `Line` LIKE '" . $row['Line'] . "' ORDER BY Qty DESC";
		// $result2 = mysqli_query($con, $query2);
		// $row2= mysqli_fetch_array($result2);
		// if(mysqli_num_rows($result2) > 0){
		// 	$item->BoxQty = $row2['Qty'];
		// }else{
		// 	$item->BoxQty = 1;
		// }

		// $po->PackagesReceived += 1*$factor;
		// $item->PackagesReceived += 1*$factor;

		// $item->CurrentReceivedQty = $row['Qty']*$factor;
		// $po->save();
		// $item->save();
		$return->Result = True;
		$return->Data = $item;
		// $return->Data->PackagesReceived = $po->PackagesReceived;
		// $return->Data->Packages = $po->Packages;
		echo safe_json_encode($return);
	}else{
		$return->Result = false;
		$return->Error = "upc_not_exists";
		echo safe_json_encode($return);
	}



	return;

}


?>
