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

$for = $_REQUEST['for'];
//$cashBox = (isset($_REQUEST['hideProcessed'])?$_REQUEST['hideProcessed']:"false") == "true"?true:false	;
$cashBox = true;
$title = "";
$fromDate = "";
$toDate = "";
$showVoid = false;
if($_SESSION['Username'] == "jcorrea" || $_SESSION['Username'] == "elisamuel40" || $_SESSION['Username'] == "ccordova"){
	$showVoid = true;
}else{
	$showVoid = false;
}
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/functions.js"></script>
       	 <script src="../js/excellentexport.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
       //        $('.grpline').css("width", "100px");
             });
			 var paymentTotals = {};
			 var checkTotals = {};
			 var cashTotals = {};

           </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" role="button" style="float: right;" href="#" download="PaymentCashBox.xls" href="#" onclick="return ExcellentExport.excel(this, 'paymentcashbox', 'Payment CashBox');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>

	  <h3 class="panel-title">Payment Cashbox </h3><br />


	  </div>
	  <div class="panel-body">
	  	<table class="table table-hover table-condensed" id="paymentcashbox">
	  		<thead>
	  			<tr>
					<th>Salesman</th>
	  				<th>Payments</th>
					<th>Total Cash</th>
	  				<th>Total Checks</th>
					<th>Total Transfers</th>
	  				<th>Total</th>
					<th>Cash Box</th>
	  			</tr>

	  		</thead>
	    <?php

	    $query = "SELECT COUNT(PAYMENT_HEAD.ID) Payments,FullName, SalesmanID, CollectingUser, SUM(CashAmount) TotalCash, SUM(CheckAmount) TotalCheck, SUM(TransferAmount) TotalTransfer FROM PAYMENT_HEAD LEFT JOIN SALESMAN ON(CollectingUser = SALESMAN.ID) WHERE PAYMENT_HEAD.ID NOT IN (SELECT PaymentID ID FROM PAYMENT_SALESMAN_RECONCILE_DETAIL) AND (PAYMENT_HEAD.ID NOT IN (SELECT PaymentID ID FROM PAYMENT_REMINDER) OR Processed = 0) AND PaymentDate > '2019-01-01' and Void = 0 GROUP BY CollectingUser";
	    //echo $query;
		$result = mysqli_query($con, $query);
	   	$total = 0;
		$totalCash = 0;
		$totalCheck = 0;
		$totalTransfer = 0;
		$totalCPD = 0;
	   	while ($row = mysqli_fetch_array($result)) {
				$total +=$row['TotalCash']+$row['TotalCheck']+$row['TotalTransfer'];
	   	?>
	   		<tr>
				<td>
					<?= $row['CollectingUser'] . " - " . $row['FullName'] ?>
				</td>
	   			<td><?= $row['Payments'] ?></td>
				<td><?= moneyFormat($row['TotalCash']) ?></td>
	   			<td><?= moneyFormat($row['TotalCheck']) ?></td>
				<td><?= moneyFormat($row['TotalTransfer']) ?></td>

				<td style="text-align: right;"><?= moneyFormat($row['TotalCash']+$row['TotalCheck']+$row['TotalTransfer']) ?></td>
				<td><a href="mod.php?p=payment&a=admin.paymenthistory&for=salesman&salesman=<?= $row['CollectingUser'] ?>&hideProcessed=true" class="btn btn-primary">Cash Box</a></td>
	   		</tr>
	   	<?php
	   	}
	     ?>
	     </table>
	  </div>
	  <div class="panel-footer" >
			<div style="text-align: right; margin-right: 20px;"><b>Total:</b> <?= moneyFormat($total) ?></div>
	  	<br>
		<br>
	  </div>
	</div>

</div>
<script type="text/javascript">
	var checkedPayments = [];
	var totalChecked = 0;
	var totalCash = 0;
	var totalCheck = 0;
$('input[name^="Received-"]').on('change', function(e){
	totalChecked = 0;
	totalCash = 0;
	totalCheck = 0;
	checkedPayments = [];
	for(var i = 0; i < $('input[name^="Received-"]').length; i++){
		if($($('input[name^="Received-"]')[i]).prop("checked")){
			var paymentID = $($('input[name^="Received-"]')[i]).data('id');
			checkedPayments.push(paymentID);
			totalChecked += paymentTotals[paymentID];
			totalCash += cashTotals[paymentID];
			totalCheck += checkTotals[paymentID];
		}
	}
	$('#totalCash').text(moneyFormat(totalCash));
	$('#totalCheck').text(moneyFormat(totalCheck));
	$('#totalReceived').text(moneyFormat(totalChecked));
	console.log(checkedPayments);
	});
$('#savePrint').on('click', function(data){
	if(checkedPayments.length == 0){
		alert('Please choose at least 1 payment to receive');
	}else{

	}
});
$('[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', '');
	var cols = $('#paymenthistory th').length;
	for (var i = 0; i < $('#paymenthistory td').length; i=i+cols) {

		var text = $($('td')[i]).text();

		var result = text.toUpperCase().indexOf(name.toUpperCase());
		if (text != name) {
			$($('tr')[i/cols+1]).css('display', 'none');
		}else {
			$($('tr')[i/cols+1]).css('display', '');
		}

	}
}
function processPayment(paymentID) {
	$.get("mod.php?p=payment&a=functions&f=processPayment&pid=" + paymentID, function(data){
		$('#processCell-' + paymentID).html('');
		var processDate = new Date(data);
		var ampm = Math.floor(processDate.getHours()/12);
		if(ampm == 0){
			ampm = "am";
		}else{
			ampm = "pm";
		}
		$('#processCell-' + paymentID).html((processDate.getMonth()+1) + "/" + (processDate.getDate()) + "/" + processDate.getFullYear() + " " + processDate.getHours()%12 + ":" + ('00'+processDate.getMinutes()).substring(processDate.getMinutes().toString().length) + " " + ampm);

	});
}

function receiveCPD(paymentID) {
	$.get("mod.php?p=payment&a=functions&f=receiveCPD&pid=" + paymentID, function(data){
		$('#processCell-' + paymentID).html('');
		var processDate = new Date(data);
		var ampm = Math.floor(processDate.getHours()/12);
		if(ampm == 0){
			ampm = "am";
		}else{
			ampm = "pm";
		}

		$('#processCell-' + paymentID).html('<input type="button" class="btn btn-primary" value="CPD - ' + (processDate.getMonth()+1) + '/' + (processDate.getDate()) + '/' + processDate.getFullYear() + ' ' + processDate.getHours()%12 + ':' + ('00'+processDate.getMinutes()).substring(processDate.getMinutes().toString().length) + ' ' + '" />')

	});
}
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) {
		data = JSON.parse(data);
		if(data.result == "true"){
			location.reload();
		}else{
			alert(data.error);
			console.log(data.sql);
		}
	});
}

function promptVoid(paymentID){
	//clearVoidPaymentModal();
	$('#VoidPaymentID').val(paymentID);
	$('#VoidPaymentName').val($('#' + paymentID + '-Customer').text());
	$('#VoidPaymentAmount').val($('#' + paymentID + '-Amount').text());
	$('#VoidPaymentSalesman').val($('#' + paymentID + '-Salesman').text());
	$('#VoidPaymentModal').modal('show');
}
function clearVoidPaymentModal() {
	$('#VoidPaymentID').val('');
	$('#VoidPaymentName').val('');
	$('#VoidPaymentAmount').val('');
	$('#VoidPaymentSalesman').val('');
	$('#VoidPaymentReason').val('');
}
function voidPayment() {
	var data = new Object();
	data.pid = $('#VoidPaymentID').val();
	data.Reason = $('#VoidPaymentReason').val();

	$.post("./mod.php?p=payment&a=functions&f=voidPayment", data, function(returnData) {
		clearVoidPaymentModal();
		console.log(returnData);
		returnData = JSON.parse(returnData);
		$('#VoidPaymentModal').modal('hide');
		if(returnData.result == "true"){
			location.reload();
		}
	});
}
function voidDetails(id){
	$.get('./mod.php?p=payment&a=functions&f=voidPaymentDetails&pid=' + id, function(data){
			clearVoidDetails();
			data = JSON.parse(data);
			$('#VoidByUser').val(data.VoidUser);
			$('#VoidDate').val(data.VoidDate);
			$('#VoidReason').val(data.VoidReason);
			$('#VoidDetailsModal').modal('show');
	});
	//alert('Not Implemented');

}
function clearVoidDetails(){
	$('#VoidByUser').val('');
	$('#VoidDate').val('');
	$('#VoidReason').val('');
}



</script>

	<div class="modal fade" id="VoidPaymentModal">
	  <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="VoidPaymentTitle">Void Payment</h4>
	      </div>
	      <div class="modal-body">
			<div class="form">
				<input type="hidden" name="VoidPaymentID" id="VoidPaymentID" value="" />
				<div class="form-group">
					<label for="VoidPaymentName">Customer</label>
					<input type="text" class="form-control" readonly name="VoidPaymentName" id="VoidPaymentName" value="" />
				</div>
				<div class="form-group">
					<label for="VoidPaymentAmount">Payment Total</label>
					<input type="text" class="form-control" readonly name="VoidPaymentAmount" id="VoidPaymentAmount" value="" />
				</div>
				<div class="form-group">
					<label for="VoidPaymentSalesman">Salesman</label>
					<input type="text" class="form-control" readonly name="VoidPaymentSalesman" id="VoidPaymentSalesman" value="" />
				</div>
				<div class="form-group">
					<label for="VoidPaymentReason">Reason</label>
					<textarea class="form-control" rows="5" id="VoidPaymentReason"></textarea>
				</div>
			</div>

	      </div>
	      <div class="modal-footer">
			<small>WARNING: THIS CANNOT BE UNDONE!</small>
	        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
	        <button type="button" class="btn btn-success" onclick="voidPayment()">Submit Void</button>
	      </div>
	    </div><!-- /.modal-content -->
	  </div><!-- /.modal-dialog -->
	</div><!-- /.modal -->

	<!-- -->

	<div class="modal fade" id="VoidDetailsModal">
	  <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="VoidPaymentTitle">Void Details</h4>
	      </div>
	      <div class="modal-body">
			<div class="form">

				<div class="form-group">
					<label for="VoidByUser">Username</label>
					<input type="text" class="form-control" readonly name="VoidByUser" id="VoidByUser" value="" />
				</div>
				<div class="form-group">
					<label for="VoidDate">Date</label>
					<input type="text" class="form-control" readonly name="VoidDate" id="VoidDate" value="" />
				</div>
				<div class="form-group">
					<label for="VoidReason">Reason</label>
					<textarea class="form-control" readonly rows="5" id="VoidReason"></textarea>
				</div>
			</div>

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

	<!-- -->

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