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

$for = $_REQUEST['by'];
$title = "";
$fromDate = $_REQUEST['fromDate'];
$toDate = $_REQUEST['toDate'];
switch ($for) {
	case "customer":
		$customer = new Customer($_REQUEST["customer"]);
		$title = " - By Customer: " . $customer->Name;
		break;
	case "salesman":
		$salesman = new Salesman($_REQUEST['salesman']);
		$title = " - By Salesman: " . $salesman->Name;
		break;
	case "date":
		$title = " - By Date: ";
		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'] ?> - Invoice History From: <?= date('m-d-Y', strtotime($from)) ?> To: <?= date('m-d-Y', strtotime($to)) ?></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; width: 95%;">
	<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="AssignmentHistory<?= $title . "(" . date("m.d.Y",strtotime($fromDate)) . " - " . date("m.d.Y",strtotime($toDate)) . ")" ?>.xls" href="#" onclick="return ExcellentExport.excel(this, 'invoicehistory', 'Invoice History');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>

	  	<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="Assignment 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">Assignment History<?= $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="AssignmentID">Assignment ID</option>
	  		    		<option value="Name">Customer Name</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="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="assignmenthistory">
	  		<thead>
	  			<tr>
	  				<th>Assignment ID</th>
	  				<th>Assignment Date/Time</th>
	  				<th>Title</th>
	  				<th>Driver</th>
					<th>Status</th>
	  				<th></th>
	  			</tr>

	  		</thead>
			<tbody>
	    <?php
	    if (isset($_REQUEST['sort'])) {
	    	if ($_REQUEST['sort'] != "") {
	    		$sort = $_REQUEST['sort'];
	    		$direction = $_REQUEST['direction'];
	    	}
	    }else {
	    	$sort = "AssignmentID";
	    	$direction = "DESC";
	    }


	    	$query = "SELECT * FROM ASSIGNMENT_HEAD LEFT JOIN CUSTOMER USING(AccountNumber) WHERE DATE(AssignmentDate) BETWEEN '$fromDate' AND '$toDate' OR DATE(DeliveryDate) BETWEEN '$fromDate' AND '$toDate' ORDER BY $sort $direction";

	   	$result = mysqli_query($con, $query);
		$completedTotal = 0;
		$totalAssignments = 0;
	   	while ($row = mysqli_fetch_array($result)) {
	   		$assignment = new Assignment($row['AssignmentID']);
				$salesman = new Salesman($assignment->DeliveryUser);
				$assignment->DeliveryName = $salesman->Name;
				$totalAssignments++;
			if($row['Completed'] == 1){
				$completedTotal++;
			}
			if($row['Completed']){
				$status = "Completed";
				$statusLabelClass = "label-success";
				$statusText = "<b>User:</b> " . $row['DeliveryUser'] . " - " . $assignment->DeliveryName . "<br />";
				$statusText .= "<b>Assignment Created:</b> " . date('m/d/Y h:i a', strtotime($row['AssignmentDate'])) . "<br />";
				$statusText .= "<b>Pickup:</b> " . date('m/d/Y h:i a', strtotime($row['PickupDate'])) . "<br />";
				$statusText .= "<b>Completion Date:</b> " . date('m/d/Y h:i a', strtotime($row['DeliveryDate']))  . "<br />";
			}elseif($row['Completed'] == "0" && !is_null($row['PickupDate'])){
				$status = "Picked Up";
				$statusLabelClass = "label-primary";
				$statusText = "<b>User:</b> " . $row['DeliveryUser'] . "<br />";
				$statusText .= "<b>Assignment Created:</b> " . date('m/d/Y h:i a', strtotime($row['AssignmentDate'])) . "<br />";
				$statusText .= "<b>Pickup:</b> " . date('m/d/Y h:i a', strtotime($row['PickupDate'])) . "<br />";

			}else{
				$status = "Waiting to be picked up";
				$statusLabelClass = "label-warning";

			}
	   	?>
	   		<tr>
				<td style="min-width: 90px;">
					<!--<span class="visible-print-block"><?= $row['AssignmentID'] ?></span>-->
					<!-- Single button -->

					<!-- Split button -->
					<div class="btn-group">
					  <a href="mod.php?p=assignments&a=view&id=<?= $row['AssignmentID'] ?>" class="btn btn-default">
						<?= "A" . $row['AssignmentID'] ?>
					  </a>
					</div>
				</td>
				<td style="white-space: nowrap;"><?= date("m/d/Y g:i a",strtotime($row['AssignmentDate'])) ?></td>
	   		<td style="max-width: 100px; white-space: nowrap;  overflow: hidden;  text-overflow: ellipsis;" class="hidden-print"><?= $row['AssignmentTitle'] ?></td>
				<td style="white-space: nowrap;"><?= $assignment->DeliveryUser . " - " . $assignment->DeliveryName ?></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;"></td>
	   		</tr>
	   	<?php
	   	}
	     ?>
			</tbody>
	     </table>
	  </div>
	  <div class="panel-footer" style="height: 130px;" >
	  	<span style="float: left; text-align: left;">
			<?php

			?>
			<strong>Total Completed Assignments: </strong><i><?= ($completedTotal) ?></i> <br>
			<strong>Total Pending Assignments: </strong><i><?= ($totalAssignments-$completedTotal) ?></i> <br>
	  	</span>
	  </div>

	</div>

</div>
<script type="text/javascript">

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

});
function setDelete(AssignmentID){
		$('#DeleteReasonModal').modal('show');
		$('#DeleteOrderNumber').val(AssignmentID);

}
function submitSetDelete(){
	var AssignmentID = $('#DeleteOrderNumber').val();
	var reason = $('#SetDeleteReason').val();
	$.get('mod.php?p=invoice&a=functions&f=voidInvoice&id=' + AssignmentID + '&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);
		}
	});
}
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', '');
		}

	}
}
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();
		}

	});

}
function processOrder(orderID){
	$.get('mod.php?p=invoice&a=functions&f=processOrder&order=' + orderID, function(data){
		alert(data);
		});
}
</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 -->

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



	<!-- 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>
