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

$for = $_REQUEST['for'];
//this will also select thecollectinguser as the salesman
$cashBox = (isset($_REQUEST['hideProcessed'])?$_REQUEST['hideProcessed']:"false") == "true"?true:false	;
$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;
}

if($fromDate == "" || is_null($fromDate)){
	$fromDate = "2000-01-01";
}
if($toDate == "" || is_null($toDate)){
	$toDate = date("Y-m-d", time());
}
 ?>

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

       <?php include("navbar.php"); ?>


   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
<div class="container " style="width: 99%; 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="PaymentHistory<?= $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>

	  	<div style="margin-right: 10px; float: right;">
	  			<div class="input-group">
	  			      <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="Payment 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"><?= ($cashBox)?"Cash Box":"Payment History" ?><?= $title . ($cashBox)?"":(" - <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="PAYMENT_HEAD.id">Payment 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="hidden" name="p" value="<?= $_REQUEST["p"] ?>" />
					<input type="hidden" name="for" value="<?= $_REQUEST["for"] ?>" />
	  		    	<input type="submit" class="form-control" name="" value="Sort" />
	  		    </form>

	  </div>
	  <div class="panel-body">
	  	<table class="table table-hover table-condensed" id="paymenthistory">
	  		<thead>
	  			<tr>
	  				<th>Payment ID</th>
					<th>Offline ID</th>
	  				<?= ($for != "customer") ? "<th>Customer</th>\n" : "" ?>
					<?= ($for != "salesman") ? "<th>Salesman</th>\n" : "" ?>
	  				<th>Payment Date/Time</th>
					<th>In Progress</th>
	  				<th style="text-align: center;">Total</th>
					<?php
						if($showVoid){
					?>
	  				<th class="hidden-print" style="text-align: center;">Void</th>
					<?php
						}
					?>
	  			</tr>

	  		</thead>
	    <?php
		if (isset($_REQUEST['sort'])) {
	    	if ($_REQUEST['sort'] != "") {
	    		$sort = $_REQUEST['sort'];
	    		$direction = $_REQUEST['direction'];
	    	}
	    }else {
	    	$sort = "PAYMENT_HEAD.id";
	    	$direction = "DESC";
	    }
		//$query = "SELECT PAYMENT_HEAD.ID FROM PAYMENT_HEAD WHERE Processed = 1 AND CollectingUser LIKE '$salesman' AND PAYMENT_HEAD.ID NOT IN (SELECT PaymentID ID FROM PAYMENT_SALESMAN_RECONCILE_DETAIL)";
		//$cashBoxQuery = ($cashBox)?"AND PaymentDate > '2019-01-01' AND Void = 0 AND PAYMENT_HEAD.ID NOT IN (SELECT PaymentID ID FROM PAYMENT_SALESMAN_RECONCILE_DETAIL) AND (PAYMENT_HEAD.ID NOT IN (SELECT PaymentID FROM PAYMENT_REMINDER) AND Processed = 1)":"";
		$cashBoxQuery = ($cashBox)?"AND PaymentDate > '2019-01-01' AND Void = 0 AND 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)":"";

	    if ($for == "customer") {
	    	$query = "SELECT PAYMENT_HEAD.*, SALESMAN.FullName as SalesmanName, CUSTOMER.Name, PAYMENT_HEAD.id as PaymentID FROM PAYMENT_HEAD, SALESMAN, CUSTOMER WHERE PAYMENT_HEAD.AccountNumber LIKE '" . $customer->AccountNumber . "' AND PAYMENT_HEAD.SalesmanID = SALESMAN.ID AND DATE(PaymentDate) BETWEEN '$fromDate' AND '$toDate' AND CUSTOMER.AccountNumber = PAYMENT_HEAD.AccountNumber $cashBoxQuery ORDER BY $sort $direction";
	    }elseif($for == "salesman") {
			if($cashBox){
				$query = "SELECT PAYMENT_HEAD.*, CUSTOMER.Name, PAYMENT_HEAD.id as PaymentID FROM PAYMENT_HEAD, CUSTOMER WHERE PAYMENT_HEAD.CollectingUser LIKE '" . $salesman->ID . "' AND DATE(PaymentDate) BETWEEN '$fromDate' AND '$toDate' AND CUSTOMER.AccountNumber = PAYMENT_HEAD.AccountNumber $cashBoxQuery ORDER BY $sort $direction";
			}else{
			$query = "SELECT PAYMENT_HEAD.*, CUSTOMER.Name, PAYMENT_HEAD.id as PaymentID FROM PAYMENT_HEAD, CUSTOMER WHERE PAYMENT_HEAD.SalesmanID LIKE '" . $salesman->ID . "' AND DATE(PaymentDate) BETWEEN '$fromDate' AND '$toDate' AND CUSTOMER.AccountNumber = PAYMENT_HEAD.AccountNumber $cashBoxQuery ORDER BY $sort $direction";
			}

	    }elseif ($for == "date") {
	    	$query = "SELECT PAYMENT_HEAD.*, SALESMAN.FullName as SalesmanName, CUSTOMER.Name, PAYMENT_HEAD.id as PaymentID FROM PAYMENT_HEAD, SALESMAN, CUSTOMER WHERE DATE(PaymentDate) BETWEEN '$fromDate' AND '$toDate' AND SALESMAN.ID = PAYMENT_HEAD.SalesmanID AND CUSTOMER.AccountNumber = PAYMENT_HEAD.AccountNumber $cashBoxQuery ORDER BY $sort $direction";

	    }
		//echo $query;
		$result = mysqli_query($con, $query);
	   	$total = 0;
		$totalCash = 0;
		$totalCheck = 0;
		$totalCPD = 0;
	   	while ($row = mysqli_fetch_array($result)) {
			$payment = new Payment($row['PaymentID']);
			if(!$row['Void']){
				if($row['CPD']){
					$totalCPD += $row['CheckAmount'];
				}else{
					$total += $row['CashAmount']+$row['CheckAmount'];
					$totalCash += $row['CashAmount'];
					$totalCheck += $row['CheckAmount'];
				}
			}

	   	?>
	   		<tr>

	   			<td>
						<div class="btn-group">
						  <button type="button" class="btn btn-default" onclick="window.open('../mod.php?p=payment&a=view&id=<?= $row['PaymentID'] ?>&key=<?= $payment->getTokenKey() ?>',null,'_blank')"><?= ($row['Void'])?$row['PaymentID'] . " - <b>Void</b>":$row['PaymentID']  ?> <?= ($row['CPD'])?"CPD":"" ?></button>
						  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
						    <span class="caret"></span>
						  </button>
						  <ul class="dropdown-menu" role="menu">
						    <li><a href="mod.php?p=payment&a=admin.paymentdetail&pid=<?= $row['PaymentID'] ?>">View Details</a></li>

						  </ul>
						</div>

					</td>
				<td><?= $row['OfflineID'] ?></td>
				<?= ($for != "customer") ? "<td id=\"" . $row['PaymentID'] . "-Customer\">" . $row['AccountNumber'] . " - " . $row['Name'] . "</td>" : "" ?>
				<?= ($for != "salesman") ? "<td id=\"" . $row['PaymentID'] . "-Salesman\">" . $row['SalesmanName'] . "</td>" : ""
				?>
	   			<td><?= date("m/d/Y g:i a",strtotime($row['PaymentDate'])) ?></td>
				<td id="processCell-<?=$row['PaymentID'] ?>">
				<?php
					if($row['Processed']){
				?>
					<span><?= date("m/d/Y g:i a",strtotime($row['ProcessDate'])) ?></span>
				<?php
					}elseif($row['CPDReceipt']){
				?>
					<span><b>CPD Rcvd:</b> <?= date("m/d/Y g:i a",strtotime($row['CPDReceiptDate'])) ?></span><br />
					<span><b>CPD Date:</b> <?= date("m/d/Y",strtotime($row['CPDDate'])) ?></span><br>
					<input type="button" class="btn btn-danger" value="Process" onclick="processPayment(<?=$row['PaymentID'] ?>)" />
				<?php

					}elseif($row['CPD'] && !$row['CPDReceipt']){
						if(!$cashBox){
				?>
					<span>Not Processed</span><br />
					<span><b>CPD Date:</b> <?= date("m/d/Y",strtotime($row['CPDDate'])) ?></span>
				<?php
						}else{
				?>
					<input type="button" class="btn btn-warning" value="CPD" onclick="receiveCPD(<?=$row['PaymentID'] ?>)" />
				<?php
						}
					}else{
						if(!$cashBox){
				?>
					<span>Not Processed</span>
				<?php
						}else{
				?>
					<input type="button" class="btn btn-danger" value="Process" onclick="processPayment(<?=$row['PaymentID'] ?>)" />
				<?php
						}
					}
				?>
				</td>
				<td style="text-align: right;" id="<?= $row['PaymentID'] ?>-Amount"><?= moneyFormat($row['CashAmount']+$row['CheckAmount']) ?></td>
				<?php
					if($showVoid){
				?>
				<td class="hidden-print" style="text-align: right;"><a href="#" class="btn btn-<?= $row['Void']?"primary":"danger" ?>" onclick="<?= $row['Void']?"voidDetails":"promptVoid" ?>('<?= $row['PaymentID'] ?>')"><?= $row['Void']?"Void Details":"Void" ?></a></td>
				<?php
					}
				?>
	   		</tr>
	   	<?php
	   	}
	     ?>
	     </table>
	  </div>
	  <div class="panel-footer" >
		<div class="row">
			<span style="text-align: left;">
				<strong>Cash Total: </strong><i><?= moneyFormat($totalCash) ?></i><br />
				<strong>Checks Total: </strong><i><?= moneyFormat($totalCheck) ?></i><br />
				<strong>CPD Total: </strong><i><?= moneyFormat($totalCPD) ?></i>
			</span>
			<span  style="float: right; text-align: right;">
				<strong>Total: </strong><i><?= moneyFormat($total) ?></i>
			</span>
		</div>
		<?php
		if($cashBox){
		?>
	  	<div class="row">
			<div class="col-xs-offset-6 col-xs-4">
				<div class="form-group">
					<label for="comment">Notes:</label>
					<textarea style="" class="form-control" rows="2" id="CashboxNotes"></textarea>

				</div>
			</div>
			<div class="col-xs-2">
				<button style="margin-top: 40px;" onclick="createReconciliation('<?= $salesman->ID ?>')" class="btn btn-success">Print Reconciliation</button>
			</div>

		</div>
		<?php
		}
		?>
	  </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', '');
	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 createReconciliation(salesmanID){
	$.post('mod.php?p=payment&a=functions&f=createReconciliation', {
		"sm": salesmanID,
		"notes": $('#CashboxNotes').val()
		}, function(data){
			data = JSON.parse(data);
			if(data.Result === false){
				alert("Error\n\n" + data.Error);
			}else{
				window.location = "mod.php?p=payment&a=admin.viewreconciliation&id=" + data.Value;

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