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

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



$function = $_REQUEST['f'];
if($function == "receiveByUPC"){
	//if parameter undo is set and equals to the string "true", returns true, else false.
	$undo = isset($_REQUEST['undo'])&&$_REQUEST['undo']=="true"?true:false;
    receiveByUPC($_REQUEST['poid'], $_REQUEST['upc'], $undo);
}elseif($function == "getPendingInvoices"){
	getPendingInvoices();
}elseif($function =="saveReviewField"){
	saveReviewField($_REQUEST['po'], $_POST);
}elseif($function == "saveReviewFieldItem"){
	saveReviewFieldItem($_POST['id'], $_POST['value']);

}elseif($function == "deletePOItem"){
	deletePOItem($_REQUEST['id']);

}elseif($function == "addNewItem"){
	addNewItem($_REQUEST['po'], $_REQUEST['sku']);
}elseif($function == "setPOFinalize"){
	setPOFinalize($_REQUEST['po']);
}elseif($function == "setPOComplete"){
	setPOComplete($_REQUEST['po']);
}elseif($function == "addNewPOItems"){

	addNewPOItems($_REQUEST['Line'], $_REQUEST['Group'], $_REQUEST['VendorID']);


}elseif($function == "cleanNewPO"){

	cleanNewPO();


}elseif($function == "createNewPO"){
	createNewPO();

}elseif($function == "setPOReceived"){
	$po = new PurchaseOrder($_REQUEST['po']);
	$po->Received = 1;
	if($po->save()){
		echo "true";
		return;
	}
	//setPOFinalize();
}elseif($function == "sendPO"){
	sendPO($_REQUEST['po']);
}elseif($function == "deletePO"){
	deletePO($_REQUEST['poid']);
}elseif($function == "saveVendor"){
	saveVendor($_POST['data']);
}elseif($function == "getVendorInfo"){
	getVendorInfo($_REQUEST['vid']);
}elseif($function == "deleteVendor"){
	deleteVendor($_POST['vid']);
}else{
    die( "Invalid function");
}
function getVendorInfo($vendorID){
	$vendor = new Vendor($vendorID);
	$vendor = json_encode($vendor);
	echo $vendor;

}
function deleteVendor($vendorID){
	global $con;
	$query = "DELETE FROM VENDOR WHERE VendorID = $vendorID";
	if(mysqli_query($con, $query )){
		echo "true";
	}else{
		echo mysqli_error($con);
	}
}
function saveVendor($data){
	global $con;
	if($data["VendorID"] !== ""){
		$vendor = new Vendor($data['VendorID']);
		unset($data['VendorID']);
		foreach ($data as $key => $value) {
			$vendor->$key = $value;
		}
		$vendor->save();
		echo "true";
	}else{
		$keys = array_keys($data);
		$values = array_values($data);
		foreach ($keys as $key => $value) {
			$keys[$key] = "`$value`";
		}
		foreach ($values as $key => $value) {
			$values[$key] = "'$value'";
		}
		$query = "INSERT INTO VENDOR (" . implode($keys, ' ,') . ") VALUES (" . implode($values, ',') . ")";

		if($result = mysqli_query($con, $query)){
			echo "true" ;
		}else{

			echo mysqli_error($con);
		}

	}
}
function deletePO($poId){
	global $con;
	$query = "UPDATE PURCHASE_ORDER_HEADER SET Void = 1 WHERE PurchaseOrderID = $poId";
	$result = mysqli_query($con, $query);
	if($result){
		echo "true";
	}else{
		echo mysqli_error($con);
	}
}
function createNewPO(){
	global $con;
	$query = "INSERT INTO PURCHASE_ORDER_HEADER (PurchaseOrderID) VALUES (0)";
	$result = mysqli_query($con,  $query);
	$PurchaseOrderID = mysqli_insert_id($con);
	$query = "DELETE FROM PURCHASE_ORDER_HEADER WHERE PurchaseOrderID = $PurchaseOrderID";
	$result = mysqli_query($con,  $query);
	$query = "UPDATE PURCHASE_ORDER_HEADER , PURCHASE_ORDER_DETAIL SET PURCHASE_ORDER_HEADER.PurchaseOrderID = $PurchaseOrderID, PURCHASE_ORDER_DETAIL.PurchaseOrderID = $PurchaseOrderID WHERE PURCHASE_ORDER_HEADER.PurchaseOrderID = 1 AND PURCHASE_ORDER_HEADER.PurchaseOrderID = PURCHASE_ORDER_DETAIL.PurchaseOrderID";

	$result = mysqli_query($con,  $query);
	$return = new stdClass();
	if($result = mysqli_query($con,  $query)){
		$return->Result = true;
		$return->PurchaseOrderID = $PurchaseOrderID;
	}else{
		$return->Result = false;
		$return->Error = mysqli_error($con);
	}
	echo json_encode($return);
	return $return;


}
function sendPO($PurchaseOrderID){
	$po = new PurchaseOrder($PurchaseOrderID);
	if($po->sendEmail()){
		$po->Sent = 1;
		$po->save();
		echo "true";
	}else{
		echo "false";
	}
}
function cleanNewPO(){
	global $con;
	$query = "DELETE FROM PURCHASE_ORDER_DETAIL WHERE OrderQty IS NULL OR OrderQty = 0 AND PurchaseOrderID = 1";
	$stmt = $con->prepare($query);
	if($stmt->execute()){
		echo "true";
	}
}
function addNewPOItems($Line, $Group, $Vendor){
	global $con;
	$query = "INSERT INTO PURCHASE_ORDER_DETAIL (`PurchaseOrderID`, `Line`, `SKU`, `Description`, `Cost`) (SELECT 1, `Line`, `SKU`, Description, Cost FROM INVENTORY WHERE `Line` LIKE ? AND `Group` LIKE ? AND VendorID LIKE ? AND SKU NOT IN (SELECT SKU FROM PURCHASE_ORDER_DETAIL WHERE PurchaseOrderID = 1))";
	$stmt = $con->prepare($query);
	$stmt->bind_param("sss", $Line, $Group, $Vendor);

	if($stmt->execute()){
		echo "true";
	}
}
function setPOComplete($po){
	$po = new PurchaseOrder($po);
	if($po->uploadComplete()){
		echo "true";
	}

}
function setPOFinalize($po){
	$po = new PurchaseOrder($po);
	$po->Confirmed = 1;
	$po->ConfirmedDate = "NOW()";
	$po->ConfirmedUser = $_SESSION['Username'];
	$po->save();
}
function addNewItem($po, $sku){
	$po = new PurchaseOrder($po);
	if($po->addItem($sku)){
		echo "true";
	}

}
function deletePOItem($id){
	$item = new PurchaseOrderItem($id);
	if($item->delete()){
		echo "true";
	}

}
function saveReviewField($po, $data){
	global $con;
	$po = new PurchaseOrder($po);
	$id = $data['id'];
	$po->{$data['id']} = $data['value'];
	if($po->save()){
		echo $data['value'];
	}




}
function saveReviewFieldItem($id, $data){
	global $con;
	$field = explode("-", $id)[1];
	$id = explode("-", $id)[0];
	//die($field . "  and id = " . $id);
	$item = new PurchaseOrderItem($id);

	$item->{$field} = $data;
	//die($data);
	if($item->save()){
		echo $data;
	}
}


function receiveByUPC($poid, $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);

	$return = new stdClass();
	//UPC EXISTS
	if(mysqli_num_rows($result)){
		$row = mysqli_fetch_array($result);
		$po = new PurchaseOrder($poid);
		$item = $po->getOrderItem($row['Line'], $row['SKU']);
		$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;
		}
		$factor = 1;
		if($undo){
			$factor = -1;
		}
		$po->PackagesReceived += 1*$factor;
		$item->PackagesReceived += 1*$factor;
		$item->ReceivedQty += $row['Qty']*$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;

}


?>
