
<?php

session_start();
if($_SESSION['dbName']==""){
	header("location:../index.php");
}

print <<< HERE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">

<TITLE> Client Rebate Report </TITLE>
</HEAD>


HERE;


include("config.inc.php");
include('function.inc.php');

//Set Time Execution For the Report
//ini_set('max_execution_time', $config['ReportTimeExecution']);
set_time_limit(0);

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");


$querylog="SELECT print as printaccess from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}


if ($printaccess==0 or $printaccess=='')
echo'<BODY oncontextmenu="return false;">';
else
echo'<BODY>';


$querysetup=" select DecimalBase, DecimalBase1, DecimalBase2, Base1, Base2, report_color1, report_color2, Company_Name As CompanyName, ifNull(ClientSalesRMaskQty,2) as ClientSalesRMaskQty ".
			" from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultsetup)){
  extract($rows);
} 

$querylog=" select ifNull(FI_RepRestrictProject,0) As FI_RepRestrictProject, ifNull(FI_RepRestrictCostcenter,0) As FI_RepRestrictCostcenter, ".
		  " ifNull(FI_RepRestrictWarehouse,0) As FI_RepRestrictWarehouse, ifNull(FI_ShowCostPrice,0) As FI_ShowCostPrice ".
          " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."') ";
$resultlog=mysql_query($querylog) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_Grn,0) As Module_Grn, ifNull(Module_Delivery,0) As Module_Delivery, ".
			 " ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['dbLabel'].".loginstk on project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%') ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " and (loginstk.project_code is not null and loginstk.project_code != '') ".
			  " order by project.project_code";
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectexist  = mysql_num_rows($projectresult);

$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(ifnull(loginstk.costcent_code,costcent.costcent_code),'%') ".
			   " where user_account='".$_SESSION['useraccount']."' ".
			   " and (loginstk.costcent_code is not null and loginstk.costcent_code != '') ".
			   " order by costcent.costcent_code";
$costcentresult = mysql_query($querycostcent,$connection) or die(mysql_error());
$costcentexist  = mysql_num_rows($costcentresult);		

$querywh=" select distinct warehouse.warehouse_code, warehouse_name ".
         " from warehouse where warehouse_code in ( select warehouse_code from ".$_SESSION['dbLabel'].".loginstk ".
		 "                                          where user_account='".$_SESSION['useraccount']."' ".
		 "                                          and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '') ) ".
		 " order by warehouse.warehouse_code";
$resultwh = mysql_query($querywh,$connection) or die(mysql_error());
$whexist  = mysql_num_rows($resultwh);


$querygroup=" select distinct group_code,group_name ".
			" from grouping where group_code in (select group_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."') ".
			" order by group_code";
$resultgroup = mysql_query($querygroup,$connection) or die(mysql_error());
$groupexist  = mysql_num_rows($resultgroup);

$now=current_server_time($connection);
$dt=split(" ",$now[0]);
$printdate=split("-",$dt[0]);


/*
echo"
<TABLE CELLPADDING=6>
<THEAD>";
*/

print <<< HERE
<table width="100%" border="0" align="left" >
HERE;


echo "<thead><tr><td align='left'>";
	
$PageLayout='landscape';
ShowReportHeader('Client Rebate Report',$PageLayout, $connection);
	
echo"</td></tr></thead><tbody>";



$queryoptions = "Select Ledger_Name From Suppliers Where Ledger_Number = '".$fromsupplier."'";
$resultoptions = mysql_query($queryoptions,$connection) or die(mysql_error());
$rowoptions=mysql_fetch_row($resultoptions);
$fromsuppliername = $rowoptions[0];

$queryoptions = "Select Ledger_Name From Suppliers Where Ledger_Number = '".$tosupplier."'";
$resultoptions = mysql_query($queryoptions,$connection) or die(mysql_error());
$rowoptions=mysql_fetch_row($resultoptions);
$tosuppliername = $rowoptions[0];

if ($curr == 'currency1'){
   $curr='null';  
   $displaycur = '';
}   
else {
   $displaycur = $curr;
   $curr="'".$curr."'";
}   

$subproj 	 = ereg_replace('-','%',$subproj);
$subcostcent = ereg_replace('-','%',$subcostcent);

$SelectedOptions = "Filter by: <br>";
if ($fromdate != '')      $SelectedOptions .= "-> Date From: ". $fromdate . "  To: ". $todate ."<br>";	
if ($displaycur != '')    $SelectedOptions .= "-> Currency: ". $displaycur ."<br>";	
if ($fromitem != '')      $SelectedOptions .= "-> Item From: ". $fromitem . "  To: ". $toitem ."<br>";
if ($fromgroup != '')     $SelectedOptions .= "-> Group From: ". $fromgroup . "  To: ". $togroup ."<br>";
if ($fromsubgroup != '')  $SelectedOptions .= "-> SubGroup From: ". $fromsubgroup . "  To: ". $tosubgroup ."<br>";
if ($fromproject != '')   $SelectedOptions .= "-> Project From: ". $fromproject . "<br>";
if ($fromcostcent != '')  $SelectedOptions .= "-> Costcent From: ". $fromcostcent . "<br>";
if ($fromclient != '')    $SelectedOptions .= "-> Client From: ". $fromclient . "  To: ". $toclient ."<br>";
if ($fromsupplier != '')  $SelectedOptions .= "-> Supplier From: ". $fromsupplier . " (". $fromsuppliername .") To: ". $tosupplier . " (". $tosuppliername .")<br>";
if ($fromsalesman != '')  $SelectedOptions .= "-> Salesman From: ". $fromsalesman . "  To: ". $tosalesman ."<br>";
if ($fromwarehouse != '') $SelectedOptions .= "-> Warehouse From: ". $fromwarehouse . "<br>";
if ($fromarea != '') 	  $SelectedOptions .= "-> Area From: ". $fromarea . "<br>";
if ($cltrating != '')	  $SelectedOptions .= "-> Client Rating: ". $cltrating . "<br>";
if ($subproj != '') 	  $SelectedOptions .= "-> Project Include: ". $subproj . "<br>";
if ($subcostcent != '')	  $SelectedOptions .= "-> Costcent Include: ". $subcostcent . "<br>";


  
if (!empty($fromdate))
   $fromdate = explodeword($fromdate);
if (!empty($todate))
   $todate = explodeword($todate);  
   
$fromitem      = GetSQLValueString($fromitem, 'text');
$toitem        = GetSQLValueString($toitem, 'text');
$fromproject   = GetSQLValueString($fromproject, 'text');
$fromcostcent  = GetSQLValueString($fromcostcent, 'text');
$fromgroup     = GetSQLValueString($fromgroup, 'text');
$togroup       = GetSQLValueString($togroup, 'text');
$fromsubgroup  = GetSQLValueString($fromsubgroup, 'text');
$tosubgroup    = GetSQLValueString($tosubgroup, 'text');
$fromwarehouse = GetSQLValueString($fromwarehouse, 'text');
$fromarea      = GetSQLValueString($fromarea, 'text');
$fromclient    = GetSQLValueString($fromclient, 'text');
$toclient      = GetSQLValueString($toclient, 'text');
$fromsupplier  = GetSQLValueString($fromsupplier, 'text');
$tosupplier    = GetSQLValueString($tosupplier, 'text');
$fromsalesman  = GetSQLValueString($fromsalesman, 'text');
$tosalesman    = GetSQLValueString($tosalesman, 'text');
$fromdate  	   = GetSQLValueString($fromdate, 'date');
$todate        = GetSQLValueString($todate, 'date');     
$subproj 	   = GetSQLValueString($subproj, 'text');
$subcostcent   = GetSQLValueString($subcostcent, 'text');        
$cltrating     = GetSQLValueString($cltrating, 'text');

if(empty($showrebatedt))    $showrebatedt = 0;
if(empty($showrebatesubdt)) $showrebatesubdt = 0;
if(empty($activeclt))  		$activeclt = 1;
if(empty($activeitem)) 		$activeitem = 1;

		
print <<<HERE



<tr><td><table class="report-master" width="100%" border="0" align="center" style='table-layout:fixed'>
<col width=100>
<tr><td>&nbsp;</td>
  <td  valign='top' width=100%><b>$SelectedOptions</b></td>
</tr>
<tr>
   <td width='100%' colspan='2'> <hr width='100%' color='black' size='1'> </td>
</tr>
</table></td></tr>
HERE;


echo "<tr><td><table  border='0' align='left' class='report-master' style='table-layout:fixed' cellpadding='0' cellspacing='0'>
	  <col width=100>
      <col width=200>
      <col width=100>
	  <col width=60>
      <col width=120>
      <col width=70>
      <col width=100>
	  <col width=100>
	  <col width=100>
	  <col width=100>
	  <col width=100> ";
	  

echo"<thead><tr >";

echo"	<th align='left'>Item Code</th>
		<th align='left'>Description</th>
		<th align='center'>Qty.Sold</th>
		<th align='center'>Cur.</th>
		<th align='center'>Sell. Amount</th>
		<th align='center'>Rebate %</th>
		<th align='center'>Rebate Amt</th>
		<th align='center'>Amount</th>
		<th align='center'>Rnd Rebate</th>
		<th align='center'>Value</th>
		<th align='center'>Wallet</th>";
echo"</tr>";
echo"<tr>
		<td colspan='11'><hr width='100%' color='black' size='1'></td>
	</tr>
	<thead>";

 

//Sales Query
$querysales = '';


if ($showrebatedt != 1) {
	$querysales = $querysales.
				" Select ClientCode, ClientName, Null as ItemCode, Null as ItemDescription, Null as ItemWeight, Null as Item_UnitSalesDesc, Null as Item_RebateBy, ".
				" Sum(QtyNetSold), Currency, Sum(SellAmount), Null as SellingPrice, Null as RebatePer, Sum(Rebate), Sum(Rebate*QtyNetSold) As RebateAmount, ".
				" Sum(ifNull(Floor((Rebate*QtyNetSold)/(if(Item_RebateBy=1, ifNull(SellingPrice,0), ifNull(SellAmount,0)))),0)) As RoundRebate, ".
				" Sum(ifNull(Floor((Rebate*QtyNetSold)/(if(Item_RebateBy=1, ifNull(SellingPrice,0), ifNull(SellAmount,0)))),0)*(if(Item_RebateBy=1, ifNull(SellingPrice,0), ifNull(SellAmount,0)))) As Value, ".
				" Sum(((Rebate*QtyNetSold) - ifNull((Floor((Rebate*QtyNetSold)/(if(Item_RebateBy=1, ifNull(SellingPrice,0), ifNull(SellAmount,0))))*(if(Item_RebateBy=1, ifNull(SellingPrice,0), ifNull(SellAmount,0)))),0))) As Wallet ".
				" From ( ";
}

$querysales = $querysales.
				" Select ClientCode, ClientName, ItemCode, ItemDescription, ItemWeight, Item_UnitSalesDesc, Item_RebateBy, QtyNetSold, Currency, ".
				" SellAmount, SellingPrice, RebatePer, Rebate, (Rebate*QtyNetSold) As RebateAmount, ".
				" ifNull(Floor((Rebate*QtyNetSold)/(if(Item_RebateBy=1, ifNull(SellingPrice,0), ifNull(SellAmount,0)))),0) As RoundRebate, ".
				" ifNull(Floor((Rebate*QtyNetSold)/(if(Item_RebateBy=1, ifNull(SellingPrice,0), ifNull(SellAmount,0)))),0)*(if(Item_RebateBy=1, ifNull(SellingPrice,0), ifNull(SellAmount,0))) As Value, ".
				" ((Rebate*QtyNetSold) - ifNull((Floor((Rebate*QtyNetSold)/(if(Item_RebateBy=1, ifNull(SellingPrice,0), ifNull(SellAmount,0))))*(if(Item_RebateBy=1, ifNull(SellingPrice,0), ifNull(SellAmount,0)))),0)) As Wallet ".
				" From ( ";
				
$querysales = $querysales.
				" Select ClientCode, ClientName, ItemCode, ItemDescription, ItemWeight, Item_UnitSalesDesc, Item_RebateBy, QtyNetSold, Currency, SellAmount, SellingPrice, ".
				" ifNull(ItemRebate_Per,0) As RebatePer, if(Item_RebateBy=1, (ifNull(ItemRebate_Per,0)*ifNull(SellingPrice,0)/100), (ifNull(ItemRebate_Per,0)*ifNull(SellAmount,0)/100)) As Rebate   ".
				" From ( ";

if($Module_Delivery == 1 ) {
	$querysales = $querysales.
							" Select Sales.Client_Code As ClientCode, Clients.Ledger_Name As ClientName, SalesDt.Item_Code As ItemCode, Items.Item_Description As ItemDescription, ".
							" Items.Item_Weight as ItemWeight, Items.Item_UnitSalesDesc, ifNull(Items.Item_RebateBy, 1) As Item_RebateBy, ".
							" Sum(if(SalesDt.Journal_Type = 'SI',SalesDt.SaleDt_Quantity,(-1)*SalesDt.SaleDt_Quantity)) As QtyNetSold, ".
							" if(upper($curr)='".$Base1."', '".$Base1."', if(upper($curr)='".$Base2."', '".$Base2."', Sales.Currency_Code))  As Currency, ".
							" Sum(if(ifNull(SalesDt.SaleDt_Price,0)=0, 0,  ".
							" ifNull( ((if(upper($curr)='".$Base1."',SalesDt.SaleDt_PriceBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_PriceBase2, SalesDt.SaleDt_Price)) - ".
							"          (ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_PriceBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_PriceBase2, SalesDt.SaleDt_Price)),0) * ifNull(SalesDt.SaleDt_discountper, 0)/100))*if(SalesDt.Journal_Type = 'SI',SalesDt.SaleDt_Quantity,(-1)*SalesDt.SaleDt_Quantity) - ".
							"         ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_DiscountBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_DiscountBase2,SalesDt.SaleDt_DiscountAmount)),0) + ".
							"         ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_TransportBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_TransportBase2,SalesDt.SaleDt_TransportAmount)),0) + ".
							"		  ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_BonusBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_BonusBase2,SalesDt.SaleDt_BonusAmount)),0)) ,0)))  As SellAmount, ".
							" if(upper($curr)='".$Base1."', ifNull(Item_SellingPrice1Base1,0), if(upper($curr)='".$Base2."', ifNull(Item_SellingPrice1Base2,0), ifNull(Item_SellingPrice1,0)))  As SellingPrice ";


	$querysales = $querysales.
							" From SalesDt  ".
							" Inner Join Sales on SalesDt.Sale_ID = Sales.Sale_ID ".
							" Inner Join Items on SalesDt.Item_Code = Items.Item_Code ".
							" Inner Join Clients on Clients.Ledger_Number = Sales.Client_Code ";
						  
	if ($projectexist >	0 && $FI_RepRestrictProject == 1) {
		$querysales= $querysales." Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
								" 			  where loginstk.user_account='".$_SESSION['useraccount']."' ".
								"              and (project_code is not null and project_code != '') ".
								"			 ) Q1 on SalesDt.project_code like concat(Q1.project_code,'%')   ";
	}							
							 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1){
		$querysales= $querysales." Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
								"			  where loginstk.user_account='".$_SESSION['useraccount']."' ".
								"              and (costcent_code is not null and costcent_code != '') ".
								"			 ) Q2 on SalesDt.Costcenter_code like concat(Q2.costcent_code,'%') ";							 
	}

	$querysales= $querysales." Where SalesDt.Journal_Type in ('SI','SR') ".
							" And (Sales.Sale_Reference Is Not Null And Sales.Sale_Reference != '')  ".
							" And Date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(Sales.Sale_Date,'%Y-%m-%d'))  ".
							" And SalesDt.item_code between ifNull(".$fromitem.",SalesDt.item_code) and ifNull(". $toitem.",SalesDt.item_code) ".
							" And ifNull(Items.group_code,'-1') between ifNull(". $fromgroup .",ifNull(Items.group_code,'-1')) and ifNull(". $togroup.",ifNull(Items.group_code,'-1'))  ".
							" And ifNull(Items.SubGroup_Code,'-1') between ifNull(". $fromsubgroup .",ifNull(Items.SubGroup_Code,'-1')) and ifNull(". $tosubgroup.",ifNull(Items.SubGroup_Code,'-1'))  ".
							" And Sales.Client_Code between ifNull(".$fromclient.",Sales.Client_Code) and ifNull(". $toclient.",Sales.Client_Code) ".
							" And ifNull(Sales.Salesman_Code,'-1') between ifNull(".$fromsalesman.",ifNull(Sales.Salesman_Code,'-1')) and ifNull(". $tosalesman.",ifNull(Sales.Salesman_Code,'-1')) ".
							" And ifNull(Items.Ledger_Number,'-1') between ifNull(".$fromsupplier.", ifNull(Items.Ledger_Number,'-1')) and ifNull(". $tosupplier.", ifNull(Items.Ledger_Number,'-1')) ".
							" And ifNull(SalesDt.project_code,'-1')     Like Concat( ifNull(".$fromproject.",ifNull(SalesDt.project_code,'-1')),'%')  ".
							" And ifNull(SalesDt.Costcenter_code,'-1')  Like Concat(ifNull(".$fromcostcent.",ifNull(SalesDt.Costcenter_code,'-1')),'%')  ".
							" And ifNull(SalesDt.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(SalesDt.warehouse_code,'-1')),'%')  ".
							" And ifNull(Clients.area_code,'-1') = ifNull(". $fromarea .",ifNull(Clients.area_code,'-1'))  ".
							" And ifNull(Clients.Client_Rating,'-1') = ifNull(". $cltrating .",ifNull(Clients.Client_Rating,'-1'))  ".
							" And (($activeclt=1 and ifNull(Clients.Client_deactivate,0) = 0) or ($activeclt=2 and ifNull(Clients.Client_deactivate,0) = 1) or ($activeclt=3 and 1 = 1)) ".
							" And (($activeitem=1 and ifNull(Items.Item_Active,0) = 1) or ($activeitem=2 and ifNull(Items.Item_Active,0) = 0) or ($activeitem=3 and 1 = 1)) ";
						  
	if ($subproj != 'Null')
		$querysales= $querysales." And ifNull(SalesDt.project_code,'-1')  Like ".$subproj;  
	if ($subcostcent != 'Null')
		$querysales= $querysales." And ifNull(SalesDt.Costcenter_code,'-1')  Like ".$subcostcent;  						  
  
	if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
		$querysales= $querysales." And SalesDt.warehouse_code In (select distinct warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  
	if ($groupexist > 0)
		$querysales= $querysales." And Items.group_code In (select distinct group_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  

	$querysales= $querysales." Group By ClientCode, ItemCode, Currency ";
} else {
 	$querysales = $querysales.
							" Select Deliveries.Client_Code As ClientCode, Clients.Ledger_Name As ClientName, DeliveryDt.Item_Code As ItemCode, Items.Item_Description As ItemDescription, ".
							" Items.Item_Weight as ItemWeight, Items.Item_UnitSalesDesc, ifNull(Items.Item_RebateBy, 1) As Item_RebateBy, ".
							" Sum(if(DeliveryDt.Journal_Type = 'DI',DeliveryDt.DeliveryDt_Quantity, (-1)*DeliveryDt.DeliveryDt_Quantity)) As QtyNetSold, ".
							" if(upper($curr)='".$Base1."', '".$Base1."', if(upper($curr)='".$Base2."', '".$Base2."', Deliveries.Currency_Code))  As Currency, ".
							" Sum(if(ifNull(DeliveryDt.DeliveryDt_Price,0)=0, 0,  ".
							" ifNull( ((if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_PriceBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_PriceBase2, DeliveryDt.DeliveryDt_Price)) - ".
							"         (ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_PriceBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_PriceBase2, DeliveryDt.DeliveryDt_Price)),0) * ifNull(DeliveryDt.DeliveryDt_discountper, 0)/100))*if(DeliveryDt.Journal_Type = 'DI',DeliveryDt.DeliveryDt_Quantity, (-1)*DeliveryDt.DeliveryDt_Quantity) - ".
							"         ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_DiscountBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_DiscountBase2,DeliveryDt.DeliveryDt_DiscountAmount)),0) + ".
							"         ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_TransportAmountBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_TransportAmountBase2,DeliveryDt.DeliveryDt_TransportAmount)),0) + ".
							"		  ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_BonusBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_BonusBase2,DeliveryDt.DeliveryDt_BonusAmount)),0)) ,0)))  As SellAmount,  ".
							" if(upper($curr)='".$Base1."', ifNull(Item_SellingPrice1Base1,0), if(upper($curr)='".$Base2."', ifNull(Item_SellingPrice1Base2,0), ifNull(Item_SellingPrice1,0)))  As SellingPrice ";

	   
	$querysales = $querysales." From DeliveryDt  ".
							" Inner Join Deliveries on DeliveryDt.Delivery_ID = Deliveries.Delivery_ID ".
							" Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ".
							" Inner Join Clients on Clients.Ledger_Number = Deliveries.Client_Code ";
				
						  
	if ($projectexist >	0 && $FI_RepRestrictProject == 1) {
		$querysales= $querysales." Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
								 " 			   	where loginstk.user_account='".$_SESSION['useraccount']."' ".
								 "             	and (project_code is not null and project_code != '') ".
								 "			 ) Q1 on DeliveryDt.project_code like concat(Q1.project_code,'%')  ";
	}						 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1){
		$querysales = $querysales." Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
								  "			     where loginstk.user_account='".$_SESSION['useraccount']."' ".
								  "              and (costcent_code is not null and costcent_code != '') ".
								  "			 ) Q2 on DeliveryDt.Costcent_Code like concat(Q2.costcent_code,'%')  ";							 
	}


	$querysales= $querysales.						  
							" Where DeliveryDt.Journal_Type in ('DI','DR') ".
							" And (Deliveries.Delivery_Reference Is Not Null And Deliveries.Delivery_Reference != '')  ".
							" And Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ".
							" And DeliveryDt.item_code between ifNull(".$fromitem.",DeliveryDt.item_code) and ifNull(". $toitem.",DeliveryDt.item_code) ".
							" And ifNull(Items.group_code,'-1') between ifNull(". $fromgroup .",ifNull(Items.group_code,'-1')) and ifNull(". $togroup.",ifNull(Items.group_code,'-1'))  ".
							" And ifNull(Items.SubGroup_Code,'-1') between ifNull(". $fromsubgroup .",ifNull(Items.SubGroup_Code,'-1')) and ifNull(". $tosubgroup.",ifNull(Items.SubGroup_Code,'-1'))  ".
							" And Deliveries.Client_Code between ifNull(".$fromclient.",Deliveries.Client_Code) and ifNull(". $toclient.",Deliveries.Client_Code) ".
							" And ifNull(Deliveries.Salesman_Code,'-1') between ifNull(".$fromsalesman.",ifNull(Deliveries.Salesman_Code,'-1')) and ifNull(". $tosalesman.",ifNull(Deliveries.Salesman_Code,'-1')) ".
							" And ifNull(Items.Ledger_Number,'-1') between ifNull(".$fromsupplier.", ifNull(Items.Ledger_Number,'-1')) and ifNull(". $tosupplier.", ifNull(Items.Ledger_Number,'-1')) ".
							" And ifNull(DeliveryDt.project_code,'-1')   Like Concat(ifNull(".$fromproject.",ifNull(DeliveryDt.project_code,'-1')),'%')  ".
							" And ifNull(DeliveryDt.Costcent_Code,'-1')  Like Concat(ifNull(".$fromcostcent.",ifNull(DeliveryDt.Costcent_Code,'-1')),'%')  ".
							" And ifNull(DeliveryDt.warehouse_code,'-1') Like Concat(ifNull(". $fromwarehouse .",ifNull(DeliveryDt.warehouse_code,'-1')),'%')  ".
							" And ifNull(Clients.area_code,'-1') = ifNull(". $fromarea .",ifNull(Clients.area_code,'-1'))  ".
							" And ifNull(Clients.Client_Rating,'-1') = ifNull(". $cltrating .",ifNull(Clients.Client_Rating,'-1'))  ".
							" And (($activeclt=1 and ifNull(Clients.Client_deactivate,0) = 0) or ($activeclt=2 and ifNull(Clients.Client_deactivate,0) = 1) or ($activeclt=3 and 1 = 1)) ".
							" And (($activeitem=1 and ifNull(Items.Item_Active,0) = 1) or ($activeitem=2 and ifNull(Items.Item_Active,0) = 0) or ($activeitem=3 and 1 = 1)) ";
						  
	if ($subproj != 'Null')
		$querysales= $querysales." And ifNull(DeliveryDt.project_code,'-1')  Like ".$subproj; 
	if ($subcostcent != 'Null')
		$querysales= $querysales." And ifNull(DeliveryDt.Costcent_Code,'-1')  Like ".$subcostcent;  

	if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
		$querysales= $querysales." And DeliveryDt.warehouse_code In (select distinct warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  
	if ($groupexist > 0)
		$querysales= $querysales." And Items.group_code In (select distinct group_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  
	  
	$querysales= $querysales." Group By ClientCode, ItemCode, Currency ";
}
$querysales= $querysales." ) Q1 ";
$querysales= $querysales." Left Join ItemsRebate on ItemsRebate.Item_Code = Q1.ItemCode ".
						 " Where ((Item_RebateBy=1 and QtyNetSold Between ifNull(ItemRebate_RangeFrom, QtyNetSold) and ifNull(ItemRebate_RangeTo, QtyNetSold)) or ".
						 "        (Item_RebateBy=2 and SellAmount Between ifNull(ItemRebate_RangeFrom, SellAmount) and ifNull(ItemRebate_RangeTo, SellAmount))) ";


$querysales= $querysales." ) Q2 ";

if ($showrebatedt != 1) {
	$querysales= $querysales." ) Q3 ";
	$querysales= $querysales." Group By ClientCode, Currency ";
}
$querysales= $querysales." Order by ClientCode, ItemCode ";
	

//echo $querysales; exit;




$ArrayTotalByReport   = Array();
$ArrayTotalByMaster   = Array();

$MasterByCode = '';
$MasterByName = '';


$col=0;
$result=mysql_query($querysales,$connection) or die(mysql_error());
while($rows=mysql_fetch_row($result)){
	if($showrebatesubdt==1){
		$color = "style='background-color:".$report_color1."'";
		$color1 = "style='background-color:".$report_color2."'";
	}else{
		if($col%2==0){
			$color = "style='background-color:".$report_color1."'";
		}else{
			$color = "style='background-color:".$report_color2."'";
		}
	}
	
	
    
    
    // Master By Options Names and Totals
	if ($showrebatedt == 1 && ($MasterByCode != $rows[0] && $MasterByCode != '') ) {
		    
		echo "<tr>";
		echo " <td>&nbsp;</td>  <td colspan='10'><hr width='100%' color='grey' size='1'></td>";
		echo "</tr>";
			
		$StyleClass  = 'totals';
		$TotalsLabel = 'Total by Client';
		DisplayTotals($ArrayTotalByMaster, $DecimalBase, $ClientSalesRMaskQty, $TotalsLabel, $StyleClass);

	}
		
		
	if ($showrebatedt == 1 && ($MasterByCode == '' || $MasterByCode != $rows[0])) { 	
		echo "<tr class='group' >";
		echo "   <td align='left' valign='top' style='font-weight:bold;'>". $rows[0] ."</td>";
		echo "   <td align='left' valign='top' style='font-weight:bold;' colspan='10'>". $rows[1] ."</td>";
		echo "</tr>"; 
		
		$MasterByCode = $rows[0];
		$MasterByName = $rows[1];
		
		unset($ArrayTotalByMaster);
		
	}
	
	
	 
	
	if ($showrebatedt == 1) {
		echo "<tr class='subgroup' $color>";
		if($showrebatesubdt == 1){
			echo "	<td align='left' valign='top'  >". $rows[2] ."</td>";
			echo "	<td align='left' valign='top'  >". $rows[3] ."</td>";
		}else{
			echo "	<td align='left' valign='top'  style='border-right:1px solid black'>". $rows[2] ."</td>";
			echo "	<td align='left' valign='top'  style='border-right:1px solid black; padding-left:2px'>". $rows[3] ."</td>";
		}
	} 
	else {
		echo "<tr class='group' $color>";
		echo "	<td align='left' valign='top' style='border-right:1px solid black'>". $rows[0] ."</td>";
		echo "	<td align='left' valign='top' style='border-right:1px solid black; padding-left:2px'>". $rows[1] ."</td>";
	}
	
	if($showrebatesubdt == 1){
		echo "	<td align='right'  valign='top' >". number_format($rows[7], $ClientSalesRMaskQty) ."</td>";
		echo "	<td align='center' valign='top' >". $rows[8] ."</td>";
		echo "	<td align='right' valign='top' >". format_currency($rows[9], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". number_format($rows[11], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". format_currency($rows[12], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". format_currency($rows[13], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". format_currency($rows[14], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". format_currency($rows[15], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' >". format_currency($rows[16], $DecimalBase) ."</td>";
	}else{
		echo "	<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px'>". number_format($rows[7], $ClientSalesRMaskQty) ."</td>";
		echo "	<td align='center' valign='top' style='border-right:1px solid black'>". $rows[8] ."</td>";
		echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px'>". format_currency($rows[9], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px'>". number_format($rows[11], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px'>". format_currency($rows[12], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px'>". format_currency($rows[13], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px'>". format_currency($rows[14], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px'>". format_currency($rows[15], $DecimalBase) ."</td>";
		echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px'>". format_currency($rows[16], $DecimalBase) ."</td>";

	}

	echo "</tr>";
	
	
	//Show Related Invoices For Each Client And Item
	if ($showrebatesubdt == 1 && $showrebatedt == 1) {
	
		$sub_query = " Select SaleReference, SaleDate, QtyNetSold, Currency, SellAmount ".
					 " From ( ";

		if($Module_Delivery == 1 ) {
			$sub_query = $sub_query." Select Sales.Sale_Reference As SaleReference, date_format(Sales.Sale_Date,'%d/%m/%Y') As SaleDate, ".
									" if(SalesDt.Journal_Type = 'SI',SalesDt.SaleDt_Quantity,(-1)*SalesDt.SaleDt_Quantity) As QtyNetSold, ".
									" if(upper($curr)='".$Base1."', '".$Base1."', if(upper($curr)='".$Base2."', '".$Base2."', Sales.Currency_Code)) As Currency, ".
									" if(ifNull(SalesDt.SaleDt_Price,0)=0, 0,  ".
									" ifNull( ((if(upper($curr)='".$Base1."',SalesDt.SaleDt_PriceBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_PriceBase2, SalesDt.SaleDt_Price)) - ".
									"          (ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_PriceBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_PriceBase2, SalesDt.SaleDt_Price)),0) * ifNull(SalesDt.SaleDt_discountper, 0)/100))*if(SalesDt.Journal_Type = 'SI',SalesDt.SaleDt_Quantity,(-1)*SalesDt.SaleDt_Quantity) - ".
									"         ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_DiscountBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_DiscountBase2,SalesDt.SaleDt_DiscountAmount)),0) + ".
									"         ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_TransportBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_TransportBase2,SalesDt.SaleDt_TransportAmount)),0) + ".
									"		  ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_BonusBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_BonusBase2,SalesDt.SaleDt_BonusAmount)),0)) ,0))  As SellAmount ".
									" From SalesDt  ".
									" Inner Join Sales on SalesDt.Sale_ID = Sales.Sale_ID ";
								  
			if ($projectexist >	0 && $FI_RepRestrictProject == 1) {
				$sub_query = $sub_query." Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
										" 			  where loginstk.user_account='".$_SESSION['useraccount']."' ".
										"              and (project_code is not null and project_code != '') ".
										"			 ) Q1 on SalesDt.project_code like concat(Q1.project_code,'%')   ";
			}							
									 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1){
				$sub_query = $sub_query." Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
										"			  where loginstk.user_account='".$_SESSION['useraccount']."' ".
										"              and (costcent_code is not null and costcent_code != '') ".
										"			 ) Q2 on SalesDt.Costcenter_code like concat(Q2.costcent_code,'%') ";							 
			}

			$sub_query = $sub_query." Where SalesDt.Journal_Type in ('SI','SR') ".
									" And (Sales.Sale_Reference Is Not Null And Sales.Sale_Reference != '')  ".
									" And SalesDt.Item_Code = '".$rows[2]."' ".
									" And Sales.Client_Code = '".$rows[0]."' ";
									
			if ($subproj != 'Null')
				$sub_query = $sub_query." And ifNull(SalesDt.project_code,'-1')  Like ".$subproj;  
			if ($subcostcent != 'Null')
				$sub_query = $sub_query." And ifNull(SalesDt.Costcenter_code,'-1')  Like ".$subcostcent;  						  
		  
			if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
				$sub_query = $sub_query." And SalesDt.warehouse_code In (select distinct warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  
			if ($groupexist > 0)
				$sub_query = $sub_query." And Items.group_code In (select distinct group_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  

		} else {
			$sub_query = $sub_query." Select Deliveries.Delivery_Reference As SaleReference, date_format(Deliveries.Delivery_Date,'%d/%m/%Y') As SaleDate, ".
									" if(DeliveryDt.Journal_Type = 'DI',DeliveryDt.DeliveryDt_Quantity, (-1)*DeliveryDt.DeliveryDt_Quantity) As QtyNetSold, ".
									" if(upper($curr)='".$Base1."', '".$Base1."', if(upper($curr)='".$Base2."', '".$Base2."', Deliveries.Currency_Code)) As Currency, ".
									" if(ifNull(DeliveryDt.DeliveryDt_Price,0)=0, 0,  ".
									" ifNull( ((if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_PriceBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_PriceBase2, DeliveryDt.DeliveryDt_Price)) - ".
									"         (ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_PriceBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_PriceBase2, DeliveryDt.DeliveryDt_Price)),0) * ifNull(DeliveryDt.DeliveryDt_discountper, 0)/100))*if(DeliveryDt.Journal_Type = 'DI',DeliveryDt.DeliveryDt_Quantity, (-1)*DeliveryDt.DeliveryDt_Quantity) - ".
									"         ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_DiscountBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_DiscountBase2,DeliveryDt.DeliveryDt_DiscountAmount)),0) + ".
									"         ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_TransportAmountBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_TransportAmountBase2,DeliveryDt.DeliveryDt_TransportAmount)),0) + ".
									"		  ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_BonusBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_BonusBase2,DeliveryDt.DeliveryDt_BonusAmount)),0)) ,0)) As SellAmount  ".
									" From DeliveryDt  ".
									" Inner Join Deliveries on DeliveryDt.Delivery_ID = Deliveries.Delivery_ID ";
						
								  
			if ($projectexist >	0 && $FI_RepRestrictProject == 1) {
				$sub_query = $sub_query." Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
										" 			   	where loginstk.user_account='".$_SESSION['useraccount']."' ".
										"             	and (project_code is not null and project_code != '') ".
										"			 ) Q1 on DeliveryDt.project_code like concat(Q1.project_code,'%')  ";
			}						 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1){
				$sub_query = $sub_query." Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
										"			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
										"              and (costcent_code is not null and costcent_code != '') ".
										"			 ) Q2 on DeliveryDt.Costcent_Code like concat(Q2.costcent_code,'%')  ";							 
			}


			$sub_query = $sub_query." Where DeliveryDt.Journal_Type in ('DI','DR') ".
									" And (Deliveries.Delivery_Reference Is Not Null And Deliveries.Delivery_Reference != '')  ".
									" And DeliveryDt.Item_Code = '".$rows[2]."' ".
									" And Deliveries.Client_Code = '".$rows[0]."' ";
									
			if ($subproj != 'Null')
				$sub_query = $sub_query." And ifNull(DeliveryDt.project_code,'-1')  Like ".$subproj; 
			if ($subcostcent != 'Null')
				$sub_query = $sub_query." And ifNull(DeliveryDt.Costcent_Code,'-1')  Like ".$subcostcent;  

			if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
				$sub_query = $sub_query." And DeliveryDt.warehouse_code In (select distinct warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  
			if ($groupexist > 0)
				$sub_query = $sub_query." And Items.group_code In (select distinct group_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  
			  
		}
		$sub_query = $sub_query." ) Q1 ";
	
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
		$sub_totalrows = mysql_num_rows($sub_result);
		
		if ($sub_totalrows > 0) {
			echo "<tr $color1>";
			echo " 	<td colspan='11'><table  border='0' align='left' class='report-master' style='table-layout:fixed' cellpadding='0' cellspacing='0'>
					<col width=30>
					<col width=80>
					<col width=80>
					<col width=80>
					<col width=60>
					<col width=120>";
			
			while($sub_rows=mysql_fetch_row($sub_result)){
				echo "<tr class='subgroup'>";
				echo "	<td align='left' valign='top' >&nbsp;</td>";
				echo "	<td align='left' valign='top' style='border-right:1px solid black'>". $sub_rows[0] ."</td>";
				echo "	<td align='left' valign='top' style='border-right:1px solid black; padding-left:2px'>". $sub_rows[1] ."</td>";
				echo "	<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px'>". number_format($sub_rows[2], $ClientSalesRMaskQty) ."</td>";
				echo "	<td align='center' valign='top' style='border-right:1px solid black; padding-right:2px'>". $sub_rows[3] ."</td>";
				echo "	<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px'>". format_currency($sub_rows[4], $DecimalBase) ."</td>";
				echo "</tr>";
			}
			
			echo "</table>";
			echo "</td></tr>";
		}	
	}
		
		
	$ArrayTotalByMaster['SoldQty']      = $ArrayTotalByMaster['SoldQty']     + $rows[7];
	$ArrayTotalByMaster['SellAmt']      = $ArrayTotalByMaster['SellAmt']     + $rows[9];
	$ArrayTotalByMaster['RebateAmt']    = $ArrayTotalByMaster['RebateAmt']   + $rows[12];
	$ArrayTotalByMaster['Amount']       = $ArrayTotalByMaster['Amount']      + $rows[13];
	$ArrayTotalByMaster['RndRebate']    = $ArrayTotalByMaster['RndRebate']   + $rows[14];
	$ArrayTotalByMaster['Value']        = $ArrayTotalByMaster['Value']       + $rows[15];
	$ArrayTotalByMaster['Wallet']       = $ArrayTotalByMaster['Wallet']      + $rows[16];
	
	$ArrayTotalByReport['SoldQty']      = $ArrayTotalByReport['SoldQty']     + $rows[7];
	$ArrayTotalByReport['SellAmt']      = $ArrayTotalByReport['SellAmt']     + $rows[9];
	$ArrayTotalByReport['RebateAmt']    = $ArrayTotalByReport['RebateAmt']   + $rows[12];
	$ArrayTotalByReport['Amount']       = $ArrayTotalByReport['Amount']      + $rows[13];
	$ArrayTotalByReport['RndRebate']    = $ArrayTotalByReport['RndRebate']   + $rows[14];
	$ArrayTotalByReport['Value']        = $ArrayTotalByReport['Value']       + $rows[15];
	$ArrayTotalByReport['Wallet']       = $ArrayTotalByReport['Wallet']      + $rows[16];
	
	$col+=1;
}

// Display Totals By Master	
if ($MasterByCode != '' && $showrebatedt == 1) {
		    
	echo "<tr>";
	echo "   <td colspan='11'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
			
	$StyleClass  = 'totals';
	$TotalsLabel = 'Total by Client';
	DisplayTotals($ArrayTotalByMaster, $DecimalBase, $ClientSalesRMaskQty, $TotalsLabel, $StyleClass);

			
}

// Display Totals By Report			
echo "<tr>";
echo "   <td colspan='11'><hr width='100%' color='black' size='1'></td>";
echo "</tr>";


$StyleClass  = 'summary';
$TotalsLabel = 'TOTALS';
DisplayTotals($ArrayTotalByReport, $DecimalBase, $ClientSalesRMaskQty, $TotalsLabel, $StyleClass);


	
echo "</table></td></tr></table>";
echo'</TBODY>';

function DisplayTotals($PArrayTotal, $PDecimalBase, $PClientSalesRMaskQty, $PTotalsLabel, $PStyleClass) {

	echo "<tr class='".$PStyleClass."'>";
	echo "   <td align='left'  valign='top' >&nbsp;</td>";
	echo "   <td align='left'  valign='top' >".$PTotalsLabel."</td>";
				
	echo "   <td align='right' valign='top' >". number_format($PArrayTotal['SoldQty'], $PClientSalesRMaskQty) ."</td>";
	echo "   <td align='left'  valign='top' >&nbsp;</td>";
	echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['SellAmt'], $PDecimalBase) ."</td>";
	echo "   <td align='left'  valign='top' >&nbsp;</td>";
	echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['RebateAmt'] , $PDecimalBase) ."</td>";
	echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['Amount'] , $PDecimalBase) ."</td>";
	echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['RndRebate'] , $PDecimalBase) ."</td>";
	echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['Value'] , $PDecimalBase) ."</td>";
	echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['Wallet'] , $PDecimalBase) ."</td>";
	echo "</tr>"; 
	
	echo "<tr><td colspan='11'>&nbsp;</td></tr>";

}

function format_currency($amount, $DecimalBase) { 

    if($amount < 0) 
        return "(".number_format(abs($amount),$DecimalBase).")"; 
 
    else return number_format($amount, $DecimalBase); 
} 

function current_server_time($connection){

  $string="Select date_format(NOW(),'%Y-%m-%d %h:%i %p'),dayname(now()) ";
  $result=mysql_query($string,$connection) or die(mysql_error());
  $now=mysql_fetch_row($result);

  return $now;
}

function explodeword($date)
{

$trim = explode('/',$date);
$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
return $trim;
}


if ($printaccess==1)
print <<< HERE

<script language=javascript>
if (typeof(window.print) != 'undefined')
{
    window.print();
}
</script>
</BODY>
</HTML>
HERE;

?>