<?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">Sales <small>All sales, regardless of payment status</small></h4>
			</div>
		</div>
		<div class="row">
			<div class="col-xs-12">
				<table class="table" id="CommissionReportSales">
					<thead>
						<tr>
							<th>Salesman</th>
							<th style="text-align: right;">Sales <i>(Pre-Tax)</i></th>
							<th style="text-align: right;">Amount to Compute</th>
							<th style="text-align: center;">Commission Rate</th>
							<th style="text-align: right;">Potential Commission</th>
							
						</tr>
						
					</thead>
					<tbody>
					<?php
						
						$query = "SELECT SALESMAN_SALES.*, SALESMAN.ID AS SalesmanID, CommissionRate, GlobalCommission, CommissionSalesman FROM SALESMAN LEFT JOIN (SELECT Salesman, round(SUM(Subtotal),2) as TotalSales, SUM(Tax1Total+Tax2Total) as TotalTaxAmount, SUM(Tax1Total) as Tax1Total, SUM(Tax2Total) as Tax2Total FROM `INVOICE_HEAD` WHERE InvoiceDate BETWEEN '" . $fromDate . "' AND '" . $toDate . " 23:59:59' GROUP BY Salesman) SALESMAN_SALES ON(SALESMAN.ID = SALESMAN_SALES.Salesman)";
						
						$result = mysqli_query($con, $query);
						$totalSales = 0;
						$totalCommission = 0;
						$precommissionTable = [];
						while($row = mysqli_fetch_array($result)){
							$salesman	= new Salesman($row['SalesmanID']);
							$precommissionTable[$row['SalesmanID']] = [];
							$precommissionTable[$row['SalesmanID']]['Information'] = $salesman;
							$precommissionTable[$row['SalesmanID']]['TotalSales'] = $row['TotalSales'];
							$precommissionTable[$row['SalesmanID']]['CommissionRate'] = $row['CommissionRate'];
							$precommissionTable[$row['SalesmanID']]['GlobalCommission'] = $row['GlobalCommission'];
							$precommissionTable[$row['SalesmanID']]['CommissionSalesman'] = $row['CommissionSalesman'];
							$precommissionTable[$row['SalesmanID']]['TotalCommission'] = $row['CommissionRate']*($row['TotalSales']);
							
							$totalSales += $row['TotalSales'];
							
						}
						$query2 = "SELECT ID, CommissionRate FROM SALESMAN WHERE GlobalCommission";
						$result2 = mysqli_query($con, $query2);
						while($row2 = mysqli_fetch_array($result2)){
							$precommissionTable[$row2['ID']]['TotalCommission'] = $totalSales*$row2['CommissionRate'];
						}
						foreach($precommissionTable as $precommissionSalesmanID => $precommissionSalesmanData){
							$totalCommission += $precommissionSalesmanData['TotalCommission'];
					?>
						
						<tr>
							<td><?= $precommissionSalesmanData['Information']->Name ?></td>
							<td style="text-align: right;"><?= moneyFormat($precommissionSalesmanData['TotalSales']); ?></td>
							<td style="text-align: right;"><?= moneyFormat($precommissionSalesmanData['GlobalCommission']?$totalSales:($precommissionSalesmanData['TotalSales'])) . ($precommissionSalesmanData['GlobalCommission']?"*":"") ?></td>
							<td style="text-align: center;"><?= ($precommissionSalesmanData['CommissionRate']*100) . "%" . ($precommissionSalesmanData['GlobalCommission']?"*":""); ?></td>
							<td style="text-align: right;"><?= moneyFormat($precommissionSalesmanData['TotalCommission']); ?></td>
							
							
							
							
						</tr>
					<?php
						}
					?>
					</tbody>
					<tfoot>
						<tr>
							<td></td>
							<td  style="text-align: right;"><b><?= moneyFormat($totalSales) ?></b></td>
							<td></td>
							<td></td>
							<td  style="text-align: right;"><b><?= moneyFormat($totalCommission) ?></b></td>
						</tr>
					</tfoot>
				</table>
				* Global Commission.
			</div>
			
		</div>
		
		
		<div class="row">
			<div class="col-xs-12">
				<h4 class="page-header">Payments <small>Payments commission report.</small></h4>
			</div>
		</div>
		
		
		<div class="row">
			<div class="col-xs-12">
				<table class="table" id="CommissionReportPayments">
					<thead>
						<tr>
							<th>Salesman</th>
							<th>Payment <i>(Pre-Tax)</i></th>
							<th>Total Discount</th>
							<th>Net Amount</th>
							<th>Commission Rate</th>
							
							<th>Total Commission</th>
							<th class="hidden-print">Report</th>
							<th class="hidden-print">Download</th>
						</tr>
						
					</thead>
					<tbody>
					<?php
						
						
						$query = "SELECT SALESMAN_PAYMENTS.*, SALESMAN.ID SalesmanID, CommissionRate , GlobalCommission, CommissionSalesman FROM SALESMAN LEFT JOIN (SELECT Salesman, SUM(IF(Processed,0,1)) PaymentsWithoutProcess, ROUND(SUM(PaymentAmount),2) as TotalPayment, ROUND(SUM(PaymentAmount),2)-sum(IF(PartialPayment, 0, TaxAmount)) TotalSales, ROUND(SUM(DiscountAmount),2) as TotalDiscount, sum(IF(PartialPayment, 0, TaxAmount)) as TotalTax, SUM(IF(PartialPayment,0,Tax1Total)) Tax1Total, SUM(IF(PartialPayment,0,Tax2Total)) Tax2Total FROM DETAILED_PAYMENT LEFT JOIN INVOICE_HEAD USING(InvoiceID) WHERE DATE(PaymentDate) BETWEEN '$fromDate' AND '$toDate' AND DETAILED_PAYMENT.Void = 0 GROUP BY Salesman) SALESMAN_PAYMENTS on(SALESMAN.ID = SALESMAN_PAYMENTS.Salesman) WHERE CommissionSalesman";
						$result = mysqli_query($con, $query);
						$netRevenue = 0;
						$totalSales = 0;
						$totalDiscount = 0;
						$totalCommission = 0;
						$commissionTable = [];
						while($row = mysqli_fetch_array($result)){
							$salesman = new Salesman($row['SalesmanID']);
							$commissionTable[$row['SalesmanID']] = [];
							$commissionTable[$row['SalesmanID']]['Information'] = $salesman;
							$commissionTable[$row['SalesmanID']]['PaymentsWithoutProcess'] = $row['PaymentsWithoutProcess'];
							$commissionTable[$row['SalesmanID']]['TotalSales'] = $row['TotalSales'];
							$commissionTable[$row['SalesmanID']]['TotalDiscount'] = $row['TotalDiscount'];
							$commissionTable[$row['SalesmanID']]['CommissionRate'] = $row['CommissionRate'];
							$commissionTable[$row['SalesmanID']]['GlobalCommission'] = $row['GlobalCommission'];
							$commissionTable[$row['SalesmanID']]['CommissionSalesman'] = $row['CommissionSalesman'];
							$commissionTable[$row['SalesmanID']]['TotalCommission'] = $row['CommissionRate']*($row['TotalSales']-$row['TotalDiscount']);
							$netRevenue += $row['TotalSales']-$row['TotalDiscount'];
							$totalSales += $row['TotalSales'];
							$totalDiscount += $row['TotalDiscount'];
							if(!$row['CommissionSalesman']){
								continue;
							}
							
						}
						$query2 = "SELECT ID, CommissionRate FROM SALESMAN WHERE GlobalCommission";
						$result2 = mysqli_query($con, $query2);
						while($row2 = mysqli_fetch_array($result2)){
							$commissionTable[$row2['ID']]['TotalCommission'] = $netRevenue*$row2['CommissionRate'];
						}
						foreach($commissionTable as $commissionSalesmanID => $commissionSalesmanData){
							
						$totalCommission += $commissionSalesmanData['TotalCommission'];
					?>
						
						<tr <?= ($commissionSalesmanData['PaymentsWithoutProcess'] > 0)?"class=\"danger\"":"" ?>>
							
							<td><?= $commissionSalesmanData['Information']->Name ?>
							
							<?php
							
							if($commissionSalesmanData['PaymentsWithoutProcess'] > 0){
								echo "<br><small><i>*Payments pending...</i></small>";
							}
							?>
							</td>
							<td><?= moneyFormat($commissionSalesmanData['TotalSales']); ?></td>
							<td><?= moneyFormat($commissionSalesmanData['TotalDiscount']); ?></td>
							<td><?= moneyFormat($commissionSalesmanData['GlobalCommission']?$netRevenue:($commissionSalesmanData['TotalSales']-$commissionSalesmanData['TotalDiscount'])) . ($commissionSalesmanData['GlobalCommission']?"*":"") ?></td>
							<td><?= $commissionSalesmanData['CommissionRate']*100 . "% " . ($commissionSalesmanData['GlobalCommission']?"*":"") ?></td>
							
							<td><?= moneyFormat($commissionSalesmanData['TotalCommission']); ?></td>
							<td class="hidden-print"><a class="btn btn-primary btn-sm" href="mod.php?p=commission&a=salesmanreport&sm=<?= $commissionSalesmanData['Information']->ID ?>&fdate=<?= $fromDate ?>&tdate=<?= $toDate ?>">Report</a></td>
							<td class="hidden-print"><a class="btn btn-success btn-sm" href="mod.php?p=commission&a=functions&f=downloadPaymentsReport&fromDate=<?= $fromDate ?>&toDate=<?= $toDate ?>&sm=<?= $commissionSalesmanData['Information']->ID ?>">Download Detail</a></td>
							
						</tr>
					<?php
						}
					?>
					</tbody>
					<tfoot>
						<tr>
							<td></td>
							<td><b><?= moneyFormat($totalSales) ?></b></td>
							<td><b><?= moneyFormat($totalDiscount) ?></b></td>
							<td><b><?= moneyFormat($netRevenue) ?></b></td>
							<td></td>
							<td><b><?= moneyFormat($totalCommission) ?></b></td>
						</tr>
					</tfoot>
				</table>
				*Global Commission
			</div>
			
			
			
		</div>
	</div>
	

     <script type="text/javascript">
			function processRegular(){
				alert('The report will begin to process now... the page will reload automatically');
				$.get('mod.php?p=taxreports&a=functions&f=processPaymentTaxRegular&fdate=<?= $fromDate ?>&tdate=<?= $toDate ?>', function(data){
					if(data == "true"){
						location.reload();		
					}else{
						alert("Unexpected result returned from server:\n\n" . data);
					}
						
				});
			}
			function processExceptions(){
				alert('The report will begin to process now... the page will reload automatically');
				$.get('mod.php?p=taxreports&a=functions&f=processPaymentTaxExceptions&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>