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

$for = $_REQUEST['for'];
//$cashBox = (isset($_REQUEST['hideProcessed'])?$_REQUEST['hideProcessed']:"false") == "true"?true:false	;
$salesman = $_REQUEST['sm'];
if($_SESSION['Username'] == "jcorres" || $_SESSION['Username'] == "elisamuel40" || $_SESSION['Username'] == "ccordova"){
	$showVoid = true;
}else{
	$showVoid = false;
}

 ?>

 <!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 = {};
				var transferTotals = {};

           </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="PaymentsWithoutDeposit<?= $title . "(" . date("m.d.Y",strtotime($fromDate)) . " - " . date("m.d.Y",strtotime($toDate)) . ")" ?>.xls" href="#" onclick="return ExcellentExport.excel(this, 'orderhistory', 'Payments without deposit');" 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">Make Deposit</h3><br />

	  </div>
	  <div class="panel-body">
	  	<table class="table table-hover table-condensed" id="paymentnodeposit">
	  		<thead>
	  			<tr>
					<th>Deposit</th>
	  				<th>Payment ID</th>
					<th style="width: 25%;">Customer</th>
					<th style="">Salesperson</th>
	  				<th>Payment Date/Time</th>
					<th>Received Date/Time</th>
					<!--<th>Collecting User</th>-->
	  				<th style="text-align: center;">Total</th>
	  			</tr>

	  		</thead>
	    <?php
		$query = "SELECT * FROM PAYMENT_HEAD WHERE Processed = 1 AND Void = 0 AND (CashAmount+CheckAmount+TransferAmount) != 0 AND ID NOT IN (SELECT PaymentID FROM PAYMENT_DEPOSIT_DETAIL) AND ID NOT IN (SELECT PaymentID ID FROM PAYMENT_REMINDER)";

		$result = mysqli_query($con, $query);
	   	$total = 0;
		$totalCash = 0;
		$totalCheck = 0;
		$totalCPD = 0;

	   	while ($row = mysqli_fetch_array($result)) {
			$row['PaymentID'] = $row['ID'];
			//var_dump($row);
			$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>
						<?php
						$depositable = true;
						if($row['CPD']){
							if(strtotime($row['CPDDate']) < time()){
									$depositable = true;
							}else{
									$depositable = false;
							}
						}
						?>
						<input type="checkbox" <?= $depositable?"":"disabled" ?> data-id="<?= $row['PaymentID'] ?>" name="Received-<?= $row['PaymentID'] ?>" class="form-control">
						<script>
							paymentTotals['<?= $row['PaymentID'] ?>'] = <?= $row['CashAmount']+$row['CheckAmount'] ?>;
							checkTotals['<?= $row['PaymentID'] ?>'] = <?= $row['CheckAmount'] ?>;
							cashTotals['<?= $row['PaymentID'] ?>'] = <?= $row['CashAmount'] ?>;
							transferTotals['<?= $row['PaymentID'] ?>'] = <?= $row['TransferAmount'] ?>;
						</script>

					</td>
	   			<td><button class="btn btn-<?= $row['CPD']?"warning":"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<br>" . date("m/d/Y", strtotime($row['CPDDate']))):"" ?></button></td>

				<td><?= $payment->Customer->Name ?>
				<?= $payment->Notes?"<br><i>" . $payment->Notes . "</i>":"" ?></td>
				<td><?= $payment->Salesman->FullName ?>
					<?php
					//var_dump();
					if($row['CollectingUser'] != $payment->Salesman->SalesmanID){
						$collectedSalesman = new Salesman($row['CollectingUser']);
						echo "<br><i>Collected By " . $collectedSalesman->Name . "</i>";
					}
					 ?>
				</td>
	   			<td><?= date("m/d/Y g:i a",strtotime($row['PaymentDate'])) ?></td>
				<td><?= date("m/d/Y g:i a",strtotime($row['ProcessDate'])) ?></td>


				<td style="text-align: right;" id="<?= $row['PaymentID'] ?>-Amount"><?= moneyFormat($row['CashAmount']+$row['CheckAmount']) ?></td>

	   		</tr>
	   	<?php
	   	}
	     ?>
	     </table>
	  </div>
	  <div class="panel-footer" >
		<span  style="float: right; text-align: right;">
	  		<strong>Total: </strong><i id="totalReceived"></i><br>
			<button id="savePrint" class="btn btn-primary">Continue</button>
	  	</span>
	  	<span style="text-align: left;">
	  		<strong>Cash Total: </strong><i id="totalCash"></i><br />
	  		<strong>Checks Total: </strong><i id="totalCheck"></i><br />

	  	</span>
	  	<br>
		<br>
	  </div>
	</div>

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


	var checkedPayments = [];
	var totalChecked = 0;
	var totalCash = 0;
	var totalCheck = 0;
	var totalTransfer = 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];
			totalTransfer += transferTotals[paymentID];
		}
	}
	$('#totalCash').text(moneyFormat(totalCash));
	$('#totalCheck').text(moneyFormat(totalCheck));
	$('#totalTransfer').text(moneyFormat(totalTransfer));
	$('#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{
		$('#SaveDepositModal').modal('toggle');
	}
});
$('[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 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');
	});

}
function createDeposit(element){
	$(element).prop("disabled", true);
	var depositDate = $('#DepositDate').val();
	var depositNotes = $('#DepositNotes').val();
	var depositor = $('#SaveDepositDepositor').val();
	$.post("./mod.php?p=payment&a=functions&f=createDeposit", {
		"data": {
			"Date": depositDate,
			"Notes": depositNotes,
			"PaymentList": checkedPayments,
			"Cash": totalCash,
			"Checks": totalCheck,
			"Transfers": totalTransfer,
			"TotalDeposit": totalChecked,
			"Depositor": depositor
			}

		},
		function(data){

			data = JSON.parse(data);
			if(data.Result){
				window.location = "mod.php?p=payment&a=viewdeposit&id=" + data.DepositID;
			}else{
				alert(data.Error);
			}

			});
}
</script>

	<div class="modal fade" id="SaveDepositModal">
	  <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="SaveDepositModalTitle">Finish Deposit</h4>
	      </div>
	      <div class="modal-body">
			<div class="form">

				<div class="form-group">
					<label for="DepositDate">Deposit Date</label>
					<input type="date" class="form-control" id="DepositDate" />
				</div>
				<div class="form-group">
					<label for="SaveDepositDepositor">Depositor</label>
					<select class="form-control" id="SaveDepositDepositor" name="SaveDepositDepositor">

						<optgroup label="Users">
					<?php
						$query = "SELECT Username, FullName FROM SALESMAN UNION (SELECT Username, FullName FROM ADMINISTRATOR) ORDER BY FullName";
						$result = mysqli_query($con, $query);
						while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
						?>
						<option value="<?= $row['Username'] ?>"><?= $row['FullName'] ?></option>
						<?php
						}

					?>
							<option value="other">Other (write in notes)</option>
						</optgroup>
					<optgroup label="Direct">
							<option value="athmovil">ATH Movil</option>
							<option value="transfer">Wire Transfer</option>

						</optgroup>
					</select>
				</div>
				<div class="form-group">
					<label for="DepositNotes">Deposit Notes</label>
					<input type="text" class="form-control" id="DepositNotes" />
				</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="createDeposit(this)">Save and Print</button>
	      </div>
	    </div><!-- /.modal-content -->
	  </div><!-- /.modal-dialog -->
	</div><!-- /.modal -->

	<!-- -->




   </body>

 </html>
