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

$for = $_REQUEST['f'];
$title = "";
$fromDate = "";
$toDate = "";

if(isset($_REQUEST['filter'])){
	
	if(trim(urldecode($_REQUEST['filter'])) != ""){
		
		$filter = mysqli_real_escape_string($con, trim(urldecode($_REQUEST['filter'])));
		
	}else{
		$filter = "%";
	}
}else{
	$filter = "%";
}
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;
}

function getElapsedTime($from, $to){
	$from = strtotime($from);
	$to = strtotime($to);
	return (secondsToTime($to-$from));
	
}
function secondsToTime($s)
{
    $h = floor($s / 3600);
    $s -= $h * 3600;
    $m = floor($s / 60);
    $s -= $m * 60;
    return $h.':'.sprintf('%02d', $m).':'.sprintf('%02d', $s);
}
 ?>
 
 <!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/functions.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("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, 'lostsalestable', 'Lost Sales');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>
	  <button class="btn btn-success hidden-print" style="float: right; margin-right: 10px;"  onclick="window.print();">Print</button>
	  	
	  		    <h3 class="panel-title">Lost Sales Report<?= $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="LostSaleDate">Date</option>
					<option value="SKU">Part Number</option>
					<option value="Reason">Reason</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>
				<input type="hidden" name="a" value="<?= $_REQUEST["a"] ?>" />
				<input type="hidden" name="p" value="<?= $_REQUEST["p"] ?>" />
				<input type="hidden" name="f" value="<?= $_REQUEST["f"] ?>" />
				<input type="hidden" name="filter" value="<?= $_REQUEST["filter"] ?>" />
				<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="lostsalestable">
	  		<thead>
	  			
	  		</thead>
			<tbody>
	    <?php 
	    if (isset($_REQUEST['sort'])) {
	    	if ($_REQUEST['sort'] != "") {
	    		$sort = $_REQUEST['sort'];
	    		$direction = $_REQUEST['direction'];
	    	}
	    }else {
	    	$sort = "LostSaleDate";
	    	$direction = "DESC";
	    }
		
	    if ($for == "customer") {
	    	$query = "SELECT *, COUNT(id) as LostSaleCount, SUM(Qty) as TotalQty, MAX(LostSaleDate) as LostSaleDate FROM LOST_SALE WHERE AccountNumber LIKE '" . $customer->AccountNumber . "' AND DATE(LostSaleDate) BETWEEN '$fromDate' AND '$toDate' AND Reason LIKE '$filter' GROUP BY SKU, Reason ORDER BY $sort $direction";	
	    }elseif($for == "salesman") {
	    	$query = "SELECT *, COUNT(id) as LostSaleCount, SUM(Qty) as TotalQty, MAX(LostSaleDate) as LostSaleDate FROM LOST_SALE WHERE AccountNumber LIKE '" . $salesman->ID . "' AND DATE(LostSaleDate) BETWEEN '$fromDate' AND '$toDate' AND Reason LIKE '$filter'  GROUP BY SKU, Reason ORDER BY $sort $direction";	
	    }elseif ($for == "date") {
	    	$query = "SELECT *, COUNT(id) as LostSaleCount, SUM(Qty) as TotalQty, MAX(LostSaleDate) as LostSaleDate FROM LOST_SALE WHERE DATE(LostSaleDate) BETWEEN '$fromDate' AND '$toDate' AND Reason LIKE '$filter'  GROUP BY SKU, Reason ORDER BY $sort $direction";	
	    }
		//echo $query;
	   	$result = mysqli_query($con, $query);
	   	
	   	while ($row = mysqli_fetch_array($result)) {
	   		
	   	?>
	   		<tr style="margin-bottom: 10px;">
				<td>
					<div style="padding: 4px; border-style: solid; border-width: thin; margin-bottom: 10px; box-shadow: 10px 10px 5px #888888;">
						<strong><h3><?= $row['SKU'] ?></h3></strong>
						<table class="table table-hover table-condensed">
							<thead>
								<tr>
									<th style="width: 10%">Customer/Salesman</th>
									<th style="width: 15%">Date</th>
									<th style="width: 30%">Description</th>
									<th style="width: 10%">Reason</th>
									<th style="width: 10%">Competition</th>
									<th style="width: 5%">Qty</th>
									<th style="width: 5%">Price</th>
									
								</tr>
								
							</thead>
							<tbody id="ViewLostSaleDetailsTbody">
							  <?php
								  $query2 = "SELECT * FROM LOST_SALE WHERE REPLACE(SKU, '-', '') LIKE '" . str_ireplace('-','', $row['SKU']) . "'";
								  $result2 = mysqli_query($con, $query2);
								  while($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
									if(strlen($row['AccountNumber']) > 3){
										$customer = new Customer($row['AccountNumber']);
										$row2['isCustomer'] = true;
										$row2['Customer'] = $customer;
									}else{
										$salesman = new Salesman($row['AccountNumber']);
										//var_dump($salesman);
										$row2['isCustomer'] = false;
										$row2['Salesman'] = $salesman;
									}
								?>
										<tr>
											<td><?= $row2['isCustomer']?$row2['Customer']->Name:$row2['Salesman']->Name ?></td>
											<td><?= date("m/d/Y h:i a", strtotime($row2['LostSaleDate'])) ?></td>
											<td><?= $row2['Description'] ?></td>
											<td><?= $row2['Reason'] ?></td>
											<td><?= $row2['CompetitionSource'] ?></td>
											<td><?= $row2['Qty'] ?></td>
											<td><?= $row2['CompetitionPrice'] ?></td>
										</tr>
								<?php
								  }
							
							  ?>
							</tbody>
						</table>
					</div>
				</td>
	   		</tr>
	   	<?php
	   	}
	     ?>
			</tbody>
	     </table>
	  </div>
	  <div class="panel-footer" style="height: 100px;" >
	  	
	  </div>
	  
	</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[i].OrderID);
		$('#EditModalOrderID').val(data[i].OrderID);
		for (var i = 0; i < data[i].Items.length; i++) {
			$('#EditOrderModalBody').append('<tr><td>' + data[i].Items[i].Group.toString() + '<br />' + data[i].Items[i].Line.toString() + '</td><td>' + data[i].Items[i].SKU.toString() + '</td><td>' + data[i].Items[i].Description + ' ' + data[i].Items[i].Notes.toString() + '</td><td><input class="form-control EditOrderItem" style="width: 80px;" type="text" name="' + data[i].Items[i].ID + '" data-Key="' + data[i].Items[i].Group.toString() + "-" + data[i].Items[i].Line.toString() + "-" + data[i].Items[i].SKU.toString() + '" data-OriginalQty="' + data[i].Items[i].OrderQty + '" value="' + data[i].Items[i].OrderQty + '" /></td><td>' + data[i].Items[i].Price + '</td><td>' + parseFloat(data[i].Items[i].Price)*parseInt(data[i].Items[i].OrderQty) + '</td></tr>');
		}
		$('#EditOrderModal').modal();

	});
}
function clearEditOrder() {
	$('#EditOrderTitle').text('Edit Order');
	$('#EditModalOrderID').val('0');
	$('#EditOrderModalBody').html('');
	
}


</script>

	<div class="modal fade" id="ViewLostSaleDetails">
	  <div class="modal-dialog modal-lg">
	    <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="ViewLostSaleDetailsTitle">View Lost Sales Details</h4>
	      </div>
	      <div class="modal-body">
	      	<input type="text" class="form-control " readonly name="ViewLostSaleDetailsSKU" id="ViewLostSaleDetailsSKU" value=""  />
			<br />
			<table class="table table-hover table-condensed" id="lostSalesDetailsTable">
				<thead>
					<tr>
						<th>Customer/Salesman</th>
						<th>Date</th>
						<th>Description</th>
						<th>Reason</th>
						<th>Competition</th>
						<th>Qty</th>
						<th>Price</th>
						
					</tr>
					
				</thead>
				<tbody id="ViewLostSaleDetailsTbody">
				</tbody>
				</table>
	      	
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
	      </div>
	    </div><!-- /.modal-content -->
	  </div><!-- /.modal-dialog -->
	</div><!-- /.modal -->
	
	<script>
		function LoadLostSaleDetails(sku){
			$.get("mod.php?p=lostsale&a=functions&f=getLostSalesDetails&sku=" + sku, function(data){
				data = JSON.parse(data);
				$('#ViewLostSaleDetailsTbody').html('');
				$('#ViewLostSaleDetailsSKU').val(sku);
				for(var i = 0; i < data.length; i++){
					var row = $('<tr />');
					if(data[i].isCustomer){
						row.append($('<td/>').text(data[i].Customer.Name));
					}else{
						row.append($('<td/>').text(data[i].Salesman.Name));
					}
					row.append($('<td/>').text(data[i].LostSaleDate));
					row.append($('<td/>').text(data[i].Description));
					row.append($('<td/>').text(data[i].Reason));
					row.append($('<td/>').text(data[i].CompetitionSource));
					row.append($('<td/>').text(data[i].Qty));
					row.append($('<td/>').text(moneyFormat(data[i].CompetitionPrice)));
					
					$('#ViewLostSaleDetailsTbody').append(row);
				}
				$('#ViewLostSaleDetails').modal('show');
				
				//console.log(data);
			});
		}
	</script>

   </body>
   
 </html>