<?php
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 = $_REQUEST['f'];
if($function == "getPickupData"){
        getPickupData($_REQUEST['pid']);
		
}elseif($function == "receivePackage"){
	receivePackage($_REQUEST['pid'], $_REQUEST['pNumber']);
}elseif($function == "saveVerification"){
	saveVerification($_REQUEST);
}elseif($function == "finalizePickup"){
	finalizePickup($_REQUEST);
}

function getPickupData($pickupID){
    $pickup = new Pickup($pickupID);
	if($pickup->PickupID != null){
		$pickup->Error = false;
		echo json_encode($pickup);	
	}else{
		$pickup->Error = true;
		$pickup->ErrorMessage = "Pickup not found";
		echo json_encode($pickup);	
	}
    
}
function receivePackage($pickupID, $packageNumber){
	global $con;
	$return = new StdClass();
	
	//$query = "SELECT * FROM PICKUP_HEAD WHERE PickupID = $pickupID";
	$query = "SELECT PICKUP_HEAD.*, COUNT(PICKUP_RECEIVE_PACKAGE.Id) PackagesReceived, (Packages - COUNT(PICKUP_RECEIVE_PACKAGE.Id)) MissingPackageCount FROM PICKUP_HEAD LEFT JOIN PICKUP_RECEIVE_PACKAGE USING(PickupID) WHERE PickupID = $pickupID GROUP BY PickupID";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	//error_reporting(E_ALL);
	if(mysqli_num_rows($result) > 0){
		
		if($packageNumber <= $row['Packages']){
		//echo "efe";	
			$query = "INSERT INTO PICKUP_RECEIVE_PACKAGE (User, PickupID, PackageNumber, ReceiveDate, BatchID) VALUES ('{$_SESSION['Username']}', $pickupID, $packageNumber, DATE_ADD(NOW(), INTERVAL -4 HOUR), " . getCurrentBatchNumber() . ");";
			
			if(mysqli_query($con, $query)){
				
				$return->result = true;
				$return->currDate = date("m/d/Y h:i a", time()+10800);
				$return->User = $_SESSION['Username'];
				$return->BatchCount = getBatchCount(getCurrentBatchNumber());
				if($row['MissingPackageCount'] == 1){
					$return->Completed = true;
					ob_start();
					setPickupStatus("warehouse", $row['PickupID'], date("Y-m-d H:i", time()+10800), "RECEIVED VIA SCANNER: " . $return->User);
					ob_end_clean();
				}
				//$return['currTime'] = date("h:i a");
				echo json_encode($return);
			}else{
				
				$return->result = false;
				$return->error = mysqli_error($con) . "\n" . $query;
				
				echo json_encode($return);
				
			}
		
		}else{
			$return->result = false;
			$return->error = "ERROR: THIS PICKUP DOES NOT HAVE $packageNumber PACKAGES";
			echo json_encode($return);
		
		}
	}else{
		$return->result = false;
		$return->error = "ERROR: PICKUP NOT FOUND";
		echo json_encode($return);
	}
}
function getCurrentBatchNumber(){
	global $con;
	$query = "SELECT id FROM PICKUP_RECEIVE_BATCH WHERE BatchCompleted = False ORDER BY id DESC LIMIT 1;";
	$result = mysqli_query($con, $query);
	
	if(mysqli_num_rows($result) > 0){
		$row = mysqli_fetch_assoc($result);
		return $row['id'];
	}else{
		$query = "INSERT INTO PICKUP_RECEIVE_BATCH (User) VALUES ('" . $_SESSION['Username'] . "')";
		$result = mysqli_query($con, $query);
		return mysqli_insert_id($con);		
	}
}
function getBatchCount($batchID){
	global $con;
	$query = "SELECT COUNT(id) as PackageCount FROM PICKUP_RECEIVE_PACKAGE WHERE BatchID = " . $batchID;
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_assoc($result);
	return $row['PackageCount'];
}
function saveBatch(){
	$batchID = getCurrentBatchNumber();
	if(getBatchCount($batchID) > 0){
		global $con;
		$query = "UPDATE PICKUP_RECEIVE_BATCH SET BatchCompleted = True, BatchCloseTime = DATE_ADD(NOW(), INTERVAL -4 HOUR) WHERE id = $batchID AND BatchCompleted = False";
	
		mysqli_query($con, $query);
	}
	
	
}
function saveVerification($submitData){
	global $con;
	$data = json_decode(($submitData['data']));
	// json_decode($submitData['data']);
	//var_dump($data);
	$query = "DELETE FROM PICKUP_VERIFICATION_STATUS WHERE PickupID = " . $data[0]->PickupID . ";";
	//echo $query . "<br>";
	mysqli_query($con, $query);
	foreach($data as $key => $value){
		//var_dump($value);
		$approved = $value->Approved?"TRUE":"FALSE";
		$query = "UPDATE PICKUP_DETAIL SET Approved = " . $approved . ", StatusUser = '" . $_SESSION['Username'] . "', StatusDate = DATE_ADD(NOW(), INTERVAL -4 HOUR) WHERE id = " . $value->RowID . ";";
		mysqli_query($con, $query);
		if(!$value->Approved){
			foreach($value->Reason as $reason){
				$query = "INSERT INTO PICKUP_VERIFICATION_STATUS (PickupDetailID, PickupID, StatusReason) VALUES ('" . $value->RowID . "', '" . $value->PickupID . "', '" . $reason . "')";
				//echo $query . "<br>";
				mysqli_query($con, $query);	
				
			}
		}
		//
	}
	echo "{ \"result\" : true }";
}

?>