<?php 

include("connect.php");
global $con, $config;
$isCustomer = $_SESSION['isCustomer'];
if($isCustomer){
	die('This functions is only for salesmen');
}
$function = $_REQUEST['f'];

$data  = urldecode($_REQUEST['data']);
$data = json_decode($data);


$salesmanID = $_REQUEST['sm'];
//creating new entry in orders db
if($function =="orders"){
	$result = array();
	$ordersUploaded = 0;
	$ordersFailed = 0;
	
	foreach($data as $key => $offlineOrder)	{
		$query = "INSERT INTO ORDER_HEAD (AccountNumber, OrderDate, Salesman, SalesmanOrder, OrderNotes, PONumber, DeliveryMethod, OfflineID, OfflineOrderDate, OfflineOrder) VALUES ('" . $offlineOrder->Customer->AccountNumber . "', DATE_ADD(NOW(), INTERVAL -4 HOUR), '" . $offlineOrder->Customer->Salesman->ID . "', True, '" . $offlineOrder->OrderNotes . "', '" . $offlineOrder->PONumber . "', '" . $offlineOrder->DeliveryMethod . "', '" . $offlineOrder->OfflineID . "', '" . $offlineOrder->OrderDate . "', True)";
		if(mysqli_query($con, $query)){
			$orderID = mysqli_insert_id($con);
		
			foreach($offlineOrder->Items as $key =>$item){
				$query = "INSERT INTO ORDER_DETAIL (`OrderID`, `Group`, `Line`, `SKU`, `Description`, `Notes`, `OrderQty`, `AvailableQty`, `Interchange`, `Price`, `Core`)
				VALUES (
				'" . $orderID . "',
				'" . $item->Group . "',
				'" . $item->Line . "',
				'" . $item->SKU . "',
				'" . $item->Description . "',
				'" . $item->Notes . "',
				'" . $item->OrderQty . "',
				'" . $item->AvailableQty . "',
				'" . $item->Interchange . "',
				'" . $item->Price . "',
				'" . $item->Core . "'
				)";
				mysqli_query($con, $query);
				$query = "UPDATE INVENTORY SET Qty = Qty - " . mysqli_real_escape_string($con, $item->OrderQty) . " WHERE `Group` = '" . mysqli_real_escape_string($con, $item->Group) . "' AND `Line` = '" . mysqli_real_escape_string($con, $item->Line) . "' AND `SKU` = '" . mysqli_real_escape_string($con, $item->SKU) . "'";
				mysqli_query($con, $query);
			}
			//AddCartLogEntry("OFFLINE ORDER UPLOAD: " . $orderID, "", "", "", 0);
			$ordersUploaded++;;
		}else{
			echo "false";
			$ordersFailed++;
		}
		
	}
	$query = "SELECT IF(ISNULL(SUBSTRING(MAX(OfflineID),6,30)),0,SUBSTRING(MAX(OfflineID),6,30)) AS LastID FROM ORDER_HEAD WHERE Salesman = '$salesmanID' AND OfflineOrder = true";
	$result = mysqli_query($con, $query);
	$lastID = mysqli_fetch_array($result);
	$return = new stdClass();
	$return->LastOrder = intval($lastID['LastID'])+1;
	$return->Result = "true";
	echo json_encode($return);
}
if($function == "payments"){
	$result = array();
	$paymentsUploaded = 0;
	$paymentsFailed = 0;
	
	foreach($data as $key => $offlinePayment)	{
		$query = "INSERT INTO PAYMENT_HEAD (PaymentDate, AccountNumber, SalesmanID, CPD, CPDDate, CashAmount, CheckAmount, Notes, OfflinePayment, OfflineID, OfflineDate) VALUES (DATE_ADD(NOW(), INTERVAL -4 HOUR), '" . $offlinePayment->Customer->AccountNumber . "', '" . $offlinePayment->Customer->Salesman->ID . "', '" . $offlinePayment->CPD . "', '" . $offlinePayment->CPDDate . "', '" . $offlinePayment->CashAmount . "', '" . $offlinePayment->CheckAmount . "', '" . $offlinePayment->Notes . "', TRUE, '" . $offlinePayment->OfflineID . "', '" . $offlinePayment->OrderDate . "')";
		if(mysqli_query($con, $query)){
			$paymentID = mysqli_insert_id($con);
		
			foreach($offlinePayment->Invoices as $key =>$invoice){
				$query = "INSERT INTO PAYMENT_DETAIL (`PaymentID`, `InvoiceNumber`, `InvoiceDate`, `Reference`, `PartialPayment`, `SubtotalAmount`, `DiscountAmount`, `TaxAmount`, `PaymentAmount`)
				VALUES (
				'" . $paymentID . "',
				'" . $invoice->InvoiceNumber . "',
				'" . $invoice->InvoiceDate . "',
				'" . $invoice->Reference . "',
				'" . $invoice->PartialPayment . "',
				'" . $invoice->Subtotal . "',
				'" . $invoice->Discount . "',
				'" . $invoice->Tax . "',
				'" . $invoice->PaymentAmount . "'
				)";
				if(!mysqli_query($con, $query)){
					echo mysqli_error($con) . "<br>Query: " . $query;
				}
			}
			
			foreach($offlinePayment->Checks as $key =>$check){
				$query = "INSERT INTO PAYMENT_CHECK (`PaymentID`, `CheckNumber`, `Amount`)
				VALUES (
				'" . $paymentID . "',
				'" . $check->CheckNumber . "',
				'" . $check->Amount . "'
				)";
				if(!mysqli_query($con, $query)){
					echo mysqli_error($con) . "<br>Query: " . $query;
				}
			}
			
			foreach($offlinePayment->Credits as $key =>$credit){
				$query = "INSERT INTO PAYMENT_CREDIT (`PaymentID`, `CreditDate`, `CreditNumber`, `Reference`, `Subtotal`, `Tax`, `Discount`, `Total`)
				VALUES (
				'" . $paymentID . "',
				'" . $credit->CreditDate . "',
				'" . $credit->CreditNumber . "',
				'" . $credit->Reference . "',
				'" . $credit->Subtotal . "',
				'" . $credit->Tax . "',
				'" . $credit->Discount . "',
				'" . $credit->Total . "'
				)";
				if(!mysqli_query($con, $query)){
					echo mysqli_error($con) . "<br>Query: " . $query;
				}
			}
			if(isset($offlinePayment->Reminder)){
				foreach($offlinePayment->Reminder as $key =>$reminder){
					$query = "INSERT INTO PAYMENT_REMINDER (`PaymentID`, `Reason`, `Notes`, `NextVisitDate`)
					VALUES (
					'" . $paymentID . "',
					'" . $reminder->Reason . "',
					'" . $reminder->NextVisitDate . "',
					'" . $reminder->Notes . "'
					)";
					if(!mysqli_query($con, $query)){
						echo mysqli_error($con) . "<br>Query: " . $query;
					}
				}	
			}
			
			$paymentsUploaded++;;
		}else{
			echo "false";
			$paymentsFailed++;
		}
		
	}
	$query = "SELECT IF(ISNULL(SUBSTRING(MAX(OfflineID),6,30)),0,SUBSTRING(MAX(OfflineID),6,30)) AS LastID FROM PAYMENT_HEAD WHERE SalesmanID = '$salesmanID' AND OfflinePayment = true";
	$result = mysqli_query($con, $query);
	$lastID = mysqli_fetch_array($result);
	$return = new stdClass();
	$return->LastPayment = intval($lastID['LastID'])+1;
	$return->Result = "true";
	echo json_encode($return);
	
	
}

?>