<?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");
}

 ?>

 <!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/functions.js"></script>
		 <script src="../js/bootstrap-combobox.js"></script>
		 <script src="../js/excellentexport.js"></script>
		   <script type="text/javascript">
			 $(document).ready(function(){
	   //        $('.grpline').css("width", "100px");
			 });
		   </script>

	 <![endif]-->
	<link rel="stylesheet" href="../css/styles.css"/>
   </head>
   <body>

	   <?php include_once("navbar.php"); ?>


   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
<div class="container " style="padding-top: 10px; width: 90%;">
	<div class="panel panel-default">
	  <div class="panel-heading form-inline">
	  
		<span class="pull-right">Pending Total: <span id="pendingInvoiceTotal"></span></span>
		<h3 class="panel-title">Invoice Queue</h3><br />
		
	  </div>
	  <div class="panel-body">
		<table style="table-layout: fixed;" class="table table-hover table-condensed" id="orderqueue">
			<thead>
				<tr>
					<th>Invoice ID</th>
					<th style="text-align: center;">Row Count</th>
					<th style="text-align: center;">Days</th>
					<th style="width: 300px;">Customer</th>
					<th>Sent Picking Date/Time</th>
					<th>PO Number</th>
					<th>Salesperson</th>
					<th style="text-align: right;">Invoice Total</th>
					<th>In Process</th>
					<th style="overflow: visible; white-space: nowarp;">Done</th>
				</tr>
			</thead>
			<tbody id="invoiceQueueTbody" >
			
			</tbody>
		<?php
//var_dump( $_SESSION);
		 ?>
		 </table>
	  </div>
	</div>

	</div>
	<script type="text/javascript">
		function Interval(fn, desc, ms){
			this.desc = desc;
			this.status = 0;
		  
			var that = this;
			this.start = function(){
				this.id = window.setInterval(function () {
		  
				// save some progess to the Interval object
				// that is used, because in interval callback this === window
				that.status++;
			
				// now call your function fn, using this === Interval object
				fn.call(that);
			  }, ms);
			}
			this.start();
		  
			this.stop = function () {
			  if (this.id) {
				window.clearInterval(this.id);
				this.id = 0;
				this.status = -1;
			  }
			};
		  }

		
		
		
		/*jshint multistr: true */
		var invoiceSubtotal = 0;
		function fillPendingOrders(){
			invoiceSubtotal = 0;
			if(!enableRefresh){
				return;
			}
			$.get('mod.php?p=invoice&a=functions&f=getPendingInvoices', function(data){
					
					$('#invoiceQueueTbody').html('');
					data = JSON.parse(data);
					
					//console.log(data);
					var isProcessing = false;
					for(var i=0;i < data.length;i++){
						invoiceSubtotal += data[i].Subtotal;
						var disabledInProcessTag = "";
						var disabledProcessTag = " disabled ";
						if(isProcessing){
							disabledInProcessTag = " disabled ";
						}
						var inProcessBtnText = "Review";
						var onHoldBadge = "";
						var inProcessBtnClass = "btn-primary";
						var Remarks = "";
						if(data[i].InProcess == "1"){
							inProcessBtnText = data[i].InProcessDate;
							isProcessing = true;
							disabledInProcessTag = " disabled ";
							inProcessBtnClass = "btn-success";
							disabledProcessTag = ""; 
						} else if (data[i].OnHold == "1"){
							inProcessBtnText = "On Hold";
							inProcessBtnClass = "btn-danger";
							onHoldBadge = "<span class=\"badge\" onclick=\"alert('User: " + data[i].OnHoldDeleteUser + " \\nDate: " + data[i].OnHoldDate + " \\nReason: " + data[i].HoldDeleteReason + "')\">i</span>";
						}
						var Notes = "";
						if(data[i].Notes !== ""){
							Notes = "<br /><small><b>Note: </b>" + data[i].Notes + "</small>";
						}
						$('#invoiceQueueTbody').append("<tr class=\"\">\
						<td >\
						<div class=\"btn-group hidden-print\">\
							<button type=\"button\" class=\"btn btn-default dropdown-toggle\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\
							  " + data[i].InvoiceID + " <span class=\"caret\"></span>\
							</button>\
							<ul class=\"dropdown-menu\">\
							  <li><a href=\"mod.php?p=invoice&a=picking&invoice=" + data[i].InvoiceID + "\" target=\"_blank\">Print Picking</a></li>\
							  <li><a href=\"mod.php?p=invoice&a=review&id=" + data[i].InvoiceID + "\">Review</a></li>\
							  <li><a href=\"#\" onclick=\"setDelete('" +  data[i].InvoiceID + "')\">Void Invoice</a></li>	\
							</ul>\
						  </div>\
						</td>\
						<td style=\"text-align: center;\">" + data[i].ItemCount + "</td>\
						<td style=\"text-align: center;\">" + data[i].DueDays + "</td>\
						<td style=\"max-width: 320px;\"><b>" + data[i].AccountNumber + "</b> - " + data[i].Name + Notes + Remarks + "</td>\
						<td>" + data[i].CreationDate + "</td>\
						<td>" + data[i].PONumber + "</td>\
						<td>" + data[i].SalesmanName + "</td>\
						<td style=\"text-align: right;\">" + moneyFormat(data[i].Subtotal) + "</td>\
						<td><button " + disabledInProcessTag + " class=\"btn " + inProcessBtnClass + "\" id=\"InProcess" + data[i].OrderID + "\" onclick=\"setInProcess('" + data[i].InvoiceID + "')\">" + inProcessBtnText + "</button> " + onHoldBadge + "</td>\
						<td><div class=\"btn-group\">\
								<button  " + disabledProcessTag + " class=\"btn  btn-default\" id=\"Processed" + data[i].InvoiceID + "\" onclick=\"setProcessed('" + data[i].InvoiceID + "')\">Done</button>\
								<button " + disabledProcessTag + " type=\"button\" class=\"btn btn-default dropdown-toggle\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\
								  <span class=\"caret\"></span>\
								  <span class=\"sr-only\">Toggle Dropdown</span>\
								</button>\
								<ul class=\"dropdown-menu\">\
								  <li><a href=\"#\" onclick=\"setOnHold(" + data[i].InvoiceID + ")\">On Hold</a></li>\
								  <li><a href=\"#\" onclick=\"setDelete(" + data[i].InvoiceID + ")\">Delete</a></li>\
								</ul>\</div>\
						</td>\
						<!--<td><button " + disabledProcessTag + " class=\"btn  btn-default\" id=\"Processed" + data[i].InvoiceID + "\" onclick=\"setProcessed('" + data[i].InvoiceID + "')\">Done</button></td>-->\
						</tr>");
					}
					$('.dropdown-toggle').click(function(event){
						enableRefresh = false;
						setInterval(ClassChangeDetector,100);
					});
			})
			.done(function(){
				$('#pendingInvoiceTotal').text(moneyFormat(invoiceSubtotal));
				//seccond success
			})
			.fail(function(){
					
			})
			.always(function(){
				refresher = setTimeout(function () {
				
					fillPendingOrders();
				
				// this === Interval object instance
				
				}, 5000);
			});
		
		}
		
		var enableRefresh = true;
		var refresher = null;
		$(document).ready(function(){
			fillPendingOrders();
			
			//setInterval(ClassChangeDetector,1005);
		});
		function ClassChangeDetector(){
			var classText = "btn-group hidden-print";
			var buttons = $('.btn-group.hidden-print');
			stop = false;
			for(var i=0;i < buttons.length; i++){
				var currClass = $(buttons[i]).attr('class');
				if(currClass != classText){
					stop = true;
					break;
				}
			}
			if(stop){
				enableRefresh = false;
			}else{
				enableRefresh =true;
				
			}
		}
		function setInProcess(InvoiceID){
			$.get('mod.php?p=invoice&a=functions&f=setReviewInvoice&id=' + InvoiceID, function(data){
				data = JSON.parse(data);
				if(data.Result === true){
					window.open('mod.php?p=invoice&a=review&id=' + InvoiceID);
					$('#InProcess' + InvoiceID).text(data.InProcessDate);
					$('#InProcess' + InvoiceID).removeClass("btn-primary");
					$('#InProcess' + InvoiceID).addClass("btn-success");
				}else{
					alert('Sorry ' + data.User + ' started processing this order, please choose the next Order available.');
				}
			});
		}
		function setProcessed(InvoiceID){
			$.get('mod.php?p=orderqueue&a=functions&f=setProcessed&id=' + OrderID, function(data){
				data = JSON.parse(data);
				if(data.Result === true){
					$('#Processed' + OrderID).parent().parent().parent().remove();
				}else{
					alert('Sorry there was an error:\n\r' + data.Error);
				}
			});
		}
		function setOnHold(OrderID){
				$('#OnHoldReasonModal').modal('show');
				$('#OrderNumber').val(OrderID);
				
		}
		function submitSetOnHold(){
			var OrderID = $('#OrderNumber').val();
			var reason = $('#SetOnHoldReason').val();
			$.get('mod.php?p=orderqueue&a=functions&f=setOnHold&id=' + OrderID + '&reason=' + reason, function(data){
				data = JSON.parse(data);
				if(data.Result === true){
					$('#OnHoldReasonModal').modal('hide');
					
				}else{
					alert('Sorry there was an error:\n\r' + data.Error);
				}
			});
		}
		
		function setDelete(InvoiceID){
				$('#DeleteReasonModal').modal('show');
				$('#DeleteOrderNumber').val(InvoiceID);
				
		}
		function submitSetDelete(){
			var InvoiceID = $('#DeleteOrderNumber').val();
			var reason = $('#SetDeleteReason').val();
			$.get('mod.php?p=invoice&a=functions&f=voidInvoice&id=' + InvoiceID + '&reason=' + reason, function(data){
				data = JSON.parse(data);
				if(data.Result === true){
					$('#DeleteReasonModal').modal('hide');
					//fillPendingOrders();
					
				}else{
					alert('Sorry there was an error:\n\r' + data.Error);
				}
			});
		}
	</script>
	
	
	<!-- OnHold Reason Modal -->
	<div class="modal fade" id="OnHoldReasonModal">
	  <div class="modal-dialog">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	        <h4 class="modal-title" id="SetOnHoldTitle">Set On Hold</h4>
	      </div>
	      <div class="modal-body">
			<div class="form">
				<div class="form-group">
					<label for="OrderNumber">Order Number</label>
					<input type="text" class="form-control"  name="OrderNumber" id="OrderNumber" value="" readonly />
				</div>
				<!--<div class="form-group">
					<label for="InvoiceCustomer">Customer</label>
					<input type="text" class="form-control" readonly name="InvoiceCustomer" id="InvoiceCustomer" readonly />
				</div>-->
				<div class="form-group">
					<label for="SetOnHoldReason">Reason</label>
					<textarea class="form-control" rows="5" id="SetOnHoldReason"></textarea>
				</div>
			</div>
			
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
	        <button type="button" id="submitSetOnHold" class="btn btn-success" onclick="submitSetOnHold();">Set On Hold</button>
	      </div>
	    </div><!-- /.modal-content -->
	  </div><!-- /.modal-dialog -->
	</div><!-- /.modal -->
	
	<!-- Delete Reason Modal -->
	<div class="modal fade" id="DeleteReasonModal">
	  <div class="modal-dialog">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	        <h4 class="modal-title" id="SetDeleteTitle">Void Invoice</h4>
	      </div>
	      <div class="modal-body">
			<div class="form">
				<div class="form-group">
					<label for="DeleteOrderNumber">Invoice Number</label>
					<input type="text" class="form-control"  name="DeleteOrderNumber" id="DeleteOrderNumber" value="" readonly />
				</div>
				<!--<div class="form-group">
					<label for="InvoiceCustomer">Customer</label>
					<input type="text" class="form-control" readonly name="InvoiceCustomer" id="InvoiceCustomer" readonly />
				</div>-->
				<div class="form-group">
					<label for="SetDeleteReason">Reason</label>
					<textarea class="form-control" rows="5" id="SetDeleteReason"></textarea>
				</div>
			</div>
			
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
	        <button type="button" id="submitSetDelete" class="btn btn-success" onclick="submitSetDelete();">Void</button>
	      </div>
	    </div><!-- /.modal-content -->
	  </div><!-- /.modal-dialog -->
	</div><!-- /.modal -->

   </body>

 </html>