<?php 
include("../connect.php");
include("../session.php");

$for = $_REQUEST['a'];
$title = "";
$fromDate = "";
$toDate = "";
switch ($for) {
	case "customer":
		$customer = new Customer($_REQUEST["customer"]);
		$title = " - By Customer: " . $customer->Name;
		$fromDate = $_REQUEST['fromDate'];
		$toDate = $_REQUEST['toDate'];
		break;
	case "salesman":
		$salesman = new Salesman($_REQUEST['salesman']);
		$title = " - By Salesman: " . $salesman->Name;
		$fromDate = $_REQUEST['fromDate'];
		$toDate = $_REQUEST['toDate'];
		break;
	case "date":
		$title = " - By Date: ";
		$fromDate = $_REQUEST['fromDate'];
		$toDate = $_REQUEST['toDate'];
		break;
}
 ?>
 
 <!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>
   
       <?= include("navbar.php"); ?>     

   
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
<div class="container " style="padding-top: 10px;">
	<div class="panel panel-default">
	  <div class="panel-heading form-inline">
	  <a class="btn btn-success hidden-print" role="button" style="float: right;" href="#" download="OrderHistory<?= $title . "(" . date("m.d.Y",strtotime($fromDate)) . " - " . date("m.d.Y",strtotime($toDate)) . ")" ?>.xls" href="#" onclick="return ExcellentExport.excel(this, 'orderhistory', 'Order History');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>
	  		    <h3 class="panel-title">Top 25 Products<?= $title . " - <i>From: " . date("m/d/Y",strtotime($fromDate)) . " To: " . date("m/d/Y",strtotime($toDate)) . "</i>"?></h3><br />
				
				<form method="get" action="" class="hidden-print">
	  		    	<select class="form-control" name="sort">
	  		    		<option value="TotalOrder">Qty Ordered</option>
						<option value="TotalPrice">Total Revenue</option>
	  		    		<option value="SKU">SKU</option>
	  		    		<option value="Line">Line</option>
	  		    	</select>
	  		    	<select class="form-control" name="direction">
	  		    		<option <?= (isset($_REQUEST['direction']) && $_REQUEST['direction'] == "ASC")?"selected":"" ?> value="ASC">Ascending</option>
	  		    		<option <?= (isset($_REQUEST['direction']) && $_REQUEST['direction'] == "DESC")?"selected":"" ?> value="DESC">Descending</option>
	  		    	</select>
					<?php
						if($for == "customer"){
					?>
					<input type="hidden" name="customer" value="<?= $_REQUEST["customer"] ?>" />
					<?php		
						}else if($for == "salesman"){
					?>
					<input type="hidden" name="salesman" value="<?= $_REQUEST["salesman"] ?>" />
					<?php		
						}
					?>
	  		    	<input type="hidden" name="a" value="<?= $_REQUEST["a"] ?>" />
	  		    	<input type="hidden" name="fromDate" value="<?= $_REQUEST["fromDate"] ?>" />
	  		    	<input type="hidden" name="toDate" value="<?= $_REQUEST["toDate"] ?>" />
	  		    	<input type="submit" class="form-control" name="" value="Sort" />
	  		    </form>
	  </div>
	  <div class="panel-body">
	  	<table class="table table-hover table-condensed" id="orderhistory">
	  		<thead>
	  			<tr>
	  				<th>Line</th>
	  				<th>SKU</th>
					<th>Description</th>
					<th>Order Count</th>
					<th>Average Per Order</th>
	  				<th>Qty Ordered</th>
					<th>Total Revenue</th>
	  			</tr>
	  			
	  		</thead>
	    <?php 
	    if (isset($_REQUEST['sort'])) {
	    	if ($_REQUEST['sort'] != "") {
	    		$sort = $_REQUEST['sort'];
	    		$direction = $_REQUEST['direction'];
	    	}
	    }else {
	    	$sort = "TotalOrder";
	    	$direction = "DESC";
	    }
	    
	    if ($for == "customer") {
			$query = "SELECT * FROM (SELECT Line, SKU, Description, COUNT(DISTINCT(ORDER_HEAD.OrderID)) AS OrderCount, ROUND(SUM(OrderQty)/COUNT(DISTINCT(ORDER_HEAD.OrderID)),2) as AveragePerOrder, SUM(OrderQty) AS TotalOrder, SUM(OrderQty*Price) As TotalPrice, ROUND(SUM(OrderQty*Price)/SUM(OrderQty),2) As AveragePrice FROM `ORDER_DETAIL`, `ORDER_HEAD` WHERE ORDER_HEAD.OrderID = ORDER_DETAIL.OrderID AND ORDER_HEAD.AccountNumber LIKE '" . $customer->AccountNumber . "' AND ORDER_HEAD.OrderDate BETWEEN '$fromDate' AND '$toDate' GROUP BY Line, SKU, Description ORDER BY SUM(OrderQty) DESC LIMIT 25) AS Top25Sold ORDER BY  $sort $direction";
	    }elseif($for == "salesman") {
			$query = "SELECT * FROM (SELECT Line, SKU, Description, COUNT(DISTINCT(ORDER_HEAD.OrderID)) AS OrderCount, ROUND(SUM(OrderQty)/COUNT(DISTINCT(ORDER_HEAD.OrderID)),2) as AveragePerOrder, SUM(OrderQty) AS TotalOrder, SUM(OrderQty*Price) As TotalPrice, ROUND(SUM(OrderQty*Price)/SUM(OrderQty),2) As AveragePrice FROM `ORDER_DETAIL`, `ORDER_HEAD` WHERE ORDER_HEAD.OrderID = ORDER_DETAIL.OrderID AND ORDER_HEAD.Salesman LIKE '" . $salesman->ID . "'  AND ORDER_HEAD.OrderDate BETWEEN '$fromDate' AND '$toDate' GROUP BY Line, SKU, Description ORDER BY SUM(OrderQty) DESC LIMIT 25) AS Top25Sold ORDER BY  $sort $direction";
	    }elseif ($for == "date") {
			$query = "SELECT * FROM (SELECT Line, SKU, Description, COUNT(DISTINCT(ORDER_HEAD.OrderID)) AS OrderCount, ROUND(SUM(OrderQty)/COUNT(DISTINCT(ORDER_HEAD.OrderID)),2) as AveragePerOrder, SUM(OrderQty) AS TotalOrder, SUM(OrderQty*Price) As TotalPrice, ROUND(SUM(OrderQty*Price)/SUM(OrderQty),2) As AveragePrice FROM `ORDER_DETAIL`, `ORDER_HEAD` WHERE ORDER_HEAD.OrderID = ORDER_DETAIL.OrderID AND ORDER_HEAD.OrderDate BETWEEN '$fromDate' AND '$toDate' GROUP BY Line, SKU, Description ORDER BY SUM(OrderQty) DESC LIMIT 25) AS Top25Sold ORDER BY  $sort $direction";
	    }
		
		
		
	   	$result = mysqli_query($con, $query);
	   	$total = 0;
	   	while ($row = mysqli_fetch_array($result)) {
			$total += $row['TotalPrice'];
	   	?>
	   		<tr>
	   			<td><?= $row['Line'] ?></td>
	   			<td><?= $row['SKU'] ?></td>
	   			<td><?= $row['Description'] ?></td>
				<td><?= $row['OrderCount'] ?></td>
				<td><?= $row['AveragePerOrder'] ?></td>
				<td><?= $row['TotalOrder'] ?></td>
				<td><?= moneyFormat($row['TotalPrice']) ?></td>	   			
	   		</tr>
	   	<?php
	   	}
	     ?>
	     </table>
	  </div>
	  <div class="panel-footer" style="height: 100px;" >
	  	<span style="float: left; text-align: left;">
	  		
	  	</span>	
	  	<span  style="float: right; text-align: right;">
	  		<span><b>Total Revenue: </b><?= moneyFormat($total) ?></span>
	  	</span>	
	  </div>
	  
</div>       
<script type="text/javascript">

$('[name=filter]').on('keypress', function(e) {
	if (e.which == 13) {
		filter();
	}

});
function clearFilter() {
	$('[name=filter]').val("");
	$('#clearButton').css('display', 'none');
	$('tr').css('display', '');
	
}
function filter() {
	var	name = $('[name=filter]').val();
	filterByName(name);
}
function filterByName(name) {
	$('#clearButton').css('display', '');
	for (var i = 0; i < $('td').length; i=i+7) {
	
		var text = $($('td')[i]).text();
		
		var result = text.toUpperCase().indexOf(name.toUpperCase());
		if (text != name) {
			$($('tr')[i/7+1]).css('display', 'none');
		}else {
			$($('tr')[i/7+1]).css('display', '');
		}
		
	}
}
function fillEditOrder(orderID) {
	clearEditOrder(); 
	$.get("functions.php?action=getOrderDetails&orderID=" + orderID, function(data) {
		data = JSON.parse(data);
		$('#EditOrderTitle').text('Edit Order #' + data.OrderID);
		$('#EditModalOrderID').val(data.OrderID);
		for (var i = 0; i < data.Items.length; i++) {
			$('#EditOrderModalBody').append('<tr><td>' + data.Items[i].Group.toString() + '<br />' + data.Items[i].Line.toString() + '</td><td>' + data.Items[i].SKU.toString() + '</td><td>' + data.Items[i].Description + ' ' + data.Items[i].Notes.toString() + '</td><td><input class="form-control EditOrderItem" style="width: 80px;" type="text" name="' + data.Items[i].ID + '" data-Key="' + data.Items[i].Group.toString() + "-" + data.Items[i].Line.toString() + "-" + data.Items[i].SKU.toString() + '" data-OriginalQty="' + data.Items[i].OrderQty + '" value="' + data.Items[i].OrderQty + '" /></td><td>' + data.Items[i].Price + '</td><td>' + parseFloat(data.Items[i].Price)*parseInt(data.Items[i].OrderQty) + '</td></tr>');
		}
		$('#EditOrderModal').modal();

	});
}
function clearEditOrder() {
	$('#EditOrderTitle').text('Edit Order');
	$('#EditModalOrderID').val('0');
	$('#EditOrderModalBody').html('');
	
}
function saveOrderInfo() {
	var items = $('.EditOrderItem');
	var changes = new Object();
	changes.OrderID = $('#EditModalOrderID').val();
	changes.Items = new Array();
	for (var i = 0; i < items.length; i++) {
		var origQty = parseInt($($('.EditOrderItem')[i]).attr("data-OriginalQty"));
		var newQty = parseInt($($('.EditOrderItem')[i]).val());
		var itemKey = $($('.EditOrderItem')[i]).attr("data-Key")
		if (origQty != newQty) {
			var item = new Object()
			item.ID = $($('.EditOrderItem')[i]).attr('name');
			item.NewQty = newQty;
			item.OriginalQty = origQty;
			item.ItemKey = itemKey;
			changes.Items.push(item);
		}
		
	}
	$.post("functions.php?action=saveOrderDetail", changes, function(data) {
		if(data == "true"){
			location.reload();
		}
	
	});
	
}

</script>

	<div class="modal fade" id="EditOrderModal">
	  <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="EditOrderTitle">Edit Order</h4>
	      </div>
	      <div class="modal-body">
	      	<input type="hidden" name="EditModalOrderID" id="EditModalOrderID" value="" />
			<table class="table table-hover table-condensed" id="orderhistory">
				<thead>
					<tr>
						<th>Group<br />Line</th>
						<th>SKU</th>
						<th>Description</th>
						
						<th>Qty</th>
						<th>Price</th>
						<th style="text-align: center;">Extension</th>
					</tr>
					
				</thead>
				<tbody id="EditOrderModalBody">
				</tbody>
				</table>
	      	
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
	        <button type="button" class="btn btn-primary" id="saveButton" onclick="saveOrderInfo()">Save</button>
	      </div>
	    </div><!-- /.modal-content -->
	  </div><!-- /.modal-dialog -->
	</div><!-- /.modal -->
	


   </body>
   
 </html>