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


$fromDate = $_REQUEST['fdate'];
$toDate = $_REQUEST['tdate'];

$query = "SELECT MIN(Sale)MAX(SaleDate) FROM SALES_HISTORY_HEADER";

 ?>
 
  <!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-fluid">
		<div class="row">
			<div class="col-xs-8">
				<h3 class="page-header">Commissions Report</h3>
				<span>From: <?= date("m/d/Y", strtotime($fromDate)) ?> - To: <?= date("m/d/Y", strtotime($toDate)) ?></span>
			</div>
			<div class="col-xs-4">
				<div class="panel panel-default">
					
				</div>
			</div>
		</div>
		
		<div class="row">
			<div class="col-xs-12">
				<h4 class="page-header">Payments</h4>
			</div>
		</div>
		
		
		<div class="row">
			<div class="col-xs-8">
				<table class="table" id="CommissionSummaryPayments">
					<thead>
						<tr>
							<th>Location</th>
							<th>Salesman</th>
							<th>Total Payments</th>
							<th>Total Discount</th>
							<th>Total Invoices</th>
							<th>Total IVU</th>
							<th>Commission</th>
							<th>Download</th>
						</tr>
						
					</thead>
					<tbody>
					<?php
						
						$query = "SELECT NEW_COMMISSION_PAYMENT_HEADER.ST, Salesman, ROUND(SUM(PaymentAmt),2) as TotalPayment, ROUND(SUM(Discount),2) as TotalDiscount, ROUND(SUM(`InvoiceTotal`),2) as TotalInvoice, ROUND(SUM(IVU),2) AS TotalTax, ROUND(SUM(CommissionAmount),2) as TotalCommission FROM NEW_COMMISSION_PAYMENT_HEADER JOIN NEW_COMMISSION_PAYMENT_DETAIL USING(InvoiceNumber) WHERE PaidDate BETWEEN '$fromDate' AND '$toDate' GROUP BY NEW_COMMISSION_PAYMENT_HEADER.ST, Salesman";
						
						$result = mysqli_query($con, $query);
						while($row = mysqli_fetch_array($result)){
							
					?>
						
						<tr>
							<td><?= $row['ST'] ?></td>
							<td><?= $row['Salesman'] ?></td>
							<td><?= moneyFormat($row['TotalPayment']); ?></td>
							<td><?= moneyFormat($row['TotalDiscount']); ?></td>
							<td><?= moneyFormat($row['TotalInvoice']); ?></td>
							<td><?= moneyFormat($row['TotalTax']); ?></td>
							<td><?= moneyFormat($row['TotalCommission']); ?></td>
							<td><a class="btn btn-success" href="mod.php?p=newcommission&a=functions&f=downloadCompletePaymentCommissionReport&fdate=<?= $fromDate ?>&tdate=<?= $toDate ?>&st=<?= $row['ST'] ?>&sm=<?= $row['Salesman'] ?>">Download Detail</a></td>
							
						</tr>
					<?php
						}
					?>
					</tbody>
				</table>
			</div>
			<div class="col-xs-4">
				<div class="panel panel-default">
					<div class="panel-heading">
						<h3 class="panel-title">Process Payment Reports</h3>
					</div>
					<div class="panel-body">
						<table class="table">
							<thead>
								<tr>
									<th>Report Type</th>
									<th></th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>Payments Report</td>
									<td><a id="processRegReportBtn" class="btn btn-success" onclick="processRegular()" href="#">Process</a></td>
								</tr>
								<tr>
									<td>Payments Commissions</td>
									<td><a class="btn btn-success" onclick="processCommissions();" href="#">Process</a></td>
								</tr>
							</tbody>
						</table>
					</div>
				</div>
			</div>
			<div class="col-xs-4">
				<div class="panel panel-default">
					<div class="panel-heading">
						<h3 class="panel-title">Download CSV Files</h3>
					</div>
					<div class="panel-body">
						<table class="table">
							<thead>
								<tr>
									<th>Report Type</th>
									<th></th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>Download Summary Report</td>
									<td><a class="btn btn-success" href="mod.php?p=newcommission&a=functions&f=downloadPaymentCommissionReportSummary&fdate=<?= $fromDate ?>&tdate=<?= $toDate ?>">Download</a></td>
								</tr>
								
								<tr>
									<td>Download Detailed Report (All)</td>
									<td><a class="btn btn-success" href="mod.php?p=newcommission&a=functions&f=downloadCompletePaymentCommissionReport&fdate=<?= $fromDate ?>&tdate=<?= $toDate ?>&st=ALL&sm=ALL">Download</a></td>
								</tr>
							</tbody>
						</table>
					</div>
				</div>
			</div>
			
			
			<div class="col-xs-4">
				<div class="panel panel-default">
					<div class="panel-heading">
						<div class="pull-right"><button onclick="addNewRule();" class="btn btn-success">Add</a></div>
						<h3 class="panel-title">Commission Rules</h3><br>
						
					</div>
					<div class="panel-body">
						<table class="table">
							<thead>
								<tr>
									<th>Line</th>
									<th>Code</th>
									<th>Percent</th>
									<th></th>
								</tr>
							</thead>
							<tbody>
								<?php
								$query = "SELECT * FROM NEW_COMMISSION_RULES ORDER BY `Line`, `Group`";
								$result = mysqli_query($con, $query);
								while($row = mysqli_fetch_array($result)){
								?>
									<tr>
										<td><?= $row['Line']=="ZZZ"?$row['Line']."*":$row['Line'] ?></td>
										<td><?= $row['Group']=="ZZZ"?$row['Group']."*":$row['Group'] ?></td>
										<td><?= $row['Rate'] ?></td>
										<th><button class="btn btn-danger" onclick="deleteCommissionRule(<?= $row['id'] ?>)">Delete</button></th>
									</tr>
								
								<?php
								}
								?>
								
								
							</tbody>
						</table>
						* Default Values<br>
						To enter a default value, enter "ZZZ" in both Line and Group fields along with the desired commission percent.
					</div>
				</div>
			</div>
		</div>
		</div>
	
		
		<div class="modal fade" id="addEditCommissionRule" tabindex="-1" role="dialog">
			<div class="modal-dialog" role="document">
				<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="addEditCommissionRuleTitle">Add/Edit Commission Rule</h4>
					</div>
					<div class="modal-body">
						<form class="form">
							<div class="form-group">
								<label for="addEditCommissionRuleLine">Line</label>
								<input type="text" class="form-control" id="addEditCommissionRuleLine" name="Line"/>
							</div>
							<div class="form-group">
								<label for="addEditCommissionRuleGroup">Group</label>
								<input type="text" class="form-control" id="addEditCommissionRuleGroup" name="Group"/>
							</div>
							<div class="form-group">
								<label for="addEditCommissionRuleRate">Rate (*Decimal, 0.07 = 7%)</label>
								<input type="text" class="form-control" id="addEditCommissionRuleRate" name="Rate"/>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
						<button type="button" onclick="saveNewRule();" class="btn btn-primary">Save changes</button>
					</div>
				</div><!-- /.modal-content -->
			</div><!-- /.modal-dialog -->
		</div><!-- /.modal -->

     <script type="text/javascript">
			function addNewRule(){
				$('#addEditCommissionRuleLine').val('');
				$('#addEditCommissionRuleGroup').val('');
				$('#addEditCommissionRuleRate').val('');
				$('#addEditCommissionRule').modal('toggle');	
			}
			function saveNewRule(){
				var line = $('#addEditCommissionRuleLine').val();
				var group = $('#addEditCommissionRuleGroup').val();
				var rate = $('#addEditCommissionRuleRate').val();
				rate = parseFloat(rate);
				if(line+group === "" || isNaN(rate)){
					alert("Invalid LineCode or Rate, please specify at least one, or a numerical rate");
					return false;
					
				}
				
				if(rate > 0.099){
					if(!confirm("Are you sure " + (rate*100) + "% is ok?")){
						return false;
					}
				}
				$.get('mod.php?p=newcommission&a=functions&f=saveNewRule&line=' + line + '&group=' + group + '&rate=' + rate, function(data){
					if(data == "true"){
						location.reload();		
					}else{
						alert("Unexpected result returned from server:\n\n" . data);
					}
						
				});
			}
			function deleteCommissionRule(id){
				if(confirm("Are you sure you want to delete this rule?")){
					$.get('mod.php?p=newcommission&a=functions&f=deleteCommissionRule&id=' + id, function(data){
						if(data == "true"){
							location.reload();		
						}else{
							alert("Unexpected result returned from server:\n\n" . data);
						}
							
					});	
				}
				
			}
			function processRegular(){
				alert('The report will begin to process now... the page will reload automatically');
				$.get('mod.php?p=newcommission&a=functions&f=processCompletePaymentCommission&fdate=<?= $fromDate ?>&tdate=<?= $toDate ?>', function(data){
					if(data == "true"){
						location.reload();		
					}else{
						alert("Unexpected result returned from server:\n\n" . data);
					}
						
				});
			}
			function processCommissions(){
				alert('The report will begin to process now... the page will reload automatically');
				$.get('mod.php?p=newcommission&a=functions&f=processCommissions&fdate=<?= $fromDate ?>&tdate=<?= $toDate ?>', function(data){
					if(data == "true"){
						location.reload();		
					}else{
						alert("Unexpected result returned from server:\n\n" . data);
					}
					
						
				});
			}
     </script>
		 	<style>
				#iFrameModalUrl{
					width: 100%;
					height: 500px;
					border: none;
				}
				
			</style>
			
		 
   </body>
 </html>