<?php
if(false){
	class Pickup {
		public $PickupID, $PickupTicket, $Customer, $PickupDate, $Items, $PickupNotes, $Packages, $Salesman, $AccountNumber, $RequestedBy, $Void, $VoidID, $VoidDate, $VoidReason, $VoidUser,$Loaded, $Via;
		public function __construct($PickupID) {
			$query = "SELECT * FROM PICKUP_HEAD WHERE PickupID = $PickupID";
			global $con;
			$result = mysqli_query($con, $query);
			$row = mysqli_fetch_array($result);
			$this->PickupID = $row['PickupID'];
			$this->PickupTicket = $row['PickupTicket'];
			$this->AccountNumber = $row['AccountNumber'];
			$this->Customer = new Customer($row['AccountNumber']);
			$this->PickupDate = $row['PickupDate'];
			$this->PickupNotes = $row['PickupNotes'];
			$this->Packages = $row['Packages'];
			$this->Salesman = new Salesman($row['Salesman']);
			$this->RequestedBy	= $row['RequestedBy'];
			$this->Via	= $row['Via'];
			$this->Loaded = false;
			$this->Void = $row['Void'];
			if($row['Void']){
				$query = "SELECT * FROM PICKUP_VOID WHERE PickupID = " . $row['PickupID'];
				$result = mysqli_query($con, $query);
				$row2 = mysqli_fetch_array($result);
				$this->VoidID = $row2['ID'];
				$this->VoidReason = $row2['Reason'];
				$this->VoidDate = $row2['VoidDate'];
				$this->VoidUser = $row2['User'];
			}
			$this->Items = array();
			$query = "SELECT id FROM PICKUP_DETAIL WHERE PickupID = $PickupID";
			$result = mysqli_query($con, $query);
			while($row = mysqli_fetch_array($result)){
				$item = new PickupItem($row['id']);
				array_push($this->Items, $item);
				unset($item);
			}
		
		}
		public function Void($reason){
			global $con;
			$reason = mysqli_real_escape_string($con,$reason);
			if(trim($reason) == ""){
				die("Invalid Reason");
			}
			/*
			$query = "UPDATE PAYMENT_HEAD SET CashAmount = 0, CheckAmount = 0, ProcessDate = NOW(), Processed = 1, Void = TRUE WHERE id = " . $this->PaymentID . ";";
			$query .= "UPDATE PAYMENT_DETAIL SET InvoiceNumber = CONCAT(InvoiceNumber,'V'), PartialPayment = 0, SubtotalAmount = 0, DiscountAmount = 0, TaxAmount = 0, PaymentAmount = 0, Reference = '' WHERE PaymentID = " . $this->PaymentID . ";";
			$query .= "UPDATE PAYMENT_CREDIT SET CreditNumber = CONCAT(CreditNumber,'V'), Subtotal = 0, Discount = 0, Tax = 0, Total = 0, Reference = '' WHERE PaymentID = " . $this->PaymentID . ";";
			$query .= "INSERT PAYMENT_VOID (PaymentID, Reason, User, VoidDate) VALUES (" . $this->PaymentID . ", '$reason', '" . $_SESSION['Username'] . "', NOW());";
			*/
			$reasonText = "THIS PICKUP REQUEST WAS VOIDED BECAUSE OF THE FOLLOWING REASON:" . $reason;
			$query = "UPDATE PICKUP_HEAD SET ToPickup = NOW(), ToPickupUser = '" . $_SESSION['Username'] . "', AtWarehouse = NOW(), AtWarehouseUser = '" . $_SESSION['Username'] . "', PickupStatus = 'VOID', PickupStatusUser = '" . $_SESSION['Username'] . "', PickupStatusNotes = '$reasonText', Void = TRUE WHERE PickupID = " . $this->PickupID . ";";
			$query .= "INSERT PICKUP_VOID (PickupID, Reason, User, VoidDate) VALUES (" . $this->PickupID . ", '$reason', '" . $_SESSION['Username'] . "', NOW());";
			
			
			if(!mysqli_multi_query($con, $query)){
				$data['result'] = false;
				$data['error'] = mysqli_error($con);
				$data['sql'] = $query;
				echo json_encode($data);
			}else{
				$data['result'] = "true";
				echo json_encode($data);
			}
			//echo $query;
			event_log($_SESSION['Username'],"PICKUP VOID", "Pickup Void \n\Pickup ID: " . $this->PickupID . " \nCustomer: " . $this->Customer->AccountNumber . " - " . $this->Customer->Name . "\nUser: " . $_SESSION['User'] . "\nReason: " . $reason);
		}
		public function GetVoidDetails(){
			global $con;
			$data['Pickup'] = $this->PickupID;
			$data['VoidDate'] = $this->VoidDate;
			$data['VoidReason'] = $this->VoidReason;
			$data['VoidUser'] = $this->VoidUser;
			//var_dump($this);
			echo json_encode($data);
		}
	}
	
	class PickupItem {
		public $Line, $SKU, $Description, $InvoiceNumber, $OrderID, $Reason, $Qty, $ReasonText;
		public function __construct($id) {
			$query = "SELECT PICKUP_DETAIL.*, CONCAT(CONCAT(INVENTORY.Description, ' '),INVENTORY.Notes) AS Description FROM PICKUP_DETAIL, INVENTORY WHERE `id` = $id AND PICKUP_DETAIL.SKU = INVENTORY.SKU AND PICKUP_DETAIL.LINE = INVENTORY.LINE";
			global $con;
			$result = mysqli_query($con, $query);
			$row = mysqli_fetch_array($result);
			$this->Line = $row['Line'];
			$this->SKU = $row['SKU'];
			$this->Description = $row['Description'];
			$this->OrderID = $row['OrderID'];
			$this->InvoiceNumber = $row['InvoiceNumber'];
			$this->Reason = $row['Reason'];
			$this->Qty = $row['Qty'];
			$this->ReasonText = getReasonText($row['Reason']);
			
		}	
	}
}

include_once("../connect.php");
include_once("../session.php");

?>
<!DOCTYPE html>
 <html lang="en">
   <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <title><?= $config['CompanyName'] ?></title>
 
     <!-- Bootstrap -->
     <link href="../css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="../css/bootstrap-combobox.css" />
 
     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
     <!--[if lt IE 9]>
       <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
       <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="../js/bootstrap.min.js"></script>
       	 <script src="../js/bootstrap-combobox.js"></script>
       	 <script src="../js/excellentexport.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
              // $('.combobox').combobox();
       //        $('.grpline').css("width", "100px");
             });
           </script>

     <![endif]-->
	<link rel="stylesheet" href="../css/styles.css"/>
	<style>
		.listPanel {
			height: 500px;
			background-color: #eee;
			
		}
	</style>
   </head>
   <body>
   
       <?php include("navbar.php"); ?>     

   <br />
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
	<div class="container " style="padding-top: 10px; width: 100%;">
		<nav class="navbar navbar-default query" role="query">
            <div class="container-fluid">
                <div class="navbar-header">
                    <a class="navbar-brand" href="javascript:void(0);">Pickup Receiving Batch #<?= getCurrentBatchNumber() ?></a>
                    
                </div>
                <div class="collapse navbar-collapse" id="">
                    <div class="navbar-form navbar-left">
                        <input type="text" class="form-control" id="pickupNumber" />
						<div class="form-group">
							<label for="batchCount">Batch Count:</label>
							<input id="batchCount" name="batchCount" class="form-control" readonly type="text" />
							
						</div>
                    </div>
					<div class="navbar-form navbar-right">
					
                    <button onclick="window.open('mod.php?p=pickupreceiving&a=carrierreport');" class="btn btn-success pull-right">Preview Report</button>
					
					 <button style="margin-right: 10px;" onclick="window.open('mod.php?p=pickupreceiving&a=carrierreport&printReceipts=true&save=true');" class="btn btn-success pull-right">Save and Print Report and Receipts</button> 
                        
                    </div>
					
                    
                </div>
                
            </div>
        </nav>
		<div class="container">
			<div class="row">
					<div class="span12">
						<div class="menu">
							<div class="accordion">
								<div class="accordion-group" id="pickupRowContainer">
									<!--
									
									-->
									
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
			
	</div>
	<audio src="/assets/audio/no.mp3" id="failSound"></audio>
	<audio src="/assets/audio/yes.mp3" id="successSound"></audio>
	
	<script>
		var currentData = [];
		
		function addNewRow(pickupID = 0){
			if(pickupID === 0){
				return;
			}
			var template = `<div class="accordion-heading">
										<h4  style="background-color: #ddd; padding: 10px;"><a class="accordion-toggle" data-toggle="collapse" href="#PICKUPID_TAG_accordion">PICKUPID_TITLE<span class="pull-right" id="PICKUPID_TAG_Status"></span></a></h4>
									</div>
									<div id="PICKUPID_TAG_accordion" class="accordion-body collapse in">
										<div class="accordion-inner">
											<table class="table table-striped table-condensed">
												<thead>
													<th>Box</th>
													<th>Date/Time</th>
													<th>User</th>
												</thead>
												<tbody id="PICKUPID_TAG_tablebody">
													
												</tbody>
											</table>
										</div>
									</div>`;
			var pickupRow = template;
			pickupRow = pickupRow.replace(/PICKUPID_TAG_/g, 'pickup' + pickupID);
			pickupRow = pickupRow.replace(/PICKUPID_TITLE/g, 'Pickup ' + pickupID);
			$('#pickupRowContainer').append(pickupRow);
			
		}
		function getPickupData(PickupID, callback = null){
			//alert(getPickupIndex(PickupID));
			//alert(getPickupIndex(PickupID)<0);
			if(getPickupIndex(PickupID) < 0){
				$.get('mod.php?p=pickupreceiving&a=functions&f=getPickupData&pid=' + PickupID, function(data){
					try{
						data = JSON.parse(data);
						if(!data.Error){
							var pickupObject = {};
							pickupObject.ID = PickupID;
							pickupObject.Packages = [];
							
							for(var i = 1; i <= data.Packages; i++){
								var packageItem = {};
								packageItem.Number = i;
								packageItem.Received = data.PackageDetails[i].Received;
								if(data.PackageDetails[i].Received){
									packageItem.Receiver = data.PackageDetails[i].Receiver;
									packageItem.ReceiveDate = data.PackageDetails[i].ReceiveDate;
								}
								pickupObject.Packages.push(packageItem);
							}
							currentData.push(pickupObject);
							if(typeof callback == "function"){
								callback();	
							}
						}else{
							$('#failSound')[0].pause();
							$('#failSound')[0].currentTime = 0;
							$('#failSound')[0].play();
						}
					}catch (err){
						alert(err.message);
					}
					
					
				});
			}else{
				if(typeof callback == "function"){
						callback();	
					}
			}
		}
		function fillRow(pickupID){
			var data = getPickupData(pickupID);
			
		}
		function preReceivePackage(pickupNumber){
			var pickupID, packageNumber;
			pickupID = pickupNumber.split("-")[0];
			packageNumber = pickupNumber.split("-")[1];
			getPickupData(pickupID, function(){
				receivePackage(pickupNumber);	
			});
		}
		function receivePackage(pickupNumber){
			var pickupID, packageNumber;
			pickupID = pickupNumber.split("-")[0];
			packageNumber = parseInt(pickupNumber.split("-")[1]);
			$.get("mod.php?p=pickupreceiving&a=functions&f=receivePackage&pid=" + pickupID + "&pNumber=" + packageNumber, function(data){
					data = JSON.parse(data);
					if(data.result === true){
						var pickupIndex = getPickupIndex(pickupID);
						
							currentData[pickupIndex].Packages[getPackageIndex(pickupIndex, packageNumber)].Received = true;
							currentData[pickupIndex].Packages[getPackageIndex(pickupIndex, packageNumber)].ReceiveDate = data.currDate;
							currentData[pickupIndex].Packages[getPackageIndex(pickupIndex, packageNumber)].Receiver = data.User;
						$('#batchCount').val(data.BatchCount);
						$('#successSound')[0].pause();
						$('#successSound')[0].currentTime = 0;
						$('#successSound')[0].play();
					}else{
						$('#failSound')[0].pause();
						$('#failSound')[0].currentTime = 0;
						$('#failSound')[0].play();
					}
					refreshPanel();
			});
			
		}
		function refreshPanel(){
			$("#pickupRowContainer").html('');
			for(var i = 0; i < currentData.length; i++){
				var pickupID = currentData[i].ID;
				addNewRow(pickupID);
				var missingArray = [];
				var booleanComplete = true;
				//var currentDate = new Date();
				for(var ii = 0; ii < currentData[i].Packages.length; ii++){
					booleanComplete = booleanComplete && currentData[i].Packages[ii].Received;
					if(!currentData[i].Packages[ii].Received){
						missingArray.push(currentData[i].Packages[ii].Number);
					}else{
						
						$('#pickup' + pickupID + "tablebody").append("<tr><td>" + currentData[i].Packages[ii].Number + "</td><td>" + currentData[i].Packages[ii].ReceiveDate + "</td><td>" + currentData[i].Packages[ii].Receiver + "</td></tr>");
						console.log("<tr><td>" + currentData[i].Packages[ii].Number + "<td><td><td><td><td></tr>");
					}
					
				}
				if(booleanComplete){
					$('#pickup' + pickupID + "Status").text('COMPLETE');
					$('#pickup' + pickupID + "accordion").addClass('collapse');
					$('#pickup' + pickupID + "accordion").removeClass('in');
				}else{
					$('#pickup' + pickupID + "Status").text('MISSING: ' + missingArray.join(", "));
					$('#pickup' + pickupID + "Status").css("color", "red");
				}
				
			}
		}
		
		function packageIsMissing(pickupNumber){
			var pickupID, packageNumber;
			pickupID = pickupNumber.split("-")[0];
			packageNumber = pickupNumber.split("-")[1];
			var packageIndex = getPackageIndex(pickupID, packageNumber);
			if(currentData[pickupID].Packages[packageIndex].Received){
				return false;
			}else{
				return true;
			}
		}
		function getPickupIndex(PickupID){
			for(var i = 0; i < currentData.length; i++){
				if(currentData[i].ID == PickupID){
					return i;
				}else{
					//return -1;
				}
			}
			return -1;
		}
		function getPackageIndex(PickupIndex, PackageNumber){
			for(var i = 0; i < currentData[PickupIndex].Packages.length; i++){
				if(currentData[PickupIndex].Packages[i].Number == PackageNumber){
					return i;
				}else{
					//return -1;
				}
			}
			return -1;
		}
		
		$('#pickupNumber').on('keyup', function(e){
			if(e.keyCode == "13"){
				preReceivePackage($('#pickupNumber').val());
				$('#pickupNumber').select();
			}
			});
		
	</script>
   </body>
   
 </html>
 
 <!--
			
		-->