<?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`,
		`TransferAmount`,`Notes`,
		`Void`,`OfflinePayment`,`OfflineID`,`OfflineDate`,`Deposited`,`CollectingUser`
		) VALUES (DATE_ADD(NOW(), INTERVAL -4 HOUR), '" . $offlinePayment->Customer->AccountNumber . "', '" . $offlinePayment->Customer->Salesman->ID . "', '" . $offlinePayment->CPD . "', '" . $offlinePayment->CPDDate . "', '" . $offlinePayment->CashAmount . "', '" . $offlinePayment->CheckAmount . "','" . $offlinePayment->TransferAmount . "', '" . $offlinePayment->Notes . "', FALSE, TRUE, '" . $offlinePayment->OfflineID . "', '" . $offlinePayment->OrderDate . "', 0, '" . $salesmanID . "')";
		if(mysqli_query($con, $query)){
			$paymentID = mysqli_insert_id($con);
			foreach($offlinePayment->Invoices as $key =>$invoice){
				$query = "INSERT INTO PAYMENT_DETAIL (`PaymentID`,`InvoiceID`,`InvoiceDate`,`Reference`,`PartialPayment`,`SubtotalAmount`,`DiscountAmount`,`TaxAmount`,`PaymentAmount`)
				VALUES (
				'" . $paymentID . "',
				'" . $invoice->InvoiceID . "',
				'" . $invoice->InvoiceDate . "',
				'" . $invoice->OrderID . "',
				'" . $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;
				}
			}
			
			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";
			
			error_log(mysqli_error($con));
			error_log($query);
			$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);
	
	
}
if($function == "estimates"){
	$result = array();
	$estimatesUploaded = 0;
	$estimatesFailed = 0;
	
	foreach($data as $key => $offlineEstimate)	{
		$query = "INSERT INTO ESTIMATE_HEAD (AccountNumber, EstimateDate, Salesman, SalesmanEstimate, EstimateNotes, PONumber, DeliveryMethod, OfflineID, OfflineEstimateDate, OfflineEstimate) VALUES ('" . $offlineEstimate->Customer->AccountNumber . "', DATE_ADD(NOW(), INTERVAL -4 HOUR), '" . $offlineEstimate->Customer->Salesman->ID . "', True, '" . $offlineEstimate->EstimateNotes . "', '" . $offlineEstimate->PONumber . "', '" . $offlineEstimate->DeliveryMethod . "', '" . $offlineEstimate->OfflineID . "', '" . $offlineEstimate->EstimateDate . "', True)";
		
		if(mysqli_query($con, $query)){
			$EstimateID = mysqli_insert_id($con);
			$customer = $offlineEstimate->Customer;
			$query = "INSERT INTO ESTIMATE_CUSTOMER (`EstimateID`, `Name`, `Email`, `Phone`, `BillToAddress1`, `BillToAddress2`, BillToCity, BillToState,
			BillToZip, ShipToAddress1, ShipToAddress2, ShipToCity, ShipToState, ShipToZip, ContactTitle, Contact, TaxID1, TaxIDExpiration1, TaxID2, TaxIDExpiration2 ) VALUES (
				$EstimateID,
			 	'" . mysqli_real_escape_string($con, $customer->Name) . "', 
				'" . $customer->Email . "', 
				'" . $customer->Phone . "', 
				'" . mysqli_real_escape_string($con, $customer->BillToAddress1) . "', 
				'" . mysqli_real_escape_string($con, $customer->BillToAddress2) . "', 
				'" . mysqli_real_escape_string($con, $customer->BillToCity) . "', 
				'" . mysqli_real_escape_string($con, $customer->BillToState) . "', 
				'" . $customer->BillToZip . "', 
				'" . mysqli_real_escape_string($con, $customer->ShipToAddress1) . "', 
				'" . mysqli_real_escape_string($con, $customer->ShipToAddress2) . "', 
				'" . mysqli_real_escape_string($con, $customer->ShipToCity) . "', 
				'" . mysqli_real_escape_string($con, $customer->ShipToState) . "', 
				'" . $customer->ShipToZip . "', 
				'" . mysqli_real_escape_string($con, $customer->ContactTitle) . "', 
				'" . mysqli_real_escape_string($con, $customer->Contact) . "', 
				'" . $customer->TaxID1 . "', 
				'" . $customer->TaxIDExpiration1 . "', 
				'" . $customer->TaxID2 . "', 
				'" . $customer->TaxIDExpiration2 . "'
				)";
				//var_dump($query);
				mysqli_query($con, $query);
			foreach($offlineEstimate->Items as $key =>$item){
				$query = "INSERT INTO ESTIMATE_DETAIL (`EstimateID`, `Group`, `Line`, `SKU`, `Description`, `Notes`, `EstimateQty`, `AvailableQty`, `Interchange`, `Price`, `Core`)
				VALUES (
				'" . $EstimateID . "',
				'" . $item->Group . "',
				'" . $item->Line . "',
				'" . $item->SKU . "',
				'" . $item->Description . "',
				'" . $item->Notes . "',
				'" . $item->EstimateQty . "',
				'" . $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 ESTIMATE UPLOAD: " . $EstimateID, "", "", "", 0);
			$estimatesUploaded++;;
		}else{
			echo "false";
			$estimatesFailed++;
		}
		
	}
	$query = "SELECT IF(ISNULL(SUBSTRING(MAX(OfflineID),6,30)),0,SUBSTRING(MAX(OfflineID),6,30)) AS LastID FROM ESTIMATE_HEAD WHERE Salesman = '$salesmanID' AND OfflineEstimate = true";
	$result = mysqli_query($con, $query);
	$lastID = mysqli_fetch_array($result);
	$return = new stdClass();
	$return->LastEstimate = intval($lastID['LastID'])+1;
	$return->Result = "true";
	echo json_encode($return);
}

?>