<?php
$pickup = new Pickup($_REQUEST['pickup']);
$finalize = (isset($_REQUEST['finalize']) && $_REQUEST['finalize'] == "true")?true:false;
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>
	
	<script src="/js/jquery-barcode.min.js"></script>
		<script>
			function generateBarcode(bcValue, selector){
			var value = bcValue;
			var btype = "code128";
			var renderer = "bmp";
			
			//var quietZone = false;
			var settings = {
			  output:renderer,
			  bgColor: "#FFFFFF",
			  color: "#000000",
			  barWidth: "2",
			  barHeight: "50",
			  moduleSize: null,
			//  posX: $("#posX").val(),
			  //posY: $("#posY").val(),
			  //addQuietZone: $("#quietZoneSize").val()
			};
			
			$(selector).barcode(value, btype, settings);
			
		  }
		</script>
   </head>
   
   
        
	<body style="font-family: sans-serif;">
   <?php include("navbar.php"); ?>    
    <!-- Stack the columns on mobile by making one full-width and the other half-width -->
 <!--<img src="<?= $root ?>img/<?= $config['SmallLogo'] ?>" style="width: 202px; height: 63px;" />--><br />
 <br />
 	<div id="header" style="margin-top: 0px;">
 		<div style="width: 60%;  height: 120px; float: left;">
 			
 			<b>Customer Name: </b><?= substr($pickup->Customer->Name, 0, 29) ?><br />
 			<b>City: </b><?= $pickup->Customer->City; ?><br />
 			<b>Customer Number: </b><?= $pickup->Customer->AccountNumber ?><br />
 			<b>Requested By:</b>
 			<?= ($pickup->RequestedBy) ?><br />
 			<b>Packages: </b>
 				<?= ($pickup->Packages) ?><br />
			<b>Via: </b>
 				<?= ($pickup->Via) ?>
 				
 				
 			
 		</div>
 		<div style="width: 38%; height: 120px; float: right;">
 			<b>Pickup Number: </b><span style="font-style: italic;"><?= $pickup->PickupID ?></span><br />
 			<b>Pickup Ticket: </b><?= $pickup->PickupTicket ?><br />
 			<b>Date: </b><?= date("m/d/Y",strtotime($pickup->PickupDate)) ?><br />
 			<b>Time: </b><?= date("g:i a",strtotime($pickup->PickupDate)) ?><br />
 			<b>Salesman: </b><?= $pickup->Salesman->ID . " - " . $pickup->Salesman->Name ?><br />
 		</div>
 	</div>
 
 <div id="content" style="width: 100%;">
 	<h4 style="text-align: center;">PICKUP VERIFICATION PROCESS</h4>
 	<table style="border: 1px solid #333; border-collapse: collapse;">
 		<thead>
 			<tr>
 				<th style="border: solid 1px black; width: 5%;">Line</th>
 				<th style="border: solid 1px black; width: 50%;">Item</th>
 				<th style="border: solid 1px black; width: 5%;">Quantity</th>
				<th style="border: solid 1px black; width: 5%;">Order ID</th>
				<th style="border: solid 1px black; width: 5%;">Date</th>
 				<th style="border: solid 1px black; width: 5%;">Invoice Number</th>
 				<th style="border: solid 1px black; width: 5%;">Reason</th>
				<th style="border: solid 1px black; width: 25%;">Verification</th>
 			</tr>
 		</thead>
 		<tbody>
 			<?php
 				$query = "SELECT PICKUP_DETAIL.* FROM PICKUP_DETAIL WHERE PICKUP_DETAIL.PickupID = '$pickup->PickupID'";
 				$result = mysqli_query($con, $query);
 				$index = 0;
				$lastRowID = 0;
 				while ($row = mysqli_fetch_array($result)) {
				//	var_dump($row['PickupDetailID']);
					//var_dump($row);
					
					$warrantyReasonText = "</br> <i>" . getWarrantyReasonText($row['WarrantyReason']) . "</i>";
					$order = new Order($row['OrderID']);
					
 			?>
 			<tr>
 				<td style="border: solid 1px black; text-align: center;">
 					<?= $row['Line'] ?>
				
				
				</td>
 				<td style="border: solid 1px black;"><b><?= $row['SKU'] ?></b><br /><small><?php getProductDescription($row['Line'], $row['SKU']) ?></small></td>
 				<td style="border: solid 1px black; text-align: center;"><?= $row['Qty'] ?></td>
 				<td style="border: solid 1px black; text-align: right; padding-right: 5px;">
 					<?php
					if($order->OrderID === null){
					?>
						<?= ($row['OrderID'] == 0?"":$row['OrderID']) ?>
					<?php
					}else{
					?>
						<a href="/admin/vieworder.php?order=<?= $order->OrderID ?>" target="_blank"><?= ($row['OrderID'] == 0?"":$row['OrderID']) ?></a>
						
					<?php
					}
					?>
					
 				</td>
				<td>
					<?= date("m/d/Y", strtotime($order->OrderDate)) . " (" . dateDifference($order->OrderDate,date('Y-m-d',strtotime($pickup->PickupDate))) . " days)" ?>
				</td>
				<td style="border: solid 1px black; text-align: right; padding-right: 5px;">
 					<?= ($row['InvoiceNumber'] == 0?"":$row['InvoiceNumber']) ?>
 				</td>
 				<td style="border: solid 1px black; text-align: right; padding-right: 5px;">
 					<?= getReasonText($row['Reason']) . $warrantyReasonText ?>
 				</td>
				<td style="border: solid 1px black; text-align: center; padding: 5px;">
					<select class="form-control" id="PickupRow-<?= $row['id']?>" data-id="<?= $row['id']?>" name="PickupRow-<?= $row['id'] ?>">
						<option value="-1">--Escoger Status--</option>
						<option <?= $row['Approved'] === "1"?"selected":""  ?> value="1">Aceptado</option>
						<option <?= $row['Approved'] === "0"?"selected":""  ?> value="0">Denegado</option>
					</select><br />
					<select class="form-control" disabled multiple style="display: none;" id="PickupRowReason-<?= $row['id']?>" data-id="<?= $row['id']?>" name="PickupRow-<?= $row['id']?>">
						<option value="-1">--ESCOGER RAZON--</option>
						<option <?= $row['StatusReason'] == "CORE MUTILADO"?"selected":""  ?> >CORE MUTILADO</option>
						<option <?= $row['StatusReason'] == "CORE NO TIENE CAJA"?"selected":""  ?> >CORE NO TIENE CAJA</option>
						<option <?= $row['StatusReason'] == "ES DESGASTE, NO TIENE GARANTIA"?"selected":""  ?> >ES DESGASTE, NO TIENE GARANTIA</option>
						<option <?= $row['StatusReason'] == "FACTURA NO CUADRA CON FABRICACION"?"selected":""  ?> >FACTURA NO CUADRA CON FABRICACION</option>
						<option <?= $row['StatusReason'] == "FECHA DE COMPRA NO CONCUERDA CON FECHA DE FACTURA"?"selected":""  ?> >FECHA DE COMPRA NO CONCUERDA CON FECHA DE FACTURA</option>
						<option <?= $row['StatusReason'] == "GARANTIA DE MERCANCIA YA EXPIR&Oacute;"?"selected":""  ?> >GARANTIA DE MERCANCIA YA EXPIR&Oacute;</option>
						<option <?= $row['StatusReason'] == "MERCANCIA NO TIENE GARANTIA"?"selected":""  ?> >MERCANCIA NO TIENE GARANTIA</option>
						<option <?= $row['StatusReason'] == "NO HAY EVIDENCIA DE COMPRA"?"selected":""  ?> >NO HAY EVIDENCIA DE COMPRA</option>
						<option <?= $row['StatusReason'] == "NO TIENE FACTURA"?"selected":""  ?> >NO TIENE FACTURA</option>
						<option <?= $row['StatusReason'] == "PROMBLEMAS CON PORCIENTO DE GARANTIA"?"selected":""  ?> >PROMBLEMAS CON PORCIENTO DE GARANTIA</option>
						<option <?= $row['StatusReason'] == "SHOCK ES DE OTRA MARCA"?"selected":""  ?> >SHOCK ES DE OTRA MARCA</option>
						<option <?= $row['StatusReason'] == "SHOCK ES FABRICACION ORIGINAL"?"selected":""  ?> >SHOCK ES FABRICACION ORIGINAL</option>
						<option <?= $row['StatusReason'] == "SHOCK ESTA BUENO"?"selected":""  ?> >SHOCK ESTA BUENO</option>
						<option <?= $row['StatusReason'] == "TIEMPO DE COMPRA EXCEDE TERMINOS DE DEVOLUCION"?"selected":""  ?> >TIEMPO DE COMPRA EXCEDE TERMINOS DE DEVOLUCION</option>
						<option <?= $row['StatusReason'] == "UNIDAD MUTILADA"?"selected":""  ?> >UNIDAD MUTILADA</option>
						<option <?= $row['StatusReason'] == "VASTAGO QUEMADO"?"selected":""  ?> >VASTAGO QUEMADO</option>
						<option <?= $row['StatusReason'] == "OTRO"?"selected":""  ?> >OTRO</option>
						
						
						
						
						
						
					</select>
					
				</td>
 			</tr>
			
 			<?php
				}
			?>
			
 		</tbody>
 	</table>
 	<div class="pull-right" style="padding: 5px; margin-top: 5px; width: 40%; word-wrap: break-word; text-align: right;">
		<?php
			if($finalize){
				$buttonText = "Finalize";	
			}else{
				$buttonText = "Save";
			}
			
		?>
		<button class="btn btn-warning pull-left" onclick="dismissPickup();">Dismiss</button>
		<button class="btn btn-success" onclick="save();"><?= $buttonText ?></button>
		<button class="btn btn-success" onclick="save(true);"><?= $buttonText ?> & Print</button>
		<button class="btn btn-danger" onclick="window.history.back();">Cancel</button>
 		 
 	</div>
 	<div style="padding: 5px; margin-top: 5px; border: 1px solid #333; width: 50%; word-wrap: break-word;"><b>Pickup Notes: </b><br />
 		 <?= $pickup->PickupNotes ?>
		 
		 
 	</div>
	
	<br />
 	<br />
 	
	<br>
 	<div class="center" style="margin: auto; text-align: center;" id="pickupBarcode-<?= $pickup->PickupID ?>">
	
 	</div>
 <script>
	var untouched = true;
	
	generateBarcode('<?= $pickup->PickupID ?>', "#pickupBarcode-<?= $pickup->PickupID ?>");
	
	function validateVerificationStatus(){
		var result = true;
		$('[id^=PickupRow-]').each(function(){
			var id = $(this).data('id');
			if($(this).val() === "-1"){
				//alert($(this).val());
				
				result = false;
				$(this).focus();
			}else if($('#PickupRowReason-' + id).val() === "-1" && !$('#PickupRowReason-' + id).prop('disabled')){
				
				result = false;
				$('#PickupRowReason-' + id).focus();
			}
		});
		return result;
		
		
	}
	$('[id^=PickupRow-]').on('change', function(){
		var id = $(this).data('id');
		if($(this).val() == "0"){
			
			$('#PickupRowReason-' + id).prop('disabled', false);
			$('#PickupRowReason-' + id).multiselect('enable');
			$('#PickupRowReason-' + id).show();
		}else{
			$('#PickupRowReason-' + id).prop('disabled', true);
			$('#PickupRowReason-' + id).multiselect('disable');
			$('#PickupRowReason-' + id).hide();
		}
		transformReasonSelects();
	});
	$('[id^=PickupRowReason-]').on('change', function(){
		var id = $(this).parent().parent().find('select[id^=PickupRow-]').data('id');
		//console.log(id);
			if($('#PickupRowReason-' + id).val()!== null && $('#PickupRowReason-' + id).val().indexOf('OTRO') > -1){
				var newReason = prompt('Entre razon especifica').toUpperCase();
				$('#PickupRowReason-' + id).append('<option>' + newReason + '</option>');
				$('#PickupRowReason-' + id).multiselect('rebuild');
				$('#PickupRowReason-' + id).multiselect('select', newReason);
				$('#PickupRowReason-' + id).multiselect('deselect', 'OTRO');
				$('#PickupRowReason-' + id).multiselect('refresh');
		}
	});
	$(document).ready(function(){
		$('[id^=PickupRow-]').each( function(){
			var id = $(this).data('id');
			console.log(id);
			if($(this).val() == "0"){
				
				$('#PickupRowReason-' + id).prop('disabled', false);
				$('#PickupRowReason-' + id).show();
			}else{
				$('#PickupRowReason-' + id).prop('disabled', true);
				$('#PickupRowReason-' + id).hide();
			}
		});	
		setTimeout(function(){
			$('[id^=PickupRow]').on('change', function(){
				untouched = false;	
			});
		}, 1000);
	});
	var arrData = [];

	function save(printRejected){
		
		if(validateVerificationStatus()){
			arrData = [];
			var approvedCount = 0;
			var rejectedCount = 0;
			$('[id^=PickupRow-]').each(function(){
				var id = $(this).data('id');
				var pickupID = <?= $pickup->PickupID ?>;
				var item = {};
				item.PickupID = pickupID;
				item.RowID = id;
				
				if($(this).val() === "1"){
					item.Approved = true;
					approvedCount++;
				}else{
					item.Approved = false;
					rejectedCount++;
				}
				if(item.Approved === false){
					item.Reason = $('#PickupRowReason-' + id).val();
				}else{
					item.Reason = null;
				}
				console.log(item);
				arrData.push(item);
			});
			$.post('mod.php?p=pickupreceiving&a=functions&f=saveVerification',
				   {
					"data": JSON.stringify(arrData)
					})
			.done(function(data){
					data = JSON.parse(data);
					if(data.result){
						if(<?= $finalize?"true":"false" ?>){
							var finalStatus = "";
							if(approvedCount > 0 && rejectedCount > 0){
								finalStatus = "Aceptado Parcial";
							}else if(approvedCount > 0 && rejectedCount === 0){
								finalStatus = "Aceptado";
							}else if(approvedCount === 0 && rejectedCount > 0){
								finalStatus = "Denegado";
							}
							$.get('functions.php?action=setPickupStatus&a=status&pickupID=<?= $pickup->PickupID ?>&value=' + finalStatus + '&notes=', function(dataPUStatus){
								alert('Pickup Verified Successfully & Status set to ' + finalStatus);
								askVerifyModal(true);
								
							});
						}else{
							$.get('functions.php?action=setPickupStatus&a=status&pickupID=<?= $pickup->PickupID ?>&value=Waiting&notes=', function(dataPUStatus){
								alert('Pickup Verified Successfully & Status set to Waiting');
								askVerifyModal();
								if(printRejected){
									window.open('mod.php?p=pickupreceiving&a=rejectedReport&pickup=<?= $pickup->PickupID ?>');
								}
							});
						}
						
					}
				})
			.fail(function(e){
				alert('Error saving the data: ' + e);
			});
			return true;
		}else{
			return false;
		}
	}
	function dismissPickup(){
		
		if(confirm('Are you sure you want to Dismiss this Pickup?')){
			
			var dismissReason = prompt("Plase enter a reason for dismissal");
			$.get('functions.php?action=setPickupStatus&a=status&pickupID=<?= $pickup->PickupID ?>&value=Dismissed&notes=' + dismissReason, function(dataPUStatus){
				alert('Pickup Dismissed Successfully');
				askVerifyModal(true);
				
			});
		}
	}
	function finalizePickup(){
		$.post('mod.php?p=pickupreceiving&a=functions&f=finalizePickup',
			   {
				
				})
		.done(function(data){
				data = JSON.parse(data);
				if(data.result){
					alert('Pickup Finalized Successfully & Status set to ' + data.Status);
						askVerifyModal(true);
				}
			})
		.fail(function(e){
			alert('Error finalizing pickup: ' + e);
		});
		return true;
		
	}
	function askVerifyModal(finalize = false){
		$('#modalGoPickupID').unbind('click');
		$('#modalGoPickupID').on('click', function() {
			var finalizeString = "&finalize=";
			if(finalize)
				finalizeString += finalizeString + "true";
			else
				finalizeString += finalizeString + "false";
			window.location ='mod.php?p=pickupreceiving&a=verify&pickup=' + $('#pickupID').val().split('-')[0] + finalizeString;
		});
		if(!finalize)
			$('#selectPickupID').modal('toggle');
		else
			window.history.back();

	}
	$(document).ready(function(){
		transformReasonSelects();
		
		<?php
		$queryReasons = "SELECT * FROM PICKUP_VERIFICATION_STATUS WHERE PickupID = " . $pickup->PickupID;
		$resultReasons = mysqli_query($con, $queryReasons);
		while($rowReasons = mysqli_fetch_array($resultReasons)){
			//var_dump($rowReasons);
			echo "$('#PickupRowReason-" . $rowReasons['PickupDetailID'] . "').multiselect('select', '" . $rowReasons['StatusReason'] . "');\n";
		}
		?>
	});
	function transformReasonSelects(){
		//$("[id^='PickupRowReason-']").multiselect('rebuild');
		$("[id^='PickupRowReason-']").multiselect({
			enableFiltering: true,
			filterBehavior: 'value',
			includeSelectAllOption: false,
			buttonWidth: '375px'
		});
		$("[id^='PickupRowReason-']").hide();
		
			
	}
	
 </script>
 </div>
 </body>
   
 </html>
 
 <!--
			
		-->