<?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/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: 95%;">
	<div class="panel panel-default">
	  <div class="panel-heading form-inline">
	  

	<h3 class="panel-title">Estimate Queue</h3><br />
	  </div>
	  <div class="panel-body">
		<table class="table table-hover table-condensed" id="estimateQueue">
			<thead>
				<tr>
					<th>Estimate ID</th>
					<th style="max-width: 250px;">Customer</th>
					<th style="max-width: 100px;">Salesman</th>
					<th>Date/Time</th>
					<th>PO Number</th>
					<th>Type</th>
					<th></th>
					<th></th>
					<th></th>
				</tr>
			</thead>
			<tbody id="estimateQueueTbody" >
			
			</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 */
		function fillPendingOrders(){
			if(!enableRefresh){
				return;
			}
			$.get('mod.php?p=estimate&a=functions&f=getPendingEstimates', function(data){
					
					$('#estimateQueueTbody').html('');
					data = JSON.parse(data);
					
					//console.log(data);
					var isProcessing = false;
					for(var i=0;i < data.length;i++){
						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 EstimateType = "Estimate";
						if(data[i].ApproveOrder === "1"){
							EstimateType = "Order";
						}
						var Notes = "";
						if(data[i].EstimateNotes !== ""){
							Notes = "<br /><small><b>Note: </b>" + data[i].EstimateNotes + "</small>";
						}
						$('#estimateQueueTbody').append("<tr id=\"row-" + data[i].EstimateID + "\"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].EstimateID + " <span class=\"caret\"></span>\
							</button>\
							<ul class=\"dropdown-menu\">\
							  <li><a href=\"" + data[i].ViewLink + "\" target=\"_blank\">View</a></li>\
							  <li><a href=\"#\" onclick=\"\">Edit</a></li>\
							  <li><a href=\"#\" onclick=\"deleteEstimate('" + data[i].EstimateID + "');\">Delete</a></li>\
							</ul>\
						  </div>\
						</td>\
						<td style=\"max-width: 350px;\"><b>" + data[i].AccountNumber + "</b> - " + data[i].Customer.Name + Notes + Remarks + "</td>\
						<td>" + data[i].Salesman.Name + "</td>\
						<td>" + data[i].EstimateDate + "</td>\
						<td>" + data[i].PONumber + "</td>\
						<td>" + EstimateType + "</td>\
						<td><button class=\"btn btn-success\" onclick=\"sendToShoppingCart('" + data[i].EstimateID + "');\">Send To Cart</button></td>\
						<td><button class=\"btn btn-success\" onclick=\"createOrder('" + data[i].EstimateID + "');\">Create Order</button></td>\
						<td><button class=\"btn btn-default\" onclick=\"archiveEstimate('" + data[i].EstimateID + "');\">Archive</button></td>\
						</tr>");
					}
					$('.dropdown-toggle').click(function(event){
						enableRefresh = false;
						setInterval(ClassChangeDetector,100);
					});
			})
			.done(function(){
				//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 sendToShoppingCart(eid){
			$.get('mod.php?p=estimate&a=functions&f=sendToShoppingCart&id=' + eid, function(){
				
				alert("Estimate loaded to shopping cart");
				
			});
		}
		function createOrder(eid){
			$.get('mod.php?p=estimate&a=functions&f=createOrder&id=' + eid, function(data){
				if(data == "false"){
					alert("Error, maybe the estimate is already processed");
				}else{
					data = JSON.parse(data);
					if(confirm("Order " + data.OrderID +  "  created, redirect to Order Queue?")){
						window.location = "mod.php?p=orderqueue&a=queue";
					}else{
						location.reload();
					}
				}
				
					
			});
		}
		function deleteEstimate(eid){
			$.get('mod.php?p=estimate&a=functions&f=deleteEstimate&id=' + eid, function(data){
				data = JSON.parse(data);
				if(data.Result === false){
					alert("Error deleting Estimate please refresh and try again.");
				}else{
					if(data.Result === true){
						$('#row-' + eid).remove();
						//fillPendingOrders();
					}
				}
				
					
			});
		}
		function archiveEstimate(eid){
			$.get('mod.php?p=estimate&a=functions&f=archiveEstimate&id=' + eid, function(data){
				data = JSON.parse(data);
				if(data.Result === false){
					alert("Error archiving Estimate please refresh and try again.");
				}else{
					if(data.Result === true){
						$('#row-' + eid).remove();
					}
				}
				
					
			});
		}
			
	</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>