<?php
include_once('include.php');
session_start();
if(!isset($_SESSION['titles']) || !isset($_SESSION['positions'])|| !isset($_SESSION['usernames'])){
header("location:index.php");
}
if(isset($_SESSION['usernames'])){
$usrr=$_SESSION['usernames'];}

$flt=racs(1);
$conn=mysqli_connect("localhost","salehljr","!2n+l)a3iX~U","salehljr_diana");

if(isset($_REQUEST['starts'])){
$starts=$_REQUEST['starts'];}
else{
$starts=date('Y-m-01');}

if(isset($_REQUEST['ends'])){
$ends=$_REQUEST['ends'];}
else{
$ends=date('Y-m-t');}

if(isset($_REQUEST['zones'])){
$zones=$_REQUEST['zones'];}
else{
$zones='all';}

if(isset($_REQUEST['regions'])){
$regions=$_REQUEST['regions'];}
else{
$regions='all';}

if(isset($_REQUEST['agents'])){
$agents=$_REQUEST['agents'];}
else{
$agents='all';}

if(isset($_REQUEST['terrys'])){
$terrys=$_REQUEST['terrys'];}
else{
$terrys='all';}

if(isset($subregions)){
$subregions=$_REQUEST['subregions'];}
else{
$subregions='all';}

if(isset($_REQUEST['agenttypes'])){
$agenttypes=$_REQUEST['agenttypes'];}
else{
$agenttypes='all';}

if(isset($_REQUEST['items'])){
$items=$_REQUEST['items'];}
else{
$items='all';}

if(isset($_REQUEST['ranges'])){
$ranges=$_REQUEST['ranges'];}
else{
$ranges='all';}

if(isset($_REQUEST['subranges'])){
$subranges=$_REQUEST['subranges'];}
else{
$subranges='all';}

if(isset($_REQUEST['dbids'])){
$dbids=$_REQUEST['dbids'];}
else{
$dbids='all';}

#$flt=racs(1);

if(strtolower($zones)!='all'){
$flt=$flt." and zones='".$zones."' ";}
if(strtolower($regions)!='all'){
$flt=$flt." and regions='".$regions."' ";}
if(strtolower($subregions)!='all'){
$flt=$flt." and sub_regions='".$subregions."' ";}
if(strtolower($agents)!='all'){
$flt=$flt." and agent_names='".$agents."' ";}
if(strtolower($dbids)!='all'){
$flt=$flt." and group_dbid='".$dbids."' ";}
if(strtolower($agenttypes)!='all'){
$flt=$flt." and agent_types='".$agenttypes."' ";}
if(strtolower($terrys)!='all'){
$flt=$flt." and territory_names='".$terrys."' ";}
if(strtolower($items)!='all'){
$flt=$flt." and item_names='".$items."' ";}
if(strtolower($ranges)!='all'){
$flt=$flt." and item_ranges='".$ranges."' ";}
if(strtolower($subranges)!='all'){
$flt=$flt." and sub_ranges='".$subranges."' ";}

?>

<!doctype html>
<link rel="stylesheet" href="css/fixedheadertable.css">
<!--<script type="text/javascript" src="https://www.gstatic.com/charts/fixedheadertable.css"></script>-->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<ol class="breadcrumb">
<li><a href="maindash.php"><i class="fa fa-dashboard"></i> Home</a></li>
<li><a href="reportpage.php"><i class="fa fa-list"></i> Reports</a></li>
<li class="active">Rg[<?php echo $regions;?>]</li>
<li class="active">Db[<?php echo $agents;?>]</li>
</ol>
</section>
<br>

<!-- Main content -->
<section class="content">
<div class="row">
<!--<div class="col-md-6">  
<div class="box box-success">
<div class="box">    
<div class="box-body no-padding">
<div id="donutchart" style="width: 500px; height: 300px;"></div>
</div>
</div>
</div>
</div>
<div class="col-md-6">  
<div class="box box-success">
<div class="box">    
<div class="box-body no-padding">
<div id="donutchart2" style="width: 500px; height: 300px;"></div>
</div>
</div>
</div>
</div>-->
<div class="col-md-12">
<div class="box box-success">
<div class="box-header">
<h3 class="box-title">Distributor Performance [<?php echo $starts;?> - <?php echo $ends;?>]</h3>
</div>

<!-- /.box-header -->    
<form method='post' class="form-inline" action='dbsalesvalue.php?'>
<div class="form-group">
<td>From:<i class="fa fa-calendar-plus-o"></i><input type='text' class="form-control" id='inputField' name='starts' value='<?php echo $starts ?>' autocomplete='off'></td>
</div>
<div class="form-group">
To:<i class="fa fa-calendar-minus-o"></i><td><input type='text' class="form-control" id='inputField2' name='ends' value='<?php echo $ends ?>' autocomplete='off'></td>
</div>
<div class="btn-group">
<button type="submit" style="margin:5px;" class="btn btn-info">Generate-Report</button>
</form>
<button type="button"  style="margin:5px;" class="btn btn-primary" onclick="scopys(1)">Copy-Excel</button>

Search:<i class="fa fa-search"></i><td><input type='text' class="form-control" style="margin:5px;" id="myInput" placeholder="Type keyword to search" autocomplete='off' onkeyup="myFunction()"></td>
</div>              
<br>
<div class="box box-primary">    
<div class="box-body table-responsive">
<table id="example" class="table table-bordered table-hover ">
<thead>
<th class="not_mapped_style" style="text-align:center">Distributor</th>
<th class="text-center">Territory</th>
<th class="text-center">Target</th>
<th class="text-center">Order</th>
<th class="text-center">Primary</th>
<th class="text-center">%</th>
<th class="text-center">Deficit</th>
<th class="text-center">RD-Sales</th>
<th class="text-center">%</th>
<th class="text-center">Open-Stock</th>
<th class="text-center">Close-Stock</th>
<th class="text-center">Calls</th>
<th class="text-center">Discount</th>
<th class="text-center">%</th>
<th class="text-center">W-Days</th>
<th class="text-center">Admin-Cost</th>
<th class="text-center">DB-ROI</th>
<th colspan="3" class="text-center">Details-View</th>
</thead>
<tbody>

<?php

$sqlst="select magents,mterrys,tgvl,acvl,tgwt,acwt,odvl,odwt,emp,rdvl,rddisc,atwds,pcalls,dbcomi,strd,stpri,optstk,optpri,optrdv from (select distinct agent_names as magents,territory_names as mterrys,executive_names as emp from rc_invoices ".$flt." and dates>='".$starts."' and dates<='".$ends."' and chanell='GENERAL TRADE' union select distinct agent_names,territory_names,executive_names from rc_targets ".$flt." and dates>='".$starts."' and dates<='".
$ends."' union select distinct agent_names,territory_names,executive_names from rc_orders ".$flt." and dates>='".$starts."' and dates<='".
$ends."' and chanell='GENERAL TRADE' union select distinct agent_names,territory_names,executive_names from rd_saleinv ".$flt." and dates>='".$starts."' and dates<='".
$ends."' and chanell='GENERAL TRADE' union select distinct agent_names,territory_names,executive_names from rd_db_stocks ".$flt." and dates>='2020-09-01' and dates<='2020-09-31') as ags 

left join(select agent_names,territory_names,executive_names,sum(box_qty*box_price) as tgvl,sum(box_qty*packets_per_box*packet_weights/1000) as tgwt from rc_targets ".$flt." and dates>='".$starts."' and dates<='".$ends."' group by agent_names,territory_names,executive_names) as tgs on tgs.agent_names=magents and tgs.territory_names=mterrys and tgs.executive_names=emp

left join (select agent_names,territory_names,executive_names,sum(box_qty*box_price) as acvl,sum(box_qty*packets_per_box*packet_weights/1000) as acwt from rc_invoices "
.$flt." and dates>='".$starts."' and dates<='".$ends."' and chanell='GENERAL TRADE' group by agent_names,territory_names) as acs on acs.agent_names=magents and acs.territory_names=mterrys and acs.executive_names=emp

left join (select agent_names,territory_names,executive_names,sum(box_qty*box_price) as odvl,sum(box_qty*packets_per_box*packet_weights/1000) as odwt from rc_orders "
.$flt." and dates>='".$starts."' and dates<='".$ends."' and order_status<>'CANCELLED' and chanell='GENERAL TRADE' group by agent_names,territory_names) as ocs on ocs.agent_names=magents and ocs.territory_names=mterrys and ocs.executive_names=emp

left join (select agent_names,territory_names,executive_names,sum(pcs_qty*pcs_price) as rdvl,sum(rtdiscount_values+wsdiscount_values) as rddisc,count(distinct(invoice_number)) as atwds,sum(pcalls) as pcalls,sum((pcs_qty*pcs_price)/100*8) as dbcomi from rd_saleinv "
.$flt." and dates>='".$starts."' and dates<='".$ends."' and chanell='GENERAL TRADE' group by agent_names,territory_names) as rds on rds.agent_names=magents and rds.territory_names=mterrys and rds.executive_names=emp

left join (select agent_names,territory_names,executive_names,sum(pcs_qty*pcs_price+box_qty*box_price) as strd from rd_saleinv ".$flt." and dates>='2020-09-01' and dates<='".$ends."' and chanell='GENERAL TRADE' and agent_types='AGENCY' group by agent_names,territory_names) 
as strdd on strdd.agent_names=magents and strdd.territory_names=mterrys and strdd.executive_names=emp

left join (select agent_names,territory_names,executive_names,sum(box_qty*box_price) as stpri from rc_invoices ".$flt." and dates>='2020-09-01' and dates<='".$ends."' and chanell='GENERAL TRADE' and agent_types='AGENCY' group by agent_names,territory_names) 
as stprd on stprd.agent_names=magents and stprd.territory_names=mterrys and stprd.executive_names=emp

left join (select agent_names,territory_names,executive_names,sum(pcs_qty*pcs_price+box_qty*box_price) as optstk from rd_db_stocks ".$flt." and dates>='2020-09-01' and dates<='".$ends."' and chanell='GENERAL TRADE' and agent_types='AGENCY' group by agent_names,territory_names) 
as optks on optks.agent_names=magents and optks.territory_names=mterrys and optks.executive_names=emp

left join (select agent_names,territory_names,executive_names,sum(pcs_qty*pcs_price+box_qty*box_price) as optrdv from rd_saleinv ".$flt." and dates>='2020-09-01' and dates<'".$starts."' and chanell='GENERAL TRADE' and agent_types='AGENCY' group by agent_names,territory_names) 
as strddop on strddop.agent_names=magents and strddop.territory_names=mterrys and strddop.executive_names=emp

left join (select agent_names,territory_names,executive_names,sum(box_qty*box_price) as optpri from rc_invoices ".$flt." and dates>='2020-09-01' and dates<'".$starts."' and chanell='GENERAL TRADE' and agent_types='AGENCY' group by agent_names,territory_names) 
as stprdop on stprdop.agent_names=magents and stprdop.territory_names=mterrys and stprdop.executive_names=emp order by acvl/tgvl*100 desc
";
 
 
$tgv=0;
$acv=0;
$tgw=0;
$acw=0;
$odvl=0;
$rdvl=0;
$rddisc=0;
$pcalls=0;
$dbcomi=0;
$sttot=0;
$opttot=0;
$wdays=0;
$chanel='General Trade';

$qry=mysqli_query($conn,$sqlst);
while($rst=mysqli_fetch_row($qry)){
$tgv=$tgv+$rst[2];
$acv=$acv+$rst[3];
$tgw=$tgw+$rst[4];
$acw=$acw+$rst[5];
$odvl=$odvl+$rst[6];
$rdvl=$rdvl+$rst[9];
$rddisc=$rddisc+$rst[10];
$pcalls=$pcalls+$rst[12];
$dbcomi=$dbcomi+$rst[13];
$sttot=$sttot+$rst[15]+$rst[16]-$rst[14];
$opttot=$opttot+$rst[16]+$rst[17]-$rst[18];
$wdays=$wdays+$rst[11];

if($rst[2]==0){
$pcs=0;}
else{
$pcs=$rst[3]*100/$rst[2];}

if($rst[2]==0){
$rds=0;}
else{
$rds=$rst[9]*100/$rst[2];}
	
if($rst[4]==0){
$wpcs=0;}
else{
$wpcs=$rst[5]*100/$rst[4];}

$admincost=0;
$roi=0;
?> 
<tr>
<td><?php echo ucwords($rst[0]); ?></td>
<td><?php echo ucwords($rst[1]); ?></td>
<td align='center'><?php echo number_format($rst[2],0,'.',','); ?></td>
<td align='center'><?php echo number_format($rst[6],0,'.',','); ?></td>
<td align='center'><?php echo number_format($rst[3],0,'.',','); ?></td>
<td align='center' class="info text-danger"><?php echo number_format($pcs,0,'.',','); ?></td>
<td align='center'><?php echo number_format($rst[2]-$rst[3],0,'.',','); ?></td>
<td align='center'><?php echo number_format($rst[9],0,'.',','); ?></td>
<td align='center' class="info text-danger"><?php echo number_format($rds,0,'.',','); ?></td>
<td align='center'><?php echo number_format($rst[16]+$rst[17]-$rst[18],0,'.',','); ?></td>
<td align='center'><?php echo number_format($rst[15]+$rst[16]-$rst[14],0,'.',','); ?></td>
<td align='center'><?php echo number_format($rst[12],0,'.',','); ?></td>
<td align='center' class="p-3 mb-2 bg-warning text-white"><?php echo number_format($rst[10],0,'.',','); ?></td>
<td align='center'><?php echo number_format($rst[10]/$rst[9]*100,0,'.',','); ?></td>
<td align='center'><?php echo number_format($rst[11],0,'.',','); ?></td>
<td align='center'><?php echo number_format($admincost,0,'.',','); ?></td>
<td align='center'><?php echo number_format($roi,0,'.',','); ?></td>

<td align='center'>  
<a href='rangesales.php?agents=<?php echo $rst[0];?>&starts=<?php echo $starts ;?>&ends=<?php echo $ends;?>' input type="submit" name="view" class="btn btn-info btn-xs"><i class="fa fa-list"></i></i>Range</a>
</td>

<td align='center'>  
<a href='productsku.php?agents=<?php echo $rst[0];?>&starts=<?php echo $starts ;?>&ends=<?php echo $ends;?>' input type="submit" name="view" class="btn bg-maroon btn-xs"><i class="fa fa-list"></i></i>Items</a>
</td>

</tr>
<?php } ?>
<td class="success">Total</td><td class="success"></td><td class="success" align='center'><?php echo number_format($tgv,0);?><td class="success" align='center'><?php echo number_format($odvl,0);?><td class="success" align='center'><?php echo number_format($acv,0);?><td class="success" align='center'><?php echo number_format($acv/$tgv*100,0);?></td><td class="success" align='center'><?php echo number_format($tgv-$acv,0);?></td><td class="success" align='center'><?php echo number_format($rdvl,0);?></td><td class="success" align='center'><?php echo number_format($rdvl/$tgv*100,2);?></td><td class="success" align='center'><?php echo number_format($opttot,0);?></td><td class="success" align='center'><?php echo number_format($sttot,0);?></td><td class="success" align='center'><?php echo number_format($pcalls,0);?></td><td class="success" align='center'><?php echo number_format($rddisc,0);?></td><td class="success" align='center'><?php echo number_format($rddisc/$rdvl*100,0);?></td><td class="success" align='center'><?php echo number_format($wdays,0);?></td><td class="success" align='center'><?php echo number_format($admincost,0);?></td><td class="success" align='center'><?php echo number_format($roi,0);?></td>

<td align='center'>  
<a href='rangesales.php?chanels=<?php echo $chanel;?>&starts=<?php echo $starts ;?>&ends=<?php echo $ends;?>' input type="submit" name="view" class="btn btn-info btn-xs"><i class="fa fa-list"></i></i>Range</a>
</td>

<td align='center'>  
<a href='productsku.php?chanels=<?php echo $chanel;?>&starts=<?php echo $starts ;?>&ends=<?php echo $ends;?>' input type="submit" name="view" class="btn bg-maroon btn-xs"><i class="fa fa-list"></i></i>Items</a>
</td>
</tbody>
</table>  
</div>
</div>
</div>
</section>
</div>
<?php include_once('footer.php');?>

<script>
  $(function () {
    $('#example1').DataTable()
    $('#example2').DataTable({
      'paging'      : true,
      'lengthChange': false,
      'searching'   : false,
      'ordering'    : true,
      'info'        : true,
      'autoWidth'   : false,
    })
  })
  
function scopys(pr)
{
var dts=document.getElementById("example");

var sels=window.getSelection();
sels.removeAllRanges();
var ranges=document.createRange();
ranges.selectNodeContents(dts);
sels.addRange(ranges);
document.execCommand("copy");
swal('Coppied!','Open Excel Sheet Press CTRL+V','success');
sels.removeAllRanges();
} 

 //Date picker
    $('#datepicker').datepicker({
        format: 'yyyy/mm/dd',
      autoclose: true
    })
function myFunction() {
  // Declare variables 
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("example");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
}

google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChartt);
function drawChartt() {
var data = google.visualization.arrayToDataTable([
['regions', 'contribution'],
<?php
$sql = "SELECT distinct regions,sum(box_qty*box_price) FROM rc_invoices ".$flt." and chanell='General Trade' and dates between '".$starts."' and '".$ends."' group by regions";
$firee = mysqli_query($conn,$sql);
while ($resultt = mysqli_fetch_assoc($firee)) {
echo"['".$resultt['regions']."',".$resultt['sum(box_qty*box_price)']."],";
}
?>
]);
var options = {
title: 'Monthly Contribution',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}

google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChartp);
function drawChartp() {
var data = google.visualization.arrayToDataTable([
['Region', 'Sales Value'],
<?php
$sql = "SELECT distinct regions,sum(box_qty*box_price) FROM rc_invoices ".$flt." and chanell='General Trade' and dates between '2020-04-01' and '".$ends."' group by regions";
$firee = mysqli_query($conn,$sql);
while ($resultt = mysqli_fetch_assoc($firee)) {
echo"['".$resultt['regions']."',".$resultt['sum(box_qty*box_price)']."],";
}
?>
]);

var options = {
title: 'Financial Year Cont:',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart2'));
chart.draw(data, options);
}

</script>
</body>
</html>

