<?php


if(stripos($_SERVER['SCRIPT_FILENAME'],"/admin/")>0){
	include("../connect.php");
	include("../session.php");	
}else{
	include("./connect.php");
	include("./session.php");
}

$fromDate = $_REQUEST['from'];
$toDate = $_REQUEST['to'];

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/excellentexport.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
       //        $('.grpline').css("width", "100px");
				//$('.panel-heading').after($('.panel-footer').clone().addClass('hidden-print'))
             });
           </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">
	  
	  	<div style="margin-right: 10px; float: right;">
	  			<div class="input-group hidden-print" >
	  			      <div id="clearButton" style="display: none;" class="input-group-addon" onclick="clearFilter()">
	  			      	<span class="glyphicon glyphicon-remove" aria-hidden="true"></span></div>
	  			      <input type="text" class="form-control" name="filter" placeholder="Invoice ID" value="" />
	  			      <div class="input-group-addon" onclick="filter()">
	  			      	<span class="glyphicon glyphicon-search" aria-hidden="true"></span></div>
	  			    </div>
	  	</div>
	  	
	  		    <h3 class="panel-title">Invoice History<?= $title . " <i>From: " . date("m/d/Y",strtotime($fromDate)) . " To: " . date("m/d/Y",strtotime($toDate)) . "</i>"?></h3><br />
	  </div>
	  <div class="panel-body">
	  	<table class="table table-hover table-condensed" id="invoicehistory">
	  		<thead>
	  			<tr>
	  				<th>Invoice ID</th>
	  				<th>Customer</th>
	  				<th>Invoice Date/Time</th>
	  				<th class="hidden-print">PO Number</th>
					<!--<th>Status</th>-->
	  				<th style="text-align: center;">Total</th>
	  				<th></th>
	  			</tr>
	  			
	  		</thead>
			<tbody>
	    <?php 
	    if (isset($_REQUEST['sort'])) {
	    	if ($_REQUEST['sort'] != "") {
	    		$sort = $_REQUEST['sort'];
	    		$direction = $_REQUEST['direction'];
	    	}
	    }else {
	    	$sort = "InvoiceID";
	    	$direction = "DESC";
	    }
	    
	    $query = "SELECT * FROM INVOICE_HEAD LEFT JOIN CUSTOMER USING(AccountNumber) WHERE INVOICE_HEAD.Salesman LIKE '" . $salesman->ID . "' AND DATE(CreationDate) BETWEEN '$fromDate' AND '$toDate' AND Status = 1 AND Void = 0 ORDER BY $sort $direction";
		//echo $query;
		$invoice = new Invoice($row['InvoiceID']);
		
	   	$result = mysqli_query($con, $query);
		$finalizedTotal = 0;
		$finalizedTransactions = 0;
		$unprocessedTotal = 0;
		$unprocessedTransactions = 0;
	   	
		$status = "";
	   	while ($row = mysqli_fetch_array($result)) {
	   		$invoice = new Invoice($row['InvoiceID']);
			if($row['Void'] == 0 && $row['Status'] && $row['OnHold'] == 0){
				$finalizedTotal += $invoice->InvoiceTotal;
				$finalizedTransactions++;
				
			}else{
				$unprocessedTotal += $invoice->InvoiceTotal;
				$unprocessedTransactions++;
			}
	   		
	   		
			if($row['Status']){
				$status = "Finalized";
				$statusLabelClass = "label-success";
				$statusText = "<b>User:</b> " . $row['ProcessUser'] . "<br />";
				$statusText .= "<b>Started Processing:</b> " . date('m/d/Y h:i a', strtotime($row['InProcessDate'])) . "<br />";
				$statusText .= "<b>Done Processing:</b> " . date('m/d/Y h:i a', strtotime($row['ProcessedDate'])) . "<br />";
				$statusText .= "<b>Elapsed Time:</b> " . getElapsedTime($row['InProcessDate'], $row['ProcessedDate']) . "<br />";
			}elseif($row['Void']){
				$status = "Void";
				$statusLabelClass = "label-danger";
				$statusText = "<b>User:</b> " . $row['HoldVoidUser'] . "<br />";
				$statusText .= "<b>Voided On:</b> " . date('m/d/Y h:i a', strtotime($row['VoidDate'])) . "<br />";
				$statusText .= "<b>Reason:</b> " . $row['HoldVoidReason'] . "<br />";
			}elseif($row['InProcess']){
				$status = "In Process";
				$statusLabelClass = "label-warning";
				$statusText = "<b>User:</b> " . $row['ProcessUser'] . "<br />";
				$statusText .= "<b>Started Processing:</b> " . date('m/d/Y h:i a', strtotime($row['InProcessDate'])) . "<br />";
			}elseif($row['OnHold']){
				$status = "On Hold";
				$statusLabelClass = "label-warning";
				$statusText = "<b>User:</b> " . $row['OnHoldDeleteUser'] . "<br />";
				$statusText .= "<b>Set On Hold on:</b> " . date('m/d/Y h:i a', strtotime($row['OnHoldDate'])) . "<br />";
				$statusText .= "<b>Reason:</b> " . $row['HoldDeleteReason'] . "<br />";
			}else{
				$status = "Unprocessed";
				$statusLabelClass = "label-default";
				$statusText = "No process data available";
				
			}
	   	?>
	   		<tr>
				<td>
					<!--<span class="visible-print-block"><?= $row['InvoiceID'] ?></span-->
					<!-- Single button -->
					<a href="mod.php?p=invoice&a=view&id=<?= $row['InvoiceID'] ?>&key=<?= $invoice->getTokenKey() ?>" class="btn btn-default">
						<?= $row['InvoiceID'] ?>
					  </a>
					<!-- Split button 
					<div class="btn-group">
					  <a href="mod.php?p=invoice&a=view&id=<?= $row['InvoiceID'] ?>" class="btn btn-default">
						<?= $row['InvoiceID'] ?>
					  </a>
					  <button 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="mod.php?p=invoice&a=managerview&id=<?= $row['InvoiceID'] ?>">View Manager Invoice</a></li>
						<?php
							if(!$invoice->Status){
						?>
						<li><a href="mod.php?p=invoice&a=review&id=<?= $row['InvoiceID'] ?>">Review</a></li>
						<?php
							}
						?>
						<li><a href="#">Create Credit </a></li>
						
					  </ul>
					</div>
					<!-- End Split button -->
					
					
					
				</td>
	   			<td><?= $row['Name'] ?></td>
	   			
	   			<td style="white-space: nowrap;"><?= date("m/d/Y g:i a",strtotime($row['InvoiceDate'])) ?></td>
	   			<td class="hidden-print"><?= $row['PONumber'] ?>
				</td>
				
				<!--<td><button style="font-size:12px;" data-placement="left" data-html="true" type="button" class="label <?= $statusLabelClass ?>" data-container="body" data-toggle="popover" title="<?= $status ?>" data-content="<?= $statusText ?>"><?= $status ?></a></td>-->
				<td style="text-align: right;"><?= moneyFormat($invoice->InvoiceTotal) ?></td>
				
	   		</tr>
	   	<?php
	   	}
	     ?>
			</tbody>
	     </table>
	  </div>
	  <div class="panel-footer" style="height: 130px;" >
	  	<span style="float: left; text-align: left;">
			<?php
				
			?>
	  		<b>Average Sale:</b> <?= @moneyFormat($finalizedTotal/$finalizedTransactions) ?><br />
			<strong>Total Transactions: </strong><i><?= $finalizedTransactions ?></i><br />
			
			
			
	  	</span>	
	  	<span  style="float: right; text-align: right;">
	  		<strong>Total: </strong><i><?= moneyFormat($finalizedTotal) ?></i> <br>
			
	  	</span>	
	  </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 = 1; i < $('tr').length; i++) {
	
		var text = $($('tr')[i]).text().trim();
		
		var result = text.toUpperCase().indexOf(name.toUpperCase());
		if (result < 0) {
			$($('tr')[i]).css('display', 'none');
		}else {
			$($('tr')[i]).css('display', '');
		}
		
	}
}

</script>

<script>
	$(function () {
		$('[data-toggle="popover"]').popover();
	  });	
</script>

   </body>
   
 </html>