<?php


if(stripos($_SERVER['SCRIPT_NAME'],"/admin/")===false?false:true){
	include_once("../connect.php");
	include_once("../session.php");
	require_once("../assets/dropphp/DropboxClient.php");
	require_once("../assets/dropphp/demo-lib.php");
	//demo_init();
}else{
	include_once("connect.php");
	include_once("session.php");
	//require_once("./assests/dropphp/DropboxClient.php");
}

$return_url = $root . "/admin/mod.php?p=orderqueue&a=functions&f=getPendingOrders";
$function = $_REQUEST['f'];
if($function == "getPendingOrders"){
	getPendingOrders();
}elseif($function == "setInProcess"){
   setInProcess($_REQUEST['id']);
}elseif($function == "setProcessed"){
   setProcessed($_REQUEST['id']);
}elseif($function == "setOnHold"){
	setOnHold($_REQUEST['id'], $_REQUEST['reason']);
}elseif($function == "setDelete"){
	setDelete($_REQUEST['id'], $_REQUEST['reason']);
}elseif($function == "compareChanges"){
	var_dump(compareChanges('order_head_update_time'));
}


function getPendingOrders(){
	global $con;
	$addOn = "LEFT JOIN (SELECT AccountNumber, ElapsedDays, SUM(Balance) Balance FROM ACCOUNTS_RECEIVABLE_AGING_DELIVERY_CACHE WHERE Balance != 0  GROUP BY AccountNumber) DUES USING(AccountNumber) ";
	//$query = "SELECT ORDER_HEAD.*, CUSTOMER.Name FROM ORDER_HEAD, CUSTOMER WHERE ORDER_HEAD.AccountNumber = CUSTOMER.AccountNumber AND Processed = FALSE AND (ProcessUser LIKE '' OR ProcessUser LIKE '" . $_SESSION['Username'] . "') AND DeleteOrder != 1";
	$query = "SELECT 1 Priority, ORDER_HEAD.*, CUSTOMER.Name, DUES.ElapsedDays DueDays FROM ORDER_HEAD, CUSTOMER $addOn WHERE ORDER_HEAD.AccountNumber = CUSTOMER.AccountNumber AND Processed = FALSE AND (ProcessUser LIKE '' OR ProcessUser LIKE '" . $_SESSION['Username'] . "') AND DeleteOrder != 1 AND (DeliveryMethod LIKE '%SAME%DA%' OR OrderNotes  LIKE '%SAME%DA%')
UNION
SELECT 2 Priority, ORDER_HEAD.*, CUSTOMER.Name, DUES.ElapsedDays DueDays FROM ORDER_HEAD, CUSTOMER $addOn WHERE ORDER_HEAD.AccountNumber = CUSTOMER.AccountNumber AND Processed = FALSE AND (ProcessUser LIKE '' OR ProcessUser LIKE '" . $_SESSION['Username'] . "') AND DeleteOrder != 1 AND (DeliveryMethod LIKE '%PICKUP%' OR OrderNotes  LIKE '%RECOGER%')
UNION
SELECT 3 Priority, ORDER_HEAD.*, CUSTOMER.Name, DUES.ElapsedDays DueDays FROM ORDER_HEAD, CUSTOMER $addOn WHERE ORDER_HEAD.AccountNumber = CUSTOMER.AccountNumber AND Processed = FALSE AND (ProcessUser LIKE '' OR ProcessUser LIKE '" . $_SESSION['Username'] . "') AND DeleteOrder != 1 AND (DeliveryMethod NOT LIKE '%SAME%DA%' AND OrderNotes NOT LIKE '%SAME%DA%' AND DeliveryMethod NOT LIKE '%PICKUP%' AND OrderNotes NOT LIKE '%RECOGER%')
ORDER BY Priority, OrderID ASC";
	$result = mysqli_query($con, $query);
	$return = [];
	
	while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
		$order = new Order($row['OrderID']);
		
		$row['ItemCount'] = count($order->Items);
		
		
		//$dueDays = new Customer($row['AccountNumber']);
		$row['DueDays'] = is_null($row['DueDays'])?0:$row['DueDays'];
		
		$row['OnHoldDate'] = date("m/d/Y h:i A",strtotime($row['OnHoldDate']));
		$row['OrderDate'] = date("m/d/Y h:i A",strtotime($row['OrderDate']));
		$row['InProcessDate'] = date("m/d/Y h:i A",strtotime($row['InProcessDate']));
		array_push($return, $row);
	}
	echo json_encode($return);
}

function setInProcess($orderID){
	global $con;
	global $dropbox;
	
	$query = "SELECT InProcess, ProcessUser FROM ORDER_HEAD WHERE OrderID = " . $orderID;
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
	$return = [];
	if($row['InProcess'] == "1"){
		$return['Result'] = false;
		$return['Error'] = "Already In Process";
		$return['User'] = $row['ProcessUser'];
	}else{
		$order = new Order($orderID);
		
		
		$query = "UPDATE ORDER_HEAD SET Processed = 1, ProcessUser = '" . $_SESSION['Username']  . "', InProcessDate = DATE_ADD(NOW(), INTERVAL -4 HOUR) WHERE OrderID = " . $orderID;
		
		if($result = mysqli_query($con, $query)){
			
			$return['InvoiceNumber'] = $order->generateInvoice();
			$return['Result'] = true;
			$return['Error'] = "";
			$return['InProcessDate'] = date("m/d/Y h:i A");
		}else{
			$return['Result'] = false;
			$return['Error'] = mysqli_error($con);
		}
	
		
	}
	echo json_encode($return);
}

function setProcessed($orderID){
	global $con;
	global $dropbox;
	$query = "UPDATE ORDER_HEAD SET Processed = 1, ProcessedDate = DATE_ADD(NOW(), INTERVAL -4 HOUR) WHERE OrderID = " . $orderID . " AND InProcess = 1;";
	$result = mysqli_query($con, $query);
	//$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
	$return = [];
	$order = new Order($orderID);
	$dropbox->Delete("/" . $_SESSION['Username'] . "/" . $orderID . "-" . $order->AccountNumber . "-" . $order->Salesman->ID . ".csv");
	if(mysqli_error($con) == ""){
		$return['Result'] = true;
		$return['Error'] = "";
		$return['OrderID'] = $orderID;
	}else{
		$return['Result'] = false;
		$return['Error'] = mysqli_error($con);
	}
	echo json_encode($return);
}
function setOnHold($orderID, $reason){
	global $con;
	global $dropbox;
	$query = "UPDATE ORDER_HEAD SET InProcess = 0, InProcessDate = '0000-00-00 00:00:00', OnHold = 1, OnHoldDate =  DATE_ADD(NOW(), INTERVAL -4 HOUR), HoldDeleteReason = '" . mysqli_real_escape_string($con, $reason) . "', ProcessUser = '', OnHoldDeleteUser = '" . $_SESSION['Username'] . "' WHERE OrderID = " . $orderID . " AND InProcess = 1;";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
	$return = [];
	$order = new Order($orderID);
	$dropbox->Delete("/" . $_SESSION['Username'] . "/" . $orderID . "-" . $order->AccountNumber . "-" . $order->Salesman->ID . ".csv");
	if(mysqli_error($con) == ""){
		$return['Result'] = true;
		$return['Error'] = "";
		$return['OrderID'] = $orderID;
	}else{
		$return['Result'] = false;
		$return['Error'] = mysqli_error($con);
	}
	echo json_encode($return);
	
}
function setDelete($orderID, $reason){
	global $con;
	global $dropbox;
	$query = "UPDATE ORDER_HEAD SET InProcess = 0, InProcessDate = '0000-00-00 00:00:00', OnHold = 0, OnHoldDate =  '0000-00-00 00:00:00', DeleteOrder = 1, DeleteOrderDate = DATE_ADD(NOW(), INTERVAL -4 HOUR), HoldDeleteReason = '" . mysqli_real_escape_string($con, $reason) . "', ProcessUser = '', OnHoldDeleteUser = '" . $_SESSION['Username'] . "' WHERE OrderID = " . $orderID . ";";
	if(!$result = mysqli_query($con, $query)){
		echo mysqli_error($con);
	}
	
	//$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
	$return = [];
	$order = new Order($orderID);
	//$dropbox->Delete("/" . $_SESSION['Username'] . "/" . $orderID . "-" . $order->AccountNumber . "-" . $order->Salesman->ID . ".csv");
	if(mysqli_error($con) == ""){
		$return['Result'] = true;
		$return['Error'] = "";
		$return['OrderID'] = $orderID;
	}else{
		$return['Result'] = false;
		$return['Error'] = mysqli_error($con);
	}
	echo json_encode($return);
	
}
function compareChanges($filename){
	//order_head_update_time
	$handle = fopen("modules/orderqueue/$filename", "r");
	$handleOrig = fopen("modules/orderqueue/$filename" . "_original", "r");
	if(fgets($handle) == fgets($handleOrig)){
		return true;
	}else{
		return false;
	}
}
?>