<?php
//echo "lol";
//die();
if(stripos($_SERVER['SCRIPT_NAME'],"/admin/")===false?false:true){
	include_once("../connect.php");
	include_once("../session.php");
}else{
	include_once("connect.php");
	include_once("session.php");
}

$function = isset($_REQUEST['f'])?$_REQUEST['f']:null;
if($function == "getDeliveryOptionData"){
    $id = $_REQUEST['id'];

	getDeliveryOptionData($id);
}elseif($function == "saveDeliveryOptionData"){
   saveDeliveryOptionData($_REQUEST);
}elseif($function == "deleteDeliveryOption"){
	deleteDeliveryOption($_REQUEST['id']);
}elseif($function == "getDeliveryZoneData"){
	getDeliveryZoneData($_REQUEST['zone']);
}elseif($function == "saveDeliveryZoneData"){
	saveDeliveryZoneData($_REQUEST);
}elseif($function == "getDeliveriesBySalesman"){
	getDeliveriesBySalesman($_REQUEST['sm']);
}elseif($function == "addToDeliveryList"){
	addToDeliveryList($_REQUEST['invoice'], $_REQUEST['sm']);
}elseif ($function == "deleteLoadedDelivery") {
	deleteLoadedDelivery($_REQUEST["id"], $_REQUEST['sm']);
	// code...
}elseif($function == "setAsDelivered"){
		$invoice = new Invoice($_REQUEST['invoiceID']);
		$invoice->deliverInvoice($_REQUEST['deliveryDriver'], $_REQUEST['deliveryDate']);
		echo "true";
}
function deleteLoadedDelivery($EntryID, $SalesmanID){
	global $con;
	if(substr($EntryID,0,1) == "A"){
		$EntryID = substr($EntryID,1,10);
		$assignment = new Assignment($EntryID);
		$assignment->RemoveFromDelivery();
	}
	$query = "DELETE FROM DELIVERY_RECORD WHERE id = " . $EntryID;
	$result = mysqli_query($con, $query);
	getDeliveriesBySalesman($SalesmanID);
	if($result){

	}else{
		return false;
	}

}
function getDeliveriesBySalesman($SalesmanID){
	global $con;
	$query = "SELECT DELIVERY_RECORD.*, INVOICE_HEAD.ShipToName, INVOICE_HEAD.ShipToCity,SALESMAN.FullName, INVOICE_HEAD.InvoiceDate FROM `DELIVERY_RECORD` JOIN INVOICE_HEAD USING(InvoiceID) LEFT JOIN SALESMAN ON(SALESMAN.ID = INVOICE_HEAD.Salesman) WHERE DELIVERY_RECORD.DeliveryUser LIKE '{$_REQUEST[sm]}' AND DropoffDate IS NULL ORDER BY PickupDate ASC";
	$result = mysqli_query($con, $query);
	$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
	//echo $query;
	foreach ($rows as $key => $value) {
//var_dump($value["InvoiceDate"]);
		//$dateDiff = date_diff($rows[$key]["InvoiceDate"], $rows[$key]["PickupDate"])
		//$invDate = date_create($value["InvoiceDate"]);
		$invDate = date_create();
		$pickupDate = date_create($value["PickupDate"]);
		//var_dump($pickupDate);
		$interval = date_diff($pickupDate, $invDate);
		//echo $interval;
		//$dateDiff = date_diff($invDate, $pickupDate)
		$rows[$key]["Days"] = $interval->days;
		$rows[$key]["InvoiceDate"] = "<b>Inv Date: </b>" . date("m/d/Y h:i a", strtotime($value["InvoiceDate"]));
		$rows[$key]["PickupDate"] = "<b>Load Date: </b>" . date("m/d/Y h:i a", strtotime($value["PickupDate"])) . " ({$rows[$key]["Days"]} days ago)";
				//$rows[$key] =


	}

	$query = "SELECT * FROM `ASSIGNMENT_HEAD` WHERE DeliveryUser LIKE '$SalesmanID' AND Completed = false";
	$result = mysqli_query($con, $query);
	$rows2 = mysqli_fetch_all($result, MYSQLI_ASSOC);

	foreach ($rows2 as $key => $value) {
		$rows2[$key]['Object'] = new Assignment($rows2[$key]['AssignmentID']);
		$rows2[$key]['FullName'] = new Salesman($rows2[$key]['Object']->DeliveryUser);
		$rows2[$key]['FullName'] = $rows2[$key]['FullName']->Name;
		$rows2[$key]["id"] = "A" . $rows2[$key]['Object']->AssignmentID;
		$rows2[$key]["InvoiceID"] = "A" . $rows2[$key]['Object']->AssignmentID;
		$invDate = date_create();
		$pickupDate = date_create($value["PickupDate"]);
		$interval = date_diff($pickupDate, $invDate);
		$rows2[$key]["Days"] = $interval->days;
		$rows2[$key]["InvoiceDate"] = "<b>Assignment Date: </b>" . date("m/d/Y h:i a", strtotime($value["AssignmentDate"]));
		$rows2[$key]["PickupDate"] = "<b>Load Date: </b>" . date("m/d/Y h:i a", strtotime($value["PickupDate"])) . " ({$rows2[$key]["Days"]} days ago)";
	}
	$rows = array_merge($rows, $rows2);
	echo safe_json_encode($rows);
}
function addToDeliveryList($invoiceID, $salesman){
	global $con;
	if(substr($invoiceID, 0,1) == "A"){
		$id = substr($invoiceID, 1,10);
		$assignment = new Assignment($id);
		$assignment->DeliveryUser = $salesman;
		$assignment->PickupDate = "NOW()";
		$assignment->save();
	}else{
		mysqli_query($con, "SET time_zone = '-04:00';");
		$query = "INSERT INTO DELIVERY_RECORD (InvoiceID, PickupDate, DeliveryUser, DispatchUser) VALUES ($invoiceID, NOW(), \"{$salesman}\", \"{$_SESSION['Username']}\")";
		//echo $query;
		$result = mysqli_query($con, $query);
	}
	getDeliveriesBySalesman($salesman);
}
function getDeliveryOptionData($id){
    global $con;
	$query = "SELECT * FROM DELIVERY_OPTION WHERE id = $id";

	$result = mysqli_query($con, $query);
	//var_dump($result);
	if($result){
		//echo $query;
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);


		echo json_encode($row);
	}else{
		echo "false";

	}
}
function saveDeliveryOptionData($data){
	global $con;
	$deliveredBy = $data['DeliveredBy'];
	$deliveredByColumn = "";
	if($deliveredBy !== ""){
		$deliveredByColumn = "`DeliveredBy`,";
		$deliveredBy = "'" . $deliveredBy . "',";
	}
	$query = "INSERT INTO DELIVERY_OPTION (`id`, `Name`, `StartTime`, `Cutoff`, `Comment`, $deliveredByColumn `FeeRule`) VALUES (" . $data['id'] . ", '" . $data['Name'] . "', '" . $data['StartTime'] . "', '" . $data['Cutoff'] . "', '" . $data['Comment'] . "', $deliveredBy '" . $data['FeeRule'] . "')
			ON DUPLICATE KEY UPDATE `Name` = VALUES(`Name`), `StartTime` = VALUES(StartTime), `Cutoff` = VALUES(Cutoff), `Comment` = VALUES(Comment), `DeliveredBy` = VALUES(DeliveredBy), `FeeRule` = VALUES(FeeRule)";
	//echo $query;
	if(mysqli_query($con, $query)){
		$return['result'] = true;
	}else{
		$return['result'] = false;
		$return['error'] = mysqli_error($con);
		$return['query']= $query;
	}
	echo json_encode($return);
	return $return;

}
function deleteDeliveryOption($id){
	global $con;
	$query = "DELETE FROM DELIVERY_OPTION WHERE id = " . $id . ";";
	if(mysqli_query($con, $query)){
		echo "true";
	}else{
		echo mysqli_error($con);
	}
}
function getDeliveryZoneData($zone){
    global $con;
	$query = "SELECT DeliveryID FROM DELIVERY_ZONE WHERE Zone = $zone";
	$result = mysqli_query($con, $query);
	$return['Cities'] = array();
	$return['Routes'] = array();
	while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
		array_push($return['Routes'], $row['DeliveryID']);
	}
	$query = "SELECT City FROM DELIVERY_ZONE_CITY WHERE Zone = $zone";
	$result = mysqli_query($con, $query);
	while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
		array_push($return['Cities'], $row['City']);
	}

	echo json_encode($return);

}
function saveDeliveryZoneData($data){
	if($data['ZoneID'] == "" || $data['ZoneID'] == null){
		die("Invalid Zone");
	}
	global $con;
	ob_start();
	deleteDeliveryZone($data['ZoneID']);
	ob_end_clean();
	$result = true;
	$return = array();
	foreach($data['Routes'] as $key => $value){
		$query = "INSERT INTO DELIVERY_ZONE (`DeliveryID`, `Zone`) VALUES (" . $value . ", " . $data['ZoneID'] . ")";
		$result = $result && mysqli_query($con, $query);
	}
	foreach($data['Cities'] as $key => $value){
		$query = "INSERT INTO DELIVERY_ZONE_CITY (`City`, `Zone`) VALUES ('" . $value . "', " . $data['ZoneID'] . ")";
		$result = $result && mysqli_query($con, $query);
	}
	$return['result'] = $result;
	if($result){

		echo json_encode($return);
	}

}
function deleteDeliveryZone($zone){
	global $con;
	$query = "DELETE FROM DELIVERY_ZONE WHERE Zone = " . $zone . ";";
	$query2 = "DELETE FROM DELIVERY_ZONE_CITY WHERE Zone = " . $zone . ";";
	if(mysqli_query($con, $query) && mysqli_query($con, $query2)){
		echo "true";
	}else{
		echo mysqli_error($con);
	}
}

?>
