<?php
require_once('SqlFormatter.php');
session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
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>

<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">

<TITLE> Client Sales Report </TITLE>
</HEAD>


HERE;

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

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");


if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
$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(Setup_Tax1Active,0) as Setup_Tax1Active, ifnull(Setup_Tax2Active,0) as Setup_Tax2Active,  ".
			" ifnull(Setup_Tax3Active,0) as Setup_Tax3Active, ifnull(Setup_Tax4Active,0) as Setup_Tax4Active,  ".
			" ifnull(Setup_Tax5Active,0) as Setup_Tax5Active, Setup_Tax1Name, Setup_Tax2Name, Setup_Tax3Name,  ".
			" Setup_Tax4Name, Setup_Tax5Name ".
			" 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, ifNull(Module_Transportation,0) As Module_Transportation,
			   ifNull(Module_expiredate,0) As Module_expiredate, ifnull(module_chargesInTransfer,0) as module_chargesInTransfer 
			   From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

if($Module_Transportation==0)
	$PrtTransp = 0;
if ($showDBN == '')
	$showDBN = 0;

$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]);

$ndate = explode('/', $fromdate);
$fromdate1 = $ndate[2]."-".$ndate[1]."-".$ndate[0];
$ndate = explode('/', $todate);
$todate1 = $ndate[2]."-".$ndate[1]."-".$ndate[0];
$companyname = explode('_',$_SESSION['dbName']);
$companyname = $companyname[0];
$querySchema = " select schemaname from ( 
				 select concat(CompanyName,'_',Diryear) as schemaname
				 from ".$_SESSION['dbLabel'].".directories
				 where '$fromdate1' between date_format(StartReportDate,'%Y-%m-%d') and date_format(EndReportDate,'%Y-%m-%d')
				 and upper(CompanyName) = upper('$companyname') ".
			   " union 
				 select concat(CompanyName,'_',Diryear) as schemaname
				 from ".$_SESSION['dbLabel'].".directories
				 where '$todate1' between date_format(StartReportDate,'%Y-%m-%d') and date_format(EndReportDate,'%Y-%m-%d')
				 and upper(CompanyName) = upper('$companyname')
				 ) as Q order by schemaname";
	//	echo $querySchema;		
/*
echo"
<TABLE CELLPADDING=6>
<THEAD>";
*/

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


echo "<thead><tr><td align='left'>";
	
$PageLayout='landscape';

if ($prtheader == 1){
	ShowReportHeader('Client Sales Report',$PageLayout, $connection);
} else {
	ShowReportTitle('Client Sales 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];


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

$queryoptions = "Select Ledger_Name From Suppliers Where Ledger_Number = '".$tosupplier1."'";
$resultoptions = mysql_query($queryoptions,$connection) or die(mysql_error());
$rowoptions=mysql_fetch_row($resultoptions);
$tosuppliername1 = $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($Module_expiredate==1 && $edatechk == 1)
if ($fromedate != '')      $SelectedOptions .= "-> Expire Date From: ". $fromedate . "  To: ". $toedate ."<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 ($fromcategory != '')  $SelectedOptions .= "-> Category From: ". $fromcategory . "  To: ". $tocategory ."<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 ($fromsupplier1 != '')  $SelectedOptions .= "-> Supplier From: ". $fromsupplier1 . " (". $fromsuppliername1 .") To: ". $tosupplier1 . " (". $tosuppliername1 .")<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 ($cashtype != '') 	  $SelectedOptions .= "-> Cash Type Include: ". $cashtype . "<br>";	

$fromwh = $fromwarehouse;
  
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');
$fromcategory  = GetSQLValueString($fromcategory, 'text');
$tocategory    = GetSQLValueString($tocategory, '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($fromedate))   $fromedate = explodeword($fromedate);
if (!empty($toedate))     $toedate = explodeword($toedate);  

if (empty($fromedate))    $fromedate = 'null';
else   $fromedate = "'".$fromedate."'"; 
if (empty($toedate))    $toedate = 'null';
else   $toedate = "'".$toedate."'";	

if(empty($showweight))   $showweight = 0;
if(empty($showsales))    $showsales = 0;
if(empty($showretsales)) $showretsales = 0;
if(empty($showunit2qty)) $showunit2qty = 0;

if(empty($prtamt)) 	  $prtamt = 0;
if(empty($prtvat)) 	  $prtvat = 0;
if(empty($prtamtvat)) $prtamtvat = 0;
if(empty($showsellprice)) $showsellprice = 0;
if(empty($sellprice)) $sellprice = 1;

if(empty($activeclt))  $activeclt = 1;
if(empty($activeitem)) $activeitem = 1;
if(empty($vatprint)) $vatprint = 3;
	
$groupby1name = '';
$groupby2name = '';   
$groupby3name = '';
$QryGroupby1Code = '';
$QryGroupby2Code = '';
$QryGroupby3Code = '';
$QryGroupby1Name = '';
$QryGroupby2Name = '';
$QryGroupby3Name = '';

if ($groupby3 != 1 ) {
	$pairs = explode(",", $groupby3);
	
	$vCount = count($pairs);
	if ($vCount > 1) {
		$QryGroupby3Code = 'Concat( ';
		$QryGroupby3Name = 'Concat( ';
	}	
	foreach ($pairs as $pair) {
		
		if ($groupby3name != '') {
			$groupby3name .= " & ";
			$QryGroupby3Code .= ", '*', ";
			$QryGroupby3Name .= ", '*', ";
		}	
			
		
		if ($pair == 2 ) {
			$groupby3name    .= 'Supplier';
			$QryGroupby3Code .= 'ifNull(SupplierCode,"None")';
			$QryGroupby3Name .= 'ifNull(SupplierName,"None")';
		}	
		else if ($pair == 3 ) {	
			$groupby3name    .= 'Salesman';
			$QryGroupby3Code .= 'ifNull(SalesmanCode,"None")';
			$QryGroupby3Name .= 'ifNull(SalesmanName,"None")';
		}
		else if ($pair == 20 ) {	
			$groupby3name    .= 'Transaction Project(Parent)';
			$QryGroupby3Code .= 'ifNull(ParentProjectCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentProjectName,"None")';
		}
		else if ($pair == 4 ) {	
			$groupby3name    .= 'Transaction Project(Detail)';
			$QryGroupby3Code .= 'ifNull(ProjectCode,"None")';
			$QryGroupby3Name .= 'ifNull(ProjectName,"None")';
		}
		else if ($pair == 21 ) {	
			$groupby3name 	 .= 'Archieve Project(Parent)';
			$QryGroupby3Code .= 'ifNull(ParentMasterProject,"None")';
			$QryGroupby3Name .= 'ifNull(ParentMasterProject,"None")';
		}
		else if ($pair == 5 ) {	
			$groupby3name 	 .= 'Archieve Project(Detail)';
			$QryGroupby3Code .= 'ifNull(MasterProject,"None")';
			$QryGroupby3Name .= 'ifNull(MasterProject,"None")';
		}
		else if ($pair == 22 ) {
			$groupby3name    .= 'Transaction Costcenter(Parent)';	
			$QryGroupby3Code .= 'ifNull(ParentCostcenterCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentCostcenterName,"None")';
		}
		else if ($pair == 6 ) {
			$groupby3name    .= 'Transaction Costcenter(Detail)';	
			$QryGroupby3Code .= 'ifNull(CostcenterCode,"None")';
			$QryGroupby3Name .= 'ifNull(CostcenterName,"None")';
		}
		else if ($pair == 23 ) {
			$groupby3name 	 .= 'Archieve Costcenter(Parent)';	
			$QryGroupby3Code .= 'ifNull(ParentMasterCostcent,"None")';
			$QryGroupby3Name .= 'ifNull(ParentMasterCostcent,"None")';
		}
		else if ($pair == 7 ) {
			$groupby3name 	 .= 'Archieve Costcenter(Detail)';	
			$QryGroupby3Code .= 'ifNull(MasterCostcent,"None")';
			$QryGroupby3Name .= 'ifNull(MasterCostcent,"None")';
		}
		else if ($pair == 24 ) {
			$groupby3name	 .= 'Warehouse(Parent)';	
			$QryGroupby3Code .= 'ifNull(ParentWarehouseCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentWarehouseCode,"None")';
		}
		else if ($pair == 8 ) {
			$groupby3name	 .= 'Warehouse(Detail)';	
			$QryGroupby3Code .= 'ifNull(WarehouseCode,"None")';
			$QryGroupby3Name .= 'ifNull(WarehouseCode,"None")';
		}
		else if ($pair == 9 ) {	
			$groupby3name    .= 'Business Type';
			$QryGroupby3Code .= 'ifNull(BusinessType,"None")';
			$QryGroupby3Name .= 'ifNull(BusinessType,"None")';
		}
		else if ($pair == 25 )	{
			$groupby3name    .= 'Group(Parent)';
			$QryGroupby3Code .= 'ifNull(ParentGroupCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentGroupName,"None")';
		}
		else if ($pair == 10 )	{
			$groupby3name    .= 'Group(Detail)';
			$QryGroupby3Code .= 'ifNull(GroupCode,"None")';
			$QryGroupby3Name .= 'ifNull(GroupName,"None")';
		}
		else if ($pair == 26 )	{
			$groupby3name 	 .= 'Subgroup(Parent)';
			$QryGroupby3Code .= 'ifNull(ParentSubGroupCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentSubGroupName,"None")';
		}
		else if ($pair == 11 )	{
			$groupby3name 	 .= 'Subgroup(Detail)';
			$QryGroupby3Code .= 'ifNull(SubGroupCode,"None")';
			$QryGroupby3Name .= 'ifNull(SubGroupName,"None")';
		}
		else if ($pair == 12 ) {	
			$groupby3name 	 .= 'Category';
			$QryGroupby3Code .= 'ifNull(CategoryCode,"None")';
			$QryGroupby3Name .= 'ifNull(CategoryName,"None")';
		}
		else if ($pair == 13 )	{
			$groupby3name 	 .= 'Profit Center';
			$QryGroupby3Code .= 'ifNull(ProfitCenter,"None")';
			$QryGroupby3Name .= 'ifNull(ProfitCenter,"None")';
		}
		else if ($pair == 27 )	{
			$groupby3name    .= 'Area(Parent)';				
			$QryGroupby3Code .= 'ifNull(ParentAreaCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentAreaName,"None")';
		}
		else if ($pair == 14 )	{
			$groupby3name 	 .= 'Area(Detail)';				
			$QryGroupby3Code .= 'ifNull(AreaCode,"None")';
			$QryGroupby3Name .= 'ifNull(AreaName,"None")';
		}
		else if ($pair == 16 )	{
			$groupby3name 	 .= 'Expire Date';				
			$QryGroupby3Code .= 'ifNull(Item_ExpireDate ,"None")';
			$QryGroupby3Name .= 'ifNull(Item_ExpireDate ,"None")';
		}
		
	}
	
	if ($vCount > 1) {
		$QryGroupby3Code .= ' ) ';
		$QryGroupby3Name .= ' ) ';
	}
	
	$QryGroupby3Code .= ' As Groupby3Code, ';
	$QryGroupby3Name .= ' As Groupby3Name, ';

} else 
{
	$QryGroupby3Code .= " -1 As Groupby3Code, ";
	$QryGroupby3Name .= " 'None' As Groupby3Name, ";
}
//echo $QryGroupby3Code."<br>";
//echo $QryGroupby3Name;
//exit;

if ($groupby1 != '' ) {
		
	if ($groupby1 == 2 ) {
		$groupby1name    .= 'Supplier';
		$QryGroupby1Code .= 'ifNull(SupplierCode,"None")';
		$QryGroupby1Name .= 'ifNull(SupplierName,"None")';
	}	
	else if ($groupby1 == 3 ) {	
		$groupby1name    .= 'Salesman';
		$QryGroupby1Code .= 'ifNull(SalesmanCode,"None")';
		$QryGroupby1Name .= 'ifNull(SalesmanName,"None")';
	}
	else if ($groupby1 == 20 ) {	
		$groupby1name    .= 'Transaction Project(Parent)';
		$QryGroupby1Code .= 'ifNull(ParentProjectCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentProjectName,"None")';
	}
	else if ($groupby1 == 4 ) {	
		$groupby1name    .= 'Transaction Project(Detail)';
		$QryGroupby1Code .= 'ifNull(ProjectCode,"None")';
		$QryGroupby1Name .= 'ifNull(ProjectName,"None")';
	}
	else if ($groupby1 == 21 ) {	
		$groupby1name 	 .= 'Archieve Project(Parent)';
		$QryGroupby1Code .= 'ifNull(ParentMasterProject,"None")';
		$QryGroupby1Name .= 'ifNull(ParentMasterProject,"None")';
	}
	else if ($groupby1 == 5 ) {	
		$groupby1name 	 .= 'Archieve Project(Detail)';
		$QryGroupby1Code .= 'ifNull(MasterProject,"None")';
		$QryGroupby1Name .= 'ifNull(MasterProject,"None")';
	}
	else if ($groupby1 == 22 ) {	
		$groupby1name    .= 'Transaction Costcenter(Parent)';	
		$QryGroupby1Code .= 'ifNull(ParentCostcenterCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentCostcenterName,"None")';
	}
	else if ($groupby1 == 6 ) {	
		$groupby1name    .= 'Transaction Costcenter(Detail)';	
		$QryGroupby1Code .= 'ifNull(CostcenterCode,"None")';
		$QryGroupby1Name .= 'ifNull(CostcenterName,"None")';
	}
	else if ($groupby1 == 23 ) {
		$groupby1name 	 .= 'Archieve Costcenter(Parent)';	
		$QryGroupby1Code .= 'ifNull(ParentMasterCostcent,"None")';
		$QryGroupby1Name .= 'ifNull(ParentMasterCostcent,"None")';
	}
	else if ($groupby1 == 7 ) {
		$groupby1name 	 .= 'Archieve Costcenter(Detail)';	
		$QryGroupby1Code .= 'ifNull(MasterCostcent,"None")';
		$QryGroupby1Name .= 'ifNull(MasterCostcent,"None")';
	}
	else if ($groupby1 == 24 ) { 	
		$groupby1name	 .= 'Warehouse(Parent)';	
		$QryGroupby1Code .= 'ifNull(ParentWarehouseCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentWarehouseCode,"None")';
	}
	else if ($groupby1 == 8 ) { 	
		$groupby1name	 .= 'Warehouse(Detail)';	
		$QryGroupby1Code .= 'ifNull(WarehouseCode,"None")';
		$QryGroupby1Name .= 'ifNull(WarehouseCode,"None")';
	}
	else if ($groupby1 == 9 ) {	
		$groupby1name    .= 'Business Type';
		$QryGroupby1Code .= 'ifNull(BusinessType,"None")';
		$QryGroupby1Name .= 'ifNull(BusinessType,"None")';
	}
	else if ($groupby1 == 25 )	{
		$groupby1name    .= 'Group(Parent)';
		$QryGroupby1Code .= 'ifNull(ParentGroupCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentGroupName,"None")';
	}
	else if ($groupby1 == 10 )	{
		$groupby1name    .= 'Group(Detail)';
		$QryGroupby1Code .= 'ifNull(GroupCode,"None")';
		$QryGroupby1Name .= 'ifNull(GroupName,"None")';
	}
	else if ($groupby1 == 26 )	{
		$groupby1name 	 .= 'Subgroup(Parent)';
		$QryGroupby1Code .= 'ifNull(ParentSubGroupCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentSubGroupName,"None")';
	}
	else if ($groupby1 == 11 )	{
		$groupby1name 	 .= 'Subgroup(Detail)';
		$QryGroupby1Code .= 'ifNull(SubGroupCode,"None")';
		$QryGroupby1Name .= 'ifNull(SubGroupName,"None")';
	}
	else if ($groupby1 == 12 ) {	
		$groupby1name 	 .= 'Category';
		$QryGroupby1Code .= 'ifNull(CategoryCode,"None")';
		$QryGroupby1Name .= 'ifNull(CategoryName,"None")';
	}
	else if ($groupby1 == 13 )	{
		$groupby1name 	 .= 'Profit Center';
		$QryGroupby1Code .= 'ifNull(ProfitCenter,"None")';
		$QryGroupby1Name .= 'ifNull(ProfitCenter,"None")';
	}
	else if ($groupby1 == 27 )	{
		$groupby1name 	 .= 'Area(Parent)';				
		$QryGroupby1Code .= 'ifNull(ParentAreaCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentAreaName,"None")';
	}
	else if ($groupby1 == 14 )	{
		$groupby1name 	 .= 'Area(Detail)';				
		$QryGroupby1Code .= 'ifNull(AreaCode,"None")';
		$QryGroupby1Name .= 'ifNull(AreaName,"None")';
	}
	else if ($groupby1 == 16 )	{
			$groupby1name 	 .= 'Expire Date';				
			$QryGroupby1Code .= 'ifNull(Item_ExpireDate ,"None")';
			$QryGroupby1Name .= 'ifNull(Item_ExpireDate ,"None")';
		}
		
	else {
		$groupby1name    .= '';				
		$QryGroupby1Code .= "-1";
		$QryGroupby1Name .= "'None'";
	}
		
	
	$QryGroupby1Code .= ' As Groupby1Code, ';
	$QryGroupby1Name .= ' As Groupby1Name, ';

} else 
{
	$QryGroupby1Code .= " -1 As Groupby1Code, ";
	$QryGroupby1Name .= " 'None' As Groupby1Name, ";
}

if ($groupby2 != '' ) {
		
	if ($groupby2 == 2 ) {
		$groupby2name    .= 'Supplier';
		$QryGroupby2Code .= 'ifNull(SupplierCode,"None")';
		$QryGroupby2Name .= 'ifNull(SupplierName,"None")';
	}	
	else if ($groupby2 == 3 ) {	
		$groupby2name    .= 'Salesman';
		$QryGroupby2Code .= 'ifNull(SalesmanCode,"None")';
		$QryGroupby2Name .= 'ifNull(SalesmanName,"None")';
	}
	else if ($groupby2 == 20 ) {	
		$groupby2name    .= 'Transaction Project(Parent)';
		$QryGroupby2Code .= 'ifNull(ParentProjectCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentProjectName,"None")';
	}
	else if ($groupby2 == 4 ) {	
		$groupby2name    .= 'Transaction Project(Detail)';
		$QryGroupby2Code .= 'ifNull(ProjectCode,"None")';
		$QryGroupby2Name .= 'ifNull(ProjectName,"None")';
	}
	else if ($groupby2 == 21 ) {	
		$groupby2name 	 .= 'Archieve Project(Parent)';
		$QryGroupby2Code .= 'ifNull(ParentMasterProject,"None")';
		$QryGroupby2Name .= 'ifNull(ParentMasterProject,"None")';
	}
	else if ($groupby2 == 5 ) {	
		$groupby2name 	 .= 'Archieve Project(Detail)';
		$QryGroupby2Code .= 'ifNull(MasterProject,"None")';
		$QryGroupby2Name .= 'ifNull(MasterProject,"None")';
	}
	else if ($groupby2 == 22 ) {	
		$groupby2name    .= 'Transaction Costcenter(Parent)';	
		$QryGroupby2Code .= 'ifNull(ParentCostcenterCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentCostcenterName,"None")';
	}
	else if ($groupby2 == 6 ) {	
		$groupby2name    .= 'Transaction Costcenter(Detail)';	
		$QryGroupby2Code .= 'ifNull(CostcenterCode,"None")';
		$QryGroupby2Name .= 'ifNull(CostcenterName,"None")';
	}
	else if ($groupby2 == 23 ) {
		$groupby2name 	 .= 'Archieve Costcenter(Parent)';	
		$QryGroupby2Code .= 'ifNull(ParentMasterCostcent,"None")';
		$QryGroupby2Name .= 'ifNull(ParentMasterCostcent,"None")';
	}
	else if ($groupby2 == 7 ) {
		$groupby2name 	 .= 'Archieve Costcenter(Detail)';	
		$QryGroupby2Code .= 'ifNull(MasterCostcent,"None")';
		$QryGroupby2Name .= 'ifNull(MasterCostcent,"None")';
	}
	else if ($groupby2 == 24 ) { 	
		$groupby2name	 .= 'Warehouse(Parent)';	
		$QryGroupby2Code .= 'ifNull(ParentWarehouseCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentWarehouseCode,"None")';
	}
	else if ($groupby2 == 8 ) { 	
		$groupby2name	 .= 'Warehouse(Detail)';	
		$QryGroupby2Code .= 'ifNull(WarehouseCode,"None")';
		$QryGroupby2Name .= 'ifNull(WarehouseCode,"None")';
	}
	else if ($groupby2 == 9 ) {	
		$groupby2name    .= 'Business Type';
		$QryGroupby2Code .= 'ifNull(BusinessType,"None")';
		$QryGroupby2Name .= 'ifNull(BusinessType,"None")';
	}
	else if ($groupby2 == 25 )	{
		$groupby2name    .= 'Group(Parent)';
		$QryGroupby2Code .= 'ifNull(ParentGroupCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentGroupName,"None")';
	}
	else if ($groupby2 == 10 )	{
		$groupby2name    .= 'Group(Detail)';
		$QryGroupby2Code .= 'ifNull(GroupCode,"None")';
		$QryGroupby2Name .= 'ifNull(GroupName,"None")';
	}
	else if ($groupby2 == 26 )	{
		$groupby2name 	 .= 'Subgroup(Parent)';
		$QryGroupby2Code .= 'ifNull(ParentSubGroupCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentSubGroupName,"None")';
	}
	else if ($groupby2 == 11 )	{
		$groupby2name 	 .= 'Subgroup(Detail)';
		$QryGroupby2Code .= 'ifNull(SubGroupCode,"None")';
		$QryGroupby2Name .= 'ifNull(SubGroupName,"None")';
	}
	else if ($groupby2 == 12 ) {	
		$groupby2name 	 .= 'Category';
		$QryGroupby2Code .= 'ifNull(CategoryCode,"None")';
		$QryGroupby2Name .= 'ifNull(CategoryName,"None")';
	}
	else if ($groupby2 == 13 )	{
		$groupby2name 	 .= 'Profit Center';
		$QryGroupby2Code .= 'ifNull(ProfitCenter,"None")';
		$QryGroupby2Name .= 'ifNull(ProfitCenter,"None")';
	}
	else if ($groupby2 == 27 )	{
		$groupby2name 	 .= 'Area(Parent)';				
		$QryGroupby2Code .= 'ifNull(ParentAreaCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentAreaName,"None")';
	}
	else if ($groupby2 == 14 )	{
		$groupby2name 	 .= 'Area(Detail)';				
		$QryGroupby2Code .= 'ifNull(AreaCode,"None")';
		$QryGroupby2Name .= 'ifNull(AreaName,"None")';
	}
	else if ($groupby2 == 16 )	{
			$groupby2name 	 .= 'Expire Date';				
			$QryGroupby2Code .= 'ifNull(Item_ExpireDate ,"None")';
			$QryGroupby2Name .= 'ifNull(Item_ExpireDate ,"None")';
		}
	else {
		$groupby2name    .= '';				
		$QryGroupby2Code .= "-1";
		$QryGroupby2Name .= "'None'";
	}
		
	
	$QryGroupby2Code .= ' As Groupby2Code, ';
	$QryGroupby2Name .= ' As Groupby2Name ';

} else 
{
	$QryGroupby2Code .= " -1 As Groupby2Code, ";
	$QryGroupby2Name .= " 'None' As Groupby2Name ";
}


$SelectedGroupBy = "Group by:  ";
if ($groupby1 != '' ) $SelectedGroupBy = $SelectedGroupBy . $groupby1name.", ";
if ($groupby2 != '' ) $SelectedGroupBy = $SelectedGroupBy . $groupby2name.", ";
if ($groupby3 != 1 )  $SelectedGroupBy = $SelectedGroupBy . $groupby3name.", ";
$SelectedOptions = substr($SelectedGroupBy, 0, strlen($SelectedGroupBy)-2) . "<br>" . $SelectedOptions;
				
				
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' width='100%' align='center' class='report-master' style='table-layout:fixed' cellpadding='0' cellspacing='0'>
	  <col width=100>
      <col width=200>
      <col width=50>
      <col width=65>
      <col width=65>
      <col width=80>
	  <col width=50>";

if ($showunit2qty == 1) {
	echo "<col width=80>";
	echo "<col width=50>";
}
	  
if ($showweight == 1) {
	echo "<col width=60>";
	echo "<col width=80>";
}
if ($packitem == 0 && $prtqtyexist == 1) {
	echo "<col width=80>";
}	
	
echo "<col width=40>";

if ($prtamt == 1) echo"<col width=110>";
if ($prtamt == 1) echo"<col width=100>";
	  
if ($Module_AdditionalTaxes == 1) {
	if ($Setup_Tax1Active == 1) echo "<col width=80>";
	if ($Setup_Tax2Active == 1) echo "<col width=80>";
	if ($Setup_Tax3Active == 1) echo "<col width=80>";
	if ($Setup_Tax4Active == 1) echo "<col width=80>";
	if ($Setup_Tax5Active == 1) echo "<col width=80>";
	
	echo "<col width=80>";
}

if ($prtdisc == 1) {
	echo "<col width=80>";
}	  

echo "<col width=100>";
echo "<col width=100>";
	  
if ($FI_ShowCostPrice == 1 && $prtcost == 1) {
	echo"<col width=110>
	  	 <col width=120>
		 <col width=120>
		 <col width=80>";
}		  
if($PrtTransp==1) 
	echo" <col width=80>";
echo"<thead><tr >";

$ColsCount = 9;

if ($prtdt == 0 && $prtsubdt == 0 && ($groupby1 != '' || $groupby2 != '' || $groupby3 != 1)) {
	echo"<th align='left' colspan='2'>Grouping Description</th>";
}
else if (($masterby == 1 && $prtsubdt == 0) || ($masterby == 2 && $prtsubdt == 1)) {
	echo"<th align='left'>Client Code</th>
		 <th >Name</th>";
} else {
    echo"<th align='left'>Item Code</th>
		 <th >Description</th>";
}

	 
		 
if ($option == 1) {
	echo"<th >&nbsp;</th>
		 <th >Qty.Return</th>
		 <th >Qty.Sold</th>";
} else {
	echo"<th >W.H.</th>
		 <th >Reference</th>
		 <th >Date</th>";
}		 
echo"    <th >Qty.Net</th>";
echo"    <th >Unit</th>";

if ($showunit2qty == 1) {
	echo "<th >Unit2Qty Sold</th>";
	echo "<th >Unit2</th>";
	
	$ColsCount += 2;
}

if ($showweight == 1) {
	echo" <th >Weight</th>
		  <th >Total Weight</th>";
		  
	$ColsCount += 2;
}

if ($packitem == 0 && $prtqtyexist == 1) {
	echo"<th >Qty.Exist</th>";
	$ColsCount += 1;
}	

echo"  <th >Cur.</th>";

if ($prtamt == 1) {
	echo"<th >Sell. Amount</th>";
	$ColsCount += 1;
}	
if ($prtvat == 1) {
	echo"<th >VAT</th>";
	$ColsCount += 1;
}

if ($Module_AdditionalTaxes == 1) {
	if ($Setup_Tax1Active == 1) { $ColsCount += 1; echo"<th >$Setup_Tax1Name</th>"; }
	if ($Setup_Tax2Active == 1) { $ColsCount += 1; echo"<th >$Setup_Tax2Name</th>"; }
	if ($Setup_Tax3Active == 1) { $ColsCount += 1; echo"<th >$Setup_Tax3Name</th>"; }
	if ($Setup_Tax4Active == 1) { $ColsCount += 1; echo"<th >$Setup_Tax4Name</th>"; }
	if ($Setup_Tax5Active == 1) { $ColsCount += 1; echo"<th >$Setup_Tax5Name</th>"; }
	
	$ColsCount += 1; 
	echo"<th >Total Taxes</th>";
}

if ($prtdisc == 1) {		 
	echo"<th >Disc. Amount</th>";
	$ColsCount += 1;
}

echo"<th >Total Amt.</th>";
echo"<th >Unit Price</th>";
		 
if ($FI_ShowCostPrice == 1 && $prtcost == 1) {		 
	echo"<th >Mean Cost</th>
		 <th >T.Mean Cost</th>
		 <th >ProfitAmount</th>
		 <th >P.Margin</th>";
		 
	$ColsCount += 4;
}

if($PrtTransp==1) {
 echo"<th >Transp.Amt.</th>";
 $ColsCount += 1;
 }
 
$ColsCountsub=$ColsCount-1;	
$ColsCountmain=	$ColsCount;
print <<<HERE
</tr>
<tr>
    <td colspan='$ColsCountmain'><hr width='100%' color='black' size='1'></td>
</tr>
 <thead>
HERE;
 

//Sales Query
$querysales = '';
if ($option == 1) {
    $querysales = 
				" Select Reference, StkDate, MasterCode, MasterDescription, DetailCode, DetailDescription, ClientCode, ClientName, ".
				" ItemCode, ItemDescription, WarehouseCode, Currency, Groupby3Code, Groupby3Name, SaleDt_discountper, ".
				" (Sum(SellAmount)/Sum(QtyNetSold)) As UnitPrice, Sum(VatAmount) As VatAmount, Sum(DiscountAmount) As DiscountAmount, (Sum(TotalMeanCost)/Sum(QtyNetSold))  MeanCostAmount, ".
				" Sum(SellAmount) As SellAmount, Sum(TotalMeanCost) As TotalMeanCost, (Sum(SellAmount) - Sum(TotalMeanCost)) As ProfitAmount, ".
				" if($prfmarby=2 and (Sum(TotalMeanCost)/Sum(QtyNetSold))=0, 0, (((Sum(SellAmount) - Sum(TotalMeanCost)) / if($prfmarby=1,Sum(SellAmount),Sum(TotalMeanCost))) * 100)) As ProfitMargin, ".
				" Round(Sum(QtyNetSold),2) As QtyNetSold, QtyExists, Round(Sum(QtySold),2) As QtySold, Round(Sum(QtyReturn),2) As QtyReturn, ".
				" Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, ItemWeight, Item_UnitSalesDesc, Round(Sum(ItemWeight*QtyNetSold),2) as TotalWeight, OrderDate, ".
				" Sum(Tax1Amount) As Tax1Amount, Sum(Tax2Amount) As Tax2Amount, Sum(Tax3Amount) As Tax3Amount, Sum(Tax4Amount) As Tax4Amount, Sum(Tax5Amount) As Tax5Amount, Item_UnitPurchaseDesc, Round(Sum(Qty2Sold),2) As Qty2Sold  ".
				" ,TransportAmount, WHTAmount, Trans_Type ".
                " From ( ";

}

if ($packitem == 1) {
    $querysales = $querysales.
				" Select Reference, StkDate, MasterCode, MasterDescription, DetailCode, DetailDescription, ClientCode, ClientName, ".
				" ItemCode, ItemDescription, WarehouseCode, Currency, Groupby3Code, Groupby3Name, SaleDt_discountper, ".
				" Sum(UnitPrice) As UnitPrice, Sum(VatAmount) As VatAmount, Sum(DiscountAmount) As DiscountAmount, Sum(MeanCostAmount)  MeanCostAmount, ".
				" Sum(SellAmount) As SellAmount, Sum(TotalMeanCost) As TotalMeanCost, ".
				" Sum(ProfitAmount) As ProfitAmount, ".
				" if($prfmarby=2 and Sum(TotalMeanCost)=0, 0, (((Sum(SellAmount) - Sum(TotalMeanCost)) / if($prfmarby=1,Sum(SellAmount),Sum(TotalMeanCost))) * 100)) As ProfitMargin, ".
				" Sum(if(Item_CodePacked='', QtyNetSold, QtyNetSold/QtyPack)) As QtyNetSold, QtyExists, ".
				" Sum(if(Item_CodePacked='', QtySold, QtySold/QtyPack)) As QtySold, ".
				" Sum(if(Item_CodePacked='', QtyReturn, QtyReturn/QtyPack)) As QtyReturn, ".
				" Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, ItemWeight, Item_UnitSalesDesc, Sum(if(Item_CodePacked='', (ItemWeight*QtyNetSold), ItemWeight*QtyNetSold/QtyPack)) as TotalWeight, OrderDate, ".
				" Sum(Tax1Amount) As Tax1Amount, Sum(Tax2Amount) As Tax2Amount, Sum(Tax3Amount) As Tax3Amount, Sum(Tax4Amount) As Tax4Amount, Sum(Tax5Amount) As Tax5Amount, Item_UnitPurchaseDesc, Sum(if(Item_CodePacked='', Qty2Sold, Qty2Sold/QtyPack)) As Qty2Sold  ".
				" ,TransportAmount, WHTAmount, Trans_Type ".
				" From ( ";

}
$querysales = $querysales.
				" Select Reference, StkDate, MasterCode, MasterDescription, DetailCode, DetailDescription, ClientCode, ClientName, ".
				" ItemCode, ItemDescription, WarehouseCode, Currency, ";
				
$querysales = $querysales.$QryGroupby3Code . $QryGroupby3Name;	

/*				" ifNull(if($groupby=2, SupplierCode, if($groupby=3, GroupCode, if($groupby=4, SubGroupCode, if($groupby=5, CategoryCode, ".
			    " if($groupby=6, SalesmanCode, if($groupby=7, ProfitCenter, if($groupby=8, ProfitGroup, if($groupby=9, CostcenterCode, ".
				" if($groupby=10, ProjectCode, if($groupby=11, AreaCode, if($groupby=12, BusinessType, ''))))))))))), -1) As GroupbyCode, ".
				" ifNull(if($groupby=2, SupplierName, if($groupby=3, GroupName, if($groupby=4, SubGroupName, if($groupby=5, CategoryName, ".
			    " if($groupby=6, SalesmanName, if($groupby=7, ProfitCenter, if($groupby=8, ProfitGroup, if($groupby=9, CostcenterName, ".
				" if($groupby=10, ProjectName, if($groupby=11, AreaName, if($groupby=12, '', ''))))))))))), 'None') As GroupbyName, ".
*/

$querysales = $querysales.
				" SaleDt_discountper, UnitPrice, ((ItemVat*UnitPrice*QtyNetSold)/100) As VatAmount, DiscountAmount, MeanCostAmount, ".
				" (UnitPrice*QtyNetSold) As SellAmount, (MeanCostAmount*QtyNetSold) As TotalMeanCost, ".
				" ((UnitPrice*QtyNetSold) - (MeanCostAmount*QtyNetSold)) As ProfitAmount, ".
				" if($prfmarby=2 and (MeanCostAmount*QtyNetSold)=0, 0, ((((UnitPrice*QtyNetSold) - (MeanCostAmount*QtyNetSold)) / if($prfmarby=1,(UnitPrice*QtyNetSold),(MeanCostAmount*QtyNetSold))) * 100)) As ProfitMargin, ".
				" QtyNetSold, QtyExists, QtySold, QtyReturn, ";

$querysales = $querysales.$QryGroupby1Code . $QryGroupby1Name.
                          $QryGroupby2Code . $QryGroupby2Name;

$querysales = $querysales.", ItemWeight, Item_UnitSalesDesc, (ItemWeight*QtyNetSold) as TotalWeight ";
$querysales = $querysales.", OrderDate, ((ItemTax1*UnitPrice*QtyNetSold)/100) As Tax1Amount, ((ItemTax2*UnitPrice*QtyNetSold)/100) As Tax2Amount, ((ItemTax3*UnitPrice*QtyNetSold)/100) As Tax3Amount ".
						  ", ((ItemTax4*UnitPrice*QtyNetSold)/100) As Tax4Amount, ((ItemTax5*UnitPrice*QtyNetSold)/100) As Tax5Amount, Item_UnitPurchaseDesc, Qty2Sold ";
if ($packitem == 1) 				
	$querysales = $querysales.", Item_CodePacked, QtyPack ";

$querysales = $querysales."	,TransportAmount , WHTAmount, Trans_Type ";
	
$querysales = $querysales.	
                " From ( ".
				" Select Sales.Sale_Reference As Reference, Date_Format(Sales.Sale_Date,'%d/%m/%Y') As StkDate, Sales.Sale_Date As OrderDate, ".
			    " if($prtdt=1, if($masterby=1, Sales.Client_Code, if($packitem=1, if(SalesDt.Item_CodePacked='', SalesDt.Item_Code, SalesDt.Item_CodePacked), SalesDt.Item_Code)), '') As MasterCode, ".
				" if($prtdt=1, if($masterby=1, Clients.Ledger_Name, Items.Item_Description), '') As MasterDescription , ".
				" if($prtsubdt=1, if($masterby=1, if($packitem=1, if(SalesDt.Item_CodePacked='', SalesDt.Item_Code, SalesDt.Item_CodePacked), SalesDt.Item_Code), Sales.Client_Code), '') As DetailCode, ".
				" if($prtsubdt=1, if($masterby=1, Items.Item_Description, Clients.Ledger_Name), '') As DetailDescription , ".
				" Sales.Client_Code As ClientCode, Clients.Ledger_Name As ClientName, ".
				" if($packitem=1, if(SalesDt.Item_CodePacked='', SalesDt.Item_Code, SalesDt.Item_CodePacked), SalesDt.Item_Code) As ItemCode, Items.Item_Description As ItemDescription, ".
				" Items.Item_Weight as ItemWeight, Items.Item_UnitSalesDesc, Items.Item_UnitPurchaseDesc,  ".
				" Sales.Salesman_Code As SalesmanCode,Salesmen.Ledger_Name As SalesmanName, ".
				" Items.Ledger_Number As SupplierCode,Suppliers.Ledger_Name As SupplierName, ".
				" ifNull(Costcent.Parent_Code, Costcent.Costcent_Code) As ParentCostcenterCode,Costcent.Costcent_Name As ParentCostcenterName, ".
				" SalesDt.Costcenter_code As CostcenterCode,Costcent.Costcent_Name As CostcenterName, ".
				" ifNull(Project.Parent_Code, Project.Project_Code) As ParentProjectCode, Project.Project_Name As ParentProjectName, ".
				" SalesDt.Project_Code As ProjectCode,Project.Project_Name As ProjectName, ".
				" ifNull(Grouping.Parent_Code, Items.Group_Code) As ParentGroupCode, Grouping.Group_Name As ParentGroupName, ".
				" Items.Group_Code As GroupCode,Grouping.Group_Name As GroupName, ".
				" ifNull(Subgroup.Parent_Code, Items.SubGroup_Code) As ParentSubGroupCode, Subgroup.Subgroup_Name As ParentSubGroupName, ".
				" Items.SubGroup_Code As SubGroupCode,Subgroup.Subgroup_Name As SubGroupName, ".
				" ifNull(Area.Parent_Code, Clients.Area_Code) As ParentAreaCode, Area.Area_Name As ParentAreaName, ".
				" Clients.Area_Code As AreaCode ,Area.Area_Name As AreaName, ".
				" Items.Category_Code As CategoryCode, Category.Category_Name As CategoryName, ".
				" Clients.ProfitCenter_Code As ProfitCenter,Concat(Clients.ProfitCenter_Code,' and ',Items.Group_Code) As ProfitGroup, ".
				" Clients.Client_BusinessType As BusinessType, Clients.Project_Code As MasterProject, Clients.CostCenter_Code As MasterCostcent, ".
				" ifNull(Project1.Parent_Code, Clients.Project_Code) As ParentMasterProject, ifNull(Costcent1.Parent_Code, Clients.CostCenter_Code) As ParentMasterCostcent, ".
				" SalesDt.Warehouse_Code As WarehouseCode, ifNull(Warehouse1.Warehouse_Code, SalesDt.Warehouse_Code) As ParentWarehouseCode,  ".
				" if(upper($curr)='".$Base1."', '".$Base1."', if(upper($curr)='".$Base2."', '".$Base2."', Sales.Currency_Code))  As Currency, ".
				" ifNull(SalesDt.SaleDt_discountper, 0) As SaleDt_discountper,  ".
				//" if($pricettc=1, if(ifNull(SalesDt.SaleDt_PriceTTC,0)=0, 0,  ".
				//" ifNull( (((if(upper($curr)='".$Base1."',SalesDt.SaleDt_PriceTTCBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_PriceTTCBase2, SalesDt.SaleDt_PriceTTC)) - ".
				//"         (ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_PriceTTCBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_PriceTTCBase2, SalesDt.SaleDt_PriceTTC)),0) * ifNull(SalesDt.SaleDt_discountper, 0)/100))*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))/SalesDt.SaleDt_Quantity) ,0)),  ".
				" if($showsellprice != 1, ".
				" 		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))*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_BonusBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_BonusBase2,SalesDt.SaleDt_BonusAmount)),0))/SalesDt.SaleDt_Quantity) ,0)), ".
				"  		if($sellprice = 1, if(upper($curr)='".$Base1."', Items.Item_SellingPrice1Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice1Base2, Items.Item_SellingPrice1)), ".
				" 		if($sellprice = 2, if(upper($curr)='".$Base1."', Items.Item_SellingPrice2Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice2Base2, Items.Item_SellingPrice2)), ".
				" 		if($sellprice = 3, if(upper($curr)='".$Base1."', Items.Item_SellingPrice3Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice3Base2, Items.Item_SellingPrice3)), ".
				" 		if($sellprice = 4, if(upper($curr)='".$Base1."', Items.Item_SellingPrice4Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice4Base2, Items.Item_SellingPrice4)), ".
				" 		if($sellprice = 5, if(upper($curr)='".$Base1."', Items.Item_SellingPrice5Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice5Base2, Items.Item_SellingPrice5)), ".
				" 		if($sellprice = 6, if(upper($curr)='".$Base1."', Items.Item_SellingPrice6Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice6Base2, Items.Item_SellingPrice6)), 0)))))) ".
				"    )  As UnitPrice, ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_TransportBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_TransportBase2,SalesDt.SaleDt_TransportAmount)),0) TransportAmount, ".
				" if(ifNull(sale_chkvat,0) = 1, SalesDt.Item_Vat, 0) As ItemVat, ifNull(SalesDt.Item_tax1,0) as ItemTax1, ifNull(SalesDt.Item_tax2,0) as ItemTax2, ifNull(SalesDt.Item_tax3,0) as ItemTax3, ifNull(SalesDt.Item_tax4,0) as ItemTax4, ifNull(SalesDt.Item_tax5,0) as ItemTax5, ".
				" if($pricettc=1, ((ifNull(if(upper($curr)='".$Base1."',ifNull(SalesDt.SaleDt_PriceTTCBase1,0),if(upper($curr)='".$Base2."',ifNull(SalesDt.SaleDt_PriceTTCBase2,0), ifNull(SalesDt.SaleDt_PriceTTC,0))),0) * ifNull(SalesDt.SaleDt_discountper, 0)/100)*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."',ifNull(SalesDt.SaleDt_PriceBase1,0),if(upper($curr)='".$Base2."',ifNull(SalesDt.SaleDt_PriceBase2,0), ifNull(SalesDt.SaleDt_Price,0))),0) * ifNull(SalesDt.SaleDt_discountper, 0)/100)*SalesDt.SaleDt_Quantity + ".
				"                   ifNull(if(upper($curr)='".$Base1."',SalesDt.SaleDt_DiscountBase1,if(upper($curr)='".$Base2."',SalesDt.SaleDt_DiscountBase2,SalesDt.SaleDt_DiscountAmount)),0)) ) As DiscountAmount,  ";
				
//$querysales= $querysales." ifNull(MeanCostCur(SalesDt.item_code, concat(".$todate.", ' 23:59:59'), if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), Sales.currency_code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";	

if ($module_chargesInTransfer == 1  && $fromwh != ''){
	$querysales= $querysales." ifNull(MeanCostCurByWH(SalesDt.item_code, concat(date_format(Sales.Sale_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), Sales.currency_code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code )), '$fromwh'),0) MeanCostAmount, ";
} else {
	if ($updmeancost == 1)
		$querysales= $querysales." ifNull(MeanCostCur(SalesDt.item_code, concat(date_format(Sales.Sale_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), Sales.currency_code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";
	else
		$querysales= $querysales." if(upper($curr)='".$Base1."', ifNull(DeliveryDt_CostBase1,0), if(upper($curr)='".$Base2."', ifNull(DeliveryDt_CostBase2,0), ifNull(DeliveryDt_Cost,0))) MeanCostAmount, ";				
}
$querysales= $querysales.
				" if(SalesDt.Journal_Type = 'SI',SalesDt.SaleDt_Quantity,(-1)*SalesDt.SaleDt_Quantity) As QtyNetSold, ";

if ($prtqtyexist == 1) {				
	$querysales= $querysales." QQtyExists.QuantityExists As QtyExists, ";
} else {
	$querysales= $querysales." Null As QtyExists, ";
}				

$querysales= $querysales.				
				" if(SalesDt.Journal_Type = 'SI',SalesDt.SaleDt_Quantity,0) As QtySold, ".
				" if(SalesDt.Journal_Type = 'SI',SalesDt.Item_Unit2Qty,0) As Qty2Sold, ".
				" if(SalesDt.Journal_Type = 'SR',Abs(SalesDt.SaleDt_Quantity),0) As QtyReturn ";

if ($packitem == 1) 				
	$querysales = $querysales.", SalesDt.Item_CodePacked, ifNull(QtyPack, 1) QtyPack ";

	
$querysales = $querysales.", SaleDt_ExpireDate as Item_ExpireDate, ifNull(if(upper($curr)='".$Base1."',Sales.Sale_WHTAmountBase1,
if(upper($curr)='".$Base2."',Sales.Sale_WHTAmountBase2, Sales.Sale_WHTAmount)),0) as WHTAmount, 'A' as Trans_Type "; 
			   
//$querysales = $querysales." From StkTransaction Stk ";
$querysales = $querysales." From SalesDt  ";

if ($packitem == 1) {				
	$querysales = $querysales.				
				" Left join ( select packdt.item_code,sum(ifnull(packdt_quantity,1)) QtyPack ".
				"             from packdt, items ".
				"             where packdt.item_code=items.item_code and item_pack=1 group by item_code ".
				"            ) QPackdt on if(SalesDt.Item_CodePacked='', SalesDt.Item_Code, SalesDt.Item_CodePacked)= QPackdt.Item_Code ";
}
		  
$querysales = $querysales.		  
				//" Inner Join SalesDt  on Stk.Transaction_ID = SalesDt.SaleDt_ID  ".
				" Inner Join Sales on SalesDt.Sale_ID = Sales.Sale_ID ".
				" Inner Join DeliveryDt On Salesdt.RelatedDt_ID = DeliveryDt.DeliveryDt_ID ".
				" Inner Join Items on if($packitem=1, if(SalesDt.Item_CodePacked='', SalesDt.Item_Code, SalesDt.Item_CodePacked), SalesDt.Item_Code) = Items.Item_Code ".
				" Inner Join Clients on Clients.Ledger_Number = Sales.Client_Code ".
				" Left Join Suppliers on Items.Ledger_Number = Suppliers.Ledger_Number ".
				" Left Join Grouping on Items.Group_Code = Grouping.Group_Code ".
				" Left Join SubGroup on Items.SubGroup_Code = SubGroup.SubGroup_Code ".
				" Left Join Category on Items.Category_Code = Category.Category_Code ".
				" Left Join Salesmen on Sales.Salesman_Code = Salesmen.Ledger_Number ".
				" Left Join Area on Area.Area_Code = Clients.Area_Code ".
				" Left Join Costcent on Costcent.Costcent_Code = SalesDt.Costcenter_code ".
				" Left Join Project on Project.Project_Code = SalesDt.Project_Code ".
				" Left Join Costcent As Costcent1 on Costcent1.Costcent_Code = Clients.CostCenter_Code ".
				" Left Join Project As Project1 on Project1.Project_Code = Clients.Project_Code ".
				" Left Join Warehouse As Warehouse1 on Warehouse1.Warehouse_Code = SalesDt.Warehouse_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,'%') ";							 

if ($prtqtyexist == 1) {							 
	$querysales= $querysales.
						  " Inner Join (  ".
						  "               Select Stk.Item_Code, Stk.Warehouse_code, Sum((ifNull(quantityproducein,0) + ifNull(quantityentered,0) - ifNull(quantityproduceout,0) - ifNull(quantitydelivered,0))) As QuantityExists  ".
						  "               From StkTransaction Stk ".
						  "               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Stk.Transaction_Date,'%Y-%m-%d')) ".
						  "               And Stk.item_code between ifNull(".$fromitem.",Stk.item_code) and ifNull(". $toitem.",Stk.item_code) ".
						  "               And ifNull(Stk.project_code,'-1')   Like Concat( ifNull(".$fromproject.",ifNull(Stk.project_code,'-1')),'%')  ".
						  "               And ifNull(Stk.Costcent_Code,'-1')  Like Concat(ifNull(".$fromcostcent.",ifNull(Stk.Costcent_Code,'-1')),'%')  ".
						  "               And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
						  "               And (($Module_Grn=1 and Stk.Transaction_Type <> 'PI') or ($Module_Grn=0 and 1=1)) ".
						  "               Group By Stk.Item_Code, Stk.Warehouse_code ".
						  "             ) As QQtyExists on SalesDt.Item_Code = QQtyExists.Item_Code and SalesDt.Warehouse_Code = QQtyExists.Warehouse_Code  ";
}

$querysales= $querysales. " Where (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 ifNull(Items.Category_Code,'-1') between ifNull(". $fromcategory .",ifNull(Items.Category_Code,'-1')) and ifNull(". $tocategory.",ifNull(Items.Category_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')   Like Concat( ifNull(".$fromarea.",ifNull(Clients.area_code,'-1')),'%')  ".
						  " And ifNull(Clients.Client_Rating,'-1') = ifNull(". $cltrating .",ifNull(Clients.Client_Rating,'-1'))  ".
						  " And (($promprint=1 and ifNull(SaleDt_Promotion,0) = 1) Or ($promprint=2 and ifNull(SaleDt_Promotion,0) = 0) Or ($promprint=3 and 1 = 1))  ".
						  " And (($zeroprint=1 and ifNull(SalesDt.SaleDt_Price,0) = 0 and ifNull(SaleDt_Promotion,0) = 0) Or ($zeroprint=2 and ifNull(SalesDt.SaleDt_Price,0) != 0) Or ($zeroprint=3 and 1 = 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 (($vatprint=1 and ifNull(Clients.Client_VAT,0) = 1) or ($vatprint=2 and ifNull(Clients.Client_VAT,0) = 0) or ($vatprint=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)) 
							And Items.Item_showInSalesReport = 1";
if($Module_expiredate==1 && $edatechk == 1)
	$querysales=$querysales." and date_format(SaleDt_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(SaleDt_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(SaleDt_ExpireDate,'%Y-%m-%d')) ";
		
if ($showsales == 1 && $showretsales == 1)
	$querysales= $querysales." And SalesDt.Journal_Type in ('SI','SR') ";
else if ($showsales == 1)
	$querysales= $querysales." And SalesDt.Journal_Type = 'SI' ";
else if ($showretsales == 1)
	$querysales= $querysales." And SalesDt.Journal_Type = 'SR' ";
						  
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']."')  ";  

if ($showDBN == 1){
	$querysales .=  " union 
					Select trans.Trans_Reference As Reference, Date_Format(trans.Trans_Date,'%d/%m/%Y') As StkDate, trans.Trans_Date As OrderDate, if($prtdt=1, if($masterby=1, transdt.Ledger_number, null),'') As MasterCode, ".
			    " if($prtdt=1, if($masterby=1, Clients.Ledger_Name, null),'') As MasterDescription , if($prtsubdt=1, if($masterby=1, trans_type, transdt.Ledger_number), '') As DetailCode, ".
				" if($prtsubdt=1, if($masterby=1, concat('Sales From ',trans_type,' REF ',trans.Trans_Reference), Clients.Ledger_Name), '') As DetailDescription , transdt.Ledger_number As ClientCode, Clients.Ledger_Name As ClientName, ".
				" trans_type As ItemCode, concat('Sales From ',trans_type) As ItemDescription, null as ItemWeight, null as Item_UnitSalesDesc, null as Item_UnitPurchaseDesc, null As SalesmanCode,null As SalesmanName, ".
				" null As SupplierCode,null As SupplierName, ifNull(Costcent.Parent_Code, Costcent.Costcent_Code) As ParentCostcenterCode,Costcent.Costcent_Name As ParentCostcenterName, ".
				" trans.Costcent_Code As CostcenterCode,Costcent.Costcent_Name As CostcenterName, ifNull(Project.Parent_Code, Project.Project_Code) As ParentProjectCode, Project.Project_Name As ParentProjectName, ".
				" trans.Project_Code As ProjectCode,Project.Project_Name As ProjectName, null As ParentGroupCode, null As ParentGroupName, null As GroupCode, null As GroupName, ".
				" null As ParentSubGroupCode, null As ParentSubGroupName, null As SubGroupCode, null As SubGroupName, ifNull(Area.Parent_Code, Clients.Area_Code) As ParentAreaCode, Area.Area_Name As ParentAreaName, ".
				" Clients.Area_Code As AreaCode ,Area.Area_Name As AreaName, null As CategoryCode, null As CategoryName, Clients.ProfitCenter_Code As ProfitCenter, Clients.ProfitCenter_Code As ProfitGroup, ".
				" Clients.Client_BusinessType As BusinessType, Clients.Project_Code As MasterProject, Clients.CostCenter_Code As MasterCostcent, ".
				" ifNull(Project1.Parent_Code, Clients.Project_Code) As ParentMasterProject, ifNull(Costcent1.Parent_Code, Clients.CostCenter_Code) As ParentMasterCostcent, null As WarehouseCode,".
				" null As ParentWarehouseCode, if(upper($curr)='".$Base1."', '".$Base1."', if(upper($curr)='".$Base2."', '".$Base2."', transdt.Currency_code))  As Currency,  0 As DeliveryDt_discountper, ".
				" if($showsellprice != 1, if(upper($curr)='".$Base1."',Transdt_Amount1,if(upper($curr)='".$Base2."',Transdt_Amount2, Transdt_Amount)) , 0) As UnitPrice, 0 TransportAmount, ".
				" 0 As ItemVat, 0 as ItemTax1, 0 as ItemTax2, 0 as ItemTax3, 0 as ItemTax4, 0 as ItemTax5, 0 As DiscountAmount, 0 as MeanCostAmount, if (trans_type='DV',1,-1) As QtyNetSold, Null As QtyExists,
				if (trans_type='DV',1,0) As QtySold, 0 As Qty2Sold, if (trans_type='CV',1,0) As QtyReturn,";
	if ($packitem == 1) 				
		$querysales .=  " null as Item_CodePacked, 1 QtyPack, ";
			   		
		$querysales .= "  null as Item_ExpireDate, null as WHTAmount, Trans_Type ".
				" from transdt ".
				" inner join trans on trans.trans_id = transdt.trans_id ".
				" Inner Join Clients on Clients.Ledger_Number = transdt.Ledger_Number ".
				" Left Join Area on Area.Area_Code = Clients.Area_Code ".
				" Left Join Costcent on Costcent.Costcent_Code = trans.Costcent_Code ".
				" Left Join Project on Project.Project_Code = trans.Project_Code ".
				" Left Join Costcent As Costcent1 on Costcent1.Costcent_Code = Clients.CostCenter_Code ".
				" Left Join Project As Project1 on Project1.Project_Code = Clients.Project_Code ";
				
	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
	  $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 trans.project_code like concat(Q1.project_code,'%')  ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
	  $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 trans.Costcent_Code like concat(Q2.costcent_code,'%')  ";			
										
	$querysales .= " Where (Trans_Reference Is Not Null And Trans_Reference != '') And trans_type in ('DV', 'CV')  ".
				   " And Date_format(trans.Trans_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(trans.Trans_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(trans.Trans_Date,'%Y-%m-%d'))  ".
					" And transdt.Ledger_number between ifNull(".$fromclient.",transdt.Ledger_number) and ifNull(". $toclient.",transdt.Ledger_number) ".
					" And ifNull(trans.project_code,'-1')   Like Concat(ifNull(".$fromproject.",ifNull(trans.project_code,'-1')),'%')  ".
					" And ifNull(trans.Costcent_Code,'-1')  Like Concat(ifNull(".$fromcostcent.",ifNull(trans.Costcent_Code,'-1')),'%')  ".
					" And ifNull(Clients.area_code,'-1')     Like Concat( 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)) ";

	 
if ($subproj != 'Null')
	$querysales .= " And ifNull(trans.project_code,'-1')  Like ".$subproj; 
if ($subcostcent != 'Null')
	$querysales .= " And ifNull(trans.Costcent_Code,'-1')  Like ".$subcostcent;  
							
}
$querysales= $querysales." ) Q1 ";

if ($packitem == 1) {
    $querysales= $querysales." ) Q3 ".
	                               " Group By Groupby1Code, Groupby2Code, Groupby3Code, MasterCode, DetailCode, WarehouseCode, Reference, StkDate ";
}

if ($option == 1) {
    $querysales= $querysales." ) Q2 ".
	                               " Group By Groupby1Code, Groupby2Code, Groupby3Code, MasterCode, DetailCode ";
}

if ($showDBN == 1)
	$querysales= $querysales." Order by Groupby1Code, Groupby2Code, Groupby3Code, MasterCode, Trans_Type, DetailCode, OrderDate  ";				
else 
	$querysales= $querysales." Order by Groupby1Code, Groupby2Code, Groupby3Code, MasterCode, DetailCode, OrderDate  ";				
	//echo $querysales;




// Delivery Query
$querydelivery = '';
if ($option == 1) {
 
    $querydelivery = 
				" Select Reference, StkDate, MasterCode, MasterDescription, DetailCode, DetailDescription, ClientCode, ClientName, ".
				" ItemCode, ItemDescription, WarehouseCode, Currency, Groupby3Code, Groupby3Name, DeliveryDt_discountper, ".
				" (Sum(SellAmount)/Sum(QtyNetSold)) As UnitPrice, Sum(VatAmount) As VatAmount, Sum(DiscountAmount) As DiscountAmount, (Sum(TotalMeanCost)/Sum(QtyNetSold))  MeanCostAmount, ".
				" Sum(SellAmount) As SellAmount, Sum(TotalMeanCost) As TotalMeanCost, (Sum(SellAmount) - Sum(TotalMeanCost)) As ProfitAmount, ".
				" if($prfmarby=2 and (Sum(TotalMeanCost)/Sum(QtyNetSold))=0, 0, (((Sum(SellAmount) - Sum(TotalMeanCost)) / if($prfmarby=1,Sum(SellAmount),Sum(TotalMeanCost))) * 100)) As ProfitMargin, ".
				" Round(Sum(QtyNetSold),2) As QtyNetSold, QtyExists, Round(Sum(QtySold),2) As QtySold, Round(Sum(QtyReturn),2) As QtyReturn, ".
				" Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, ItemWeight, Item_UnitSalesDesc, Round(Sum(ItemWeight*QtyNetSold),2) as TotalWeight, OrderDate, ".
				" Sum(Tax1Amount) As Tax1Amount, Sum(Tax2Amount) As Tax2Amount, Sum(Tax3Amount) As Tax3Amount, Sum(Tax4Amount) As Tax4Amount, Sum(Tax5Amount) As Tax5Amount, Item_UnitPurchaseDesc, Round(Sum(Qty2Sold),2) As Qty2Sold  ".
                " ,TransportAmount , Trans_Type ".
				" From ( ";
}


if ($packitem == 1) {
    $querydelivery = $querydelivery.
				" Select Reference, StkDate, MasterCode, MasterDescription, DetailCode, DetailDescription, ClientCode, ClientName, ".
				" ItemCode, ItemDescription, WarehouseCode, Currency, Groupby3Code, Groupby3Name, DeliveryDt_discountper, ".
				" Sum(UnitPrice) As UnitPrice, Sum(VatAmount) As VatAmount, Sum(DiscountAmount) As DiscountAmount, Sum(MeanCostAmount)  MeanCostAmount, ".
				" Sum(SellAmount) As SellAmount, Sum(TotalMeanCost) As TotalMeanCost, ".
				" Sum(ProfitAmount) As ProfitAmount, ".
				" if($prfmarby=2 and Sum(TotalMeanCost)=0, 0, (((Sum(SellAmount) - Sum(TotalMeanCost)) / if($prfmarby=1,Sum(SellAmount),Sum(TotalMeanCost))) * 100)) As ProfitMargin, ".
				" Sum(if(Item_CodePacked='', QtyNetSold, QtyNetSold/QtyPack)) As QtyNetSold, QtyExists, ".
				" Sum(if(Item_CodePacked='', QtySold, QtySold/QtyPack)) As QtySold, ".
				" Sum(if(Item_CodePacked='', QtyReturn, QtyReturn/QtyPack)) As QtyReturn, ".
				" Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, ItemWeight, Item_UnitSalesDesc, Sum(if(Item_CodePacked='', (ItemWeight*QtyNetSold), ItemWeight*QtyNetSold/QtyPack)) as TotalWeight, OrderDate, ".
				" Sum(Tax1Amount) As Tax1Amount, Sum(Tax2Amount) As Tax2Amount, Sum(Tax3Amount) As Tax3Amount, Sum(Tax4Amount) As Tax4Amount, Sum(Tax5Amount) As Tax5Amount, Item_UnitPurchaseDesc, Sum(if(Item_CodePacked='', Qty2Sold, Qty2Sold/QtyPack)) As Qty2Sold  ".
                " ,TransportAmount , Trans_Type".
				" From ( ";

}

$querydelivery = $querydelivery.
				" Select Reference, StkDate, MasterCode, MasterDescription, DetailCode, DetailDescription, ClientCode, ClientName, ".
				" ItemCode, ItemDescription, WarehouseCode, Currency, ";

$querydelivery = $querydelivery.$QryGroupby3Code . $QryGroupby3Name;				
				/*" ifNull(if($groupby=2, SupplierCode, if($groupby=3, GroupCode, if($groupby=4, SubGroupCode, if($groupby=5, CategoryCode, ".
			    " if($groupby=6, SalesmanCode, if($groupby=7, ProfitCenter, if($groupby=8, ProfitGroup, if($groupby=9, CostcenterCode, ".
				" if($groupby=10, ProjectCode, if($groupby=11, AreaCode, if($groupby=12, BusinessType, ''))))))))))), -1) As GroupbyCode, ".
				" ifNull(if($groupby=2, SupplierName, if($groupby=3, GroupName, if($groupby=4, SubGroupName, if($groupby=5, CategoryName, ".
			    " if($groupby=6, SalesmanName, if($groupby=7, ProfitCenter, if($groupby=8, ProfitGroup, if($groupby=9, CostcenterName, ".
				" if($groupby=10, ProjectName, if($groupby=11, AreaName, if($groupby=12, '', ''))))))))))), 'None') As GroupbyName, ".
*/
$querydelivery = $querydelivery.				
				" DeliveryDt_discountper, UnitPrice, ((ItemVat*UnitPrice*QtyNetSold)/100) As VatAmount, DiscountAmount, MeanCostAmount, ".
				" (UnitPrice*QtyNetSold) As SellAmount, (MeanCostAmount*QtyNetSold) As TotalMeanCost, ".
				" ((UnitPrice*QtyNetSold) - (MeanCostAmount*QtyNetSold)) As ProfitAmount, ".
				" if($prfmarby=2 and (MeanCostAmount*QtyNetSold)=0, 0, ((((UnitPrice*QtyNetSold) - (MeanCostAmount*QtyNetSold)) / if($prfmarby=1,(UnitPrice*QtyNetSold),(MeanCostAmount*QtyNetSold))) * 100)) As ProfitMargin, ".
				" QtyNetSold, QtyExists, QtySold, QtyReturn, ";
				
$querydelivery = $querydelivery.$QryGroupby1Code . $QryGroupby1Name.
                                $QryGroupby2Code . $QryGroupby2Name;
								
$querydelivery = $querydelivery.", ItemWeight, Item_UnitSalesDesc, (ItemWeight*QtyNetSold) as TotalWeight ";
$querydelivery = $querydelivery.", OrderDate, ((ItemTax1*UnitPrice*QtyNetSold)/100) As Tax1Amount, ((ItemTax2*UnitPrice*QtyNetSold)/100) As Tax2Amount, ((ItemTax3*UnitPrice*QtyNetSold)/100) As Tax3Amount ".
							    ", ((ItemTax4*UnitPrice*QtyNetSold)/100) As Tax4Amount, ((ItemTax5*UnitPrice*QtyNetSold)/100) As Tax5Amount, Item_UnitPurchaseDesc, Qty2Sold ";
if ($packitem == 1) 				
	$querydelivery = $querydelivery.", Item_CodePacked, QtyPack ";
	
	$querydelivery = $querydelivery."	,TransportAmount, Trans_Type  ";
	
$querydelivery = $querydelivery.
				" From ( ".
				" Select Deliveries.Delivery_Reference As Reference, Date_Format(Deliveries.Delivery_Date,'%d/%m/%Y') As StkDate, Deliveries.Delivery_Date As OrderDate, ".
			    " if($prtdt=1, if($masterby=1, Deliveries.Client_Code, if($packitem=1, if(DeliveryDt.Item_CodePacked='', DeliveryDt.Item_Code, DeliveryDt.Item_CodePacked), DeliveryDt.Item_Code)),'') As MasterCode, ".
				" if($prtdt=1, if($masterby=1, Clients.Ledger_Name, Items.Item_Description),'') As MasterDescription , ".
				" if($prtsubdt=1, if($masterby=1, if($packitem=1, if(DeliveryDt.Item_CodePacked='', DeliveryDt.Item_Code, DeliveryDt.Item_CodePacked), DeliveryDt.Item_Code), Deliveries.Client_Code), '') As DetailCode, ".
				" if($prtsubdt=1, if($masterby=1, Items.Item_Description, Clients.Ledger_Name), '') As DetailDescription , ".
				" Deliveries.Client_Code As ClientCode, Clients.Ledger_Name As ClientName, ".
				" if($packitem=1, if(DeliveryDt.Item_CodePacked='', DeliveryDt.Item_Code, DeliveryDt.Item_CodePacked), DeliveryDt.Item_Code) As ItemCode, Items.Item_Description As ItemDescription, ".
				" Items.Item_Weight as ItemWeight, Items.Item_UnitSalesDesc, Items.Item_UnitPurchaseDesc,  ".
				" Deliveries.Salesman_Code As SalesmanCode,Salesmen.Ledger_Name As SalesmanName, ".
				" Items.Ledger_Number As SupplierCode,Suppliers.Ledger_Name As SupplierName, ".
				" ifNull(Costcent.Parent_Code, Costcent.Costcent_Code) As ParentCostcenterCode,Costcent.Costcent_Name As ParentCostcenterName, ".
				" DeliveryDt.Costcent_Code As CostcenterCode,Costcent.Costcent_Name As CostcenterName, ".
				" ifNull(Project.Parent_Code, Project.Project_Code) As ParentProjectCode, Project.Project_Name As ParentProjectName, ".
				" DeliveryDt.Project_Code As ProjectCode,Project.Project_Name As ProjectName, ".
				" ifNull(Grouping.Parent_Code, Items.Group_Code) As ParentGroupCode, Grouping.Group_Name As ParentGroupName, ".
				" Items.Group_Code As GroupCode,Grouping.Group_Name As GroupName, ".
				" ifNull(Subgroup.Parent_Code, Items.SubGroup_Code) As ParentSubGroupCode, Subgroup.Subgroup_Name As ParentSubGroupName, ".
				" Items.SubGroup_Code As SubGroupCode,Subgroup.Subgroup_Name As SubGroupName, ".
				" ifNull(Area.Parent_Code, Clients.Area_Code) As ParentAreaCode, Area.Area_Name As ParentAreaName, ".
				" Clients.Area_Code As AreaCode ,Area.Area_Name As AreaName, ".
				" Items.Category_Code As CategoryCode, Category.Category_Name As CategoryName, ".
				" Clients.ProfitCenter_Code As ProfitCenter,Concat(Clients.ProfitCenter_Code,' and ',Items.Group_Code) As ProfitGroup, ".
				" Clients.Client_BusinessType As BusinessType, Clients.Project_Code As MasterProject, Clients.CostCenter_Code As MasterCostcent, ".
				" ifNull(Project1.Parent_Code, Clients.Project_Code) As ParentMasterProject, ifNull(Costcent1.Parent_Code, Clients.CostCenter_Code) As ParentMasterCostcent, ".
				" DeliveryDt.Warehouse_Code As WarehouseCode, ifNull(Warehouse1.Warehouse_Code, DeliveryDt.Warehouse_Code) As ParentWarehouseCode,  ".
				" if(upper($curr)='".$Base1."', '".$Base1."', if(upper($curr)='".$Base2."', '".$Base2."', Deliveries.Currency_Code))  As Currency, ".
				" ifNull(DeliveryDt.DeliveryDt_discountper, 0) As DeliveryDt_discountper,  ".
				//" if($pricettc=1, if(ifNull(DeliveryDt.DeliveryDt_PriceTTC,0)=0, 0,  ".
				//" ifNull( (((if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_PriceTTCBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_PriceTTCBase2, DeliveryDt.DeliveryDt_PriceTTC)) - ".
				//"         (ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_PriceTTCBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_PriceTTCBase2, DeliveryDt.DeliveryDt_PriceTTC)),0) * ifNull(DeliveryDt.DeliveryDt_discountper, 0)/100))*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))/DeliveryDt.DeliveryDt_Quantity) ,0)),  ".
				" if($showsellprice != 1, ".
				" 		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))*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_BonusBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_BonusBase2,DeliveryDt.DeliveryDt_BonusAmount)),0))/DeliveryDt.DeliveryDt_Quantity) ,0)),  ".
				"  		if($sellprice = 1, if(upper($curr)='".$Base1."', Items.Item_SellingPrice1Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice1Base2, Items.Item_SellingPrice1)), ".
				" 		if($sellprice = 2, if(upper($curr)='".$Base1."', Items.Item_SellingPrice2Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice2Base2, Items.Item_SellingPrice2)), ".
				" 		if($sellprice = 3, if(upper($curr)='".$Base1."', Items.Item_SellingPrice3Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice3Base2, Items.Item_SellingPrice3)), ".
				" 		if($sellprice = 4, if(upper($curr)='".$Base1."', Items.Item_SellingPrice4Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice4Base2, Items.Item_SellingPrice4)), ".
				" 		if($sellprice = 5, if(upper($curr)='".$Base1."', Items.Item_SellingPrice5Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice5Base2, Items.Item_SellingPrice5)), ".
				" 		if($sellprice = 6, if(upper($curr)='".$Base1."', Items.Item_SellingPrice6Base1, if(upper($curr)='".$Base2."', Items.Item_SellingPrice6Base2, Items.Item_SellingPrice6)), 0)))))) ".
				"    )  As UnitPrice, ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_TransportAmountBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_TransportAmountBase2,DeliveryDt.DeliveryDt_TransportAmount)),0) TransportAmount, ". 
				" if(ifNull(Delivery_VAT,0) > 0, DeliveryDt.Item_Vat, 0) As ItemVat, ifNull(DeliveryDt.Item_tax1,0) as ItemTax1, ifNull(DeliveryDt.Item_tax2,0) as ItemTax2, ifNull(DeliveryDt.Item_tax3,0) as ItemTax3, ifNull(DeliveryDt.Item_tax4,0) as ItemTax4, ifNull(DeliveryDt.Item_tax5,0) as ItemTax5, ".
				" if($pricettc=1, ((ifNull(if(upper($curr)='".$Base1."',ifNull(DeliveryDt.DeliveryDt_PriceTTCBase1,0),if(upper($curr)='".$Base2."',ifNull(DeliveryDt.DeliveryDt_PriceTTCBase2,0), ifNull(DeliveryDt.DeliveryDt_PriceTTC,0))),0) * ifNull(DeliveryDt.DeliveryDt_discountper, 0)/100)*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."',ifNull(DeliveryDt.DeliveryDt_PriceBase1,0),if(upper($curr)='".$Base2."',ifNull(DeliveryDt.DeliveryDt_PriceBase2,0), ifNull(DeliveryDt.DeliveryDt_Price,0))),0) * ifNull(DeliveryDt.DeliveryDt_discountper, 0)/100)*DeliveryDt.DeliveryDt_Quantity + ".
				"                   ifNull(if(upper($curr)='".$Base1."',DeliveryDt.DeliveryDt_DiscountBase1,if(upper($curr)='".$Base2."',DeliveryDt.DeliveryDt_DiscountBase2,DeliveryDt.DeliveryDt_DiscountAmount)),0)) ) As DiscountAmount,  ";


//$querydelivery= $querydelivery." ifNull(MeanCostCur(DeliveryDt.Item_Code, concat(".$todate.", ' 23:59:59'), if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), Deliveries.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";
if ($module_chargesInTransfer == 1  && $fromwh != ''){
	$querydelivery= $querydelivery." ifNull(MeanCostCurByWH(DeliveryDt.Item_Code, concat(date_format(Deliveries.Delivery_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), Deliveries.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code )),'$fromwh'),0) MeanCostAmount, ";
}
else {
	if ($updmeancost == 1)
		$querydelivery= $querydelivery." ifNull(MeanCostCur(DeliveryDt.Item_Code, concat(date_format(Deliveries.Delivery_Date,'%Y-%m-%d'), ' 23:59:59'), if(upper($curr)='".$Base1."', 1,if(upper($curr)='".$Base2."',2, 1)), Deliveries.Currency_Code, if(upper($curr)='".$Base1."', '',if(upper($curr)='".$Base2."','',items.currency_code ))),0) MeanCostAmount, ";
	else
		$querydelivery= $querydelivery."  if(upper($curr)='".$Base1."', ifNull(DeliveryDt_CostBase1,0), if(upper($curr)='".$Base2."', ifNull(DeliveryDt_CostBase2,0), ifNull(DeliveryDt_Cost,0))) MeanCostAmount, ";
}
$querydelivery= $querydelivery.	
				" if(DeliveryDt.Journal_Type = 'DI',DeliveryDt.DeliveryDt_Quantity, (-1)*DeliveryDt.DeliveryDt_Quantity) As QtyNetSold, ";
				
if ($prtqtyexist == 1) {				
	$querydelivery= $querydelivery.	" QQtyExists.QuantityExists As QtyExists, ";
} else {
	$querydelivery= $querydelivery.	" Null As QtyExists, ";
}

$querydelivery= $querydelivery.					
				" if(DeliveryDt.Journal_Type = 'DI',DeliveryDt.DeliveryDt_Quantity,0) As QtySold, ".
				" if(DeliveryDt.Journal_Type = 'DI',DeliveryDt.Item_Unit2Qty,0) As Qty2Sold, ".
				" if(DeliveryDt.Journal_Type = 'DR',Abs(DeliveryDt.DeliveryDt_Quantity),0) As QtyReturn ";
				
if ($packitem == 1) 				
	$querydelivery= $querydelivery.", DeliveryDt.Item_CodePacked, ifNull(QtyPack, 1) QtyPack ";
			   
$querydelivery= $querydelivery." , DeliveryDt_ExpireDate as Item_ExpireDate, 'A' as Trans_Type ";

$querydelivery= $querydelivery." From DeliveryDt  ";
				
if ($packitem == 1) {				
	$querydelivery= $querydelivery.				
				" Left join ( select packdt.item_code, sum(ifnull(packdt_quantity,1)) QtyPack ".
				"             from packdt, items ".
				"             where packdt.item_code=items.item_code and item_pack=1 group by item_code ".
				"            ) QPackdt on if(DeliveryDt.Item_CodePacked='', DeliveryDt.Item_Code, DeliveryDt.Item_CodePacked)= QPackdt.Item_Code ";
}

$querydelivery= $querydelivery.				
				//" Inner Join DeliveryDt  on Stk.Transaction_ID = DeliveryDt.DeliveryDt_ID  ".
				" Inner Join Deliveries on DeliveryDt.Delivery_ID = Deliveries.Delivery_ID ".
				" Inner Join Items on if($packitem=1, if(DeliveryDt.Item_CodePacked='', DeliveryDt.Item_Code, DeliveryDt.Item_CodePacked), DeliveryDt.Item_Code) = Items.Item_Code ".
				" Inner Join Clients on Clients.Ledger_Number = Deliveries.Client_Code ".
				" Left Join Suppliers on Items.Ledger_Number = Suppliers.Ledger_Number ".
				" Left Join Grouping on Items.Group_Code = Grouping.Group_Code ".
				" Left Join SubGroup on Items.SubGroup_Code = SubGroup.SubGroup_Code ".
				" Left Join Category on Items.Category_Code = Category.Category_Code ".
				" Left Join Salesmen on Deliveries.Salesman_Code = Salesmen.Ledger_Number ".
				" Left Join Area on Area.Area_Code = Clients.Area_Code ".
				" Left Join Costcent on Costcent.Costcent_Code = DeliveryDt.Costcent_Code ".
				" Left Join Project on Project.Project_Code = DeliveryDt.Project_Code ".
				" Left Join Costcent As Costcent1 on Costcent1.Costcent_Code = Clients.CostCenter_Code ".
				" Left Join Project As Project1 on Project1.Project_Code = Clients.Project_Code ".
				" Left Join Warehouse As Warehouse1 on Warehouse1.Warehouse_Code = DeliveryDt.Warehouse_Code ";
						  
if ($projectexist >	0 && $FI_RepRestrictProject == 1)
  $querydelivery= $querydelivery." 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)
  $querydelivery= $querydelivery." 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,'%')  ";							 
						   

if ($prtqtyexist == 1) {
	$querydelivery= $querydelivery.
						  " Inner Join (  ".
						  "               Select Stk.Item_Code, Stk.Warehouse_code, Sum((ifNull(quantityproducein,0) + ifNull(quantityentered,0) - ifNull(quantityproduceout,0) - ifNull(quantitydelivered,0))) As QuantityExists  ".
						  "               From StkTransaction Stk ".
						  "               Where Date_Format(Stk.Transaction_Date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Stk.Transaction_Date,'%Y-%m-%d')) ".
						  "               And Stk.item_code between ifNull(".$fromitem.",Stk.item_code) and ifNull(". $toitem.",Stk.item_code) ".
						  "				  And ifNull(Stk.project_code,'-1')   Like Concat( ifNull(".$fromproject.",ifNull(Stk.project_code,'-1')),'%')  ".
						  " 			  And ifNull(Stk.Costcent_Code,'-1')  Like Concat( ifNull(".$fromcostcent.",ifNull(Stk.Costcent_Code,'-1')),'%')  ".
						  "				  And ifNull(Stk.warehouse_code,'-1') Like Concat( ifNull(". $fromwarehouse .",ifNull(Stk.warehouse_code,'-1')),'%')  ".
						  "               And (($Module_Grn=1 and Stk.Transaction_Type <> 'PI') or ($Module_Grn=0 and 1=1)) ".
						  "               Group By Stk.Item_Code, Stk.Warehouse_code ".
						  "             ) As QQtyExists on DeliveryDt.Item_Code = QQtyExists.Item_Code and DeliveryDt.Warehouse_Code = QQtyExists.Warehouse_Code  ";
}

$querydelivery= $querydelivery.						  
						  " Where (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 ifNull(Items.Category_Code,'-1') between ifNull(". $fromcategory .",ifNull(Items.Category_Code,'-1')) and ifNull(". $tocategory.",ifNull(Items.Category_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')     Like Concat( ifNull(".$fromarea.",ifNull(Clients.area_code,'-1')),'%')  ".
						  " And ifNull(Clients.Client_Rating,'-1') = ifNull(". $cltrating .",ifNull(Clients.Client_Rating,'-1'))  ".
						  " And (($promprint=1 and ifNull(DeliveryDt_Promotion,0) = 1) Or ($promprint=2 and ifNull(DeliveryDt_Promotion,0) = 0) Or ($promprint=3 and 1 = 1))  ".
						  " And (($zeroprint=1 and ifNull(DeliveryDt.DeliveryDt_Price,0) = 0 and ifNull(DeliveryDt_Promotion,0) = 0) Or ($zeroprint=2 and ifNull(DeliveryDt.DeliveryDt_Price,0) != 0) Or ($zeroprint=3 and 1 = 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 (($vatprint=1 and ifNull(Clients.Client_VAT,0) = 1) or ($vatprint=2 and ifNull(Clients.Client_VAT,0) = 0) or ($vatprint=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)) 
							And Items.Item_showInSalesReport = 1";
if($fromsupplier1 != '' && $tosupplier1 != '' )
	$querydelivery= $querydelivery.	" And Items.item_code in (select item_code from purchasesdt, purchases where purchasesdt.purchase_id = purchases.purchase_id and 
											Supplier_code1 BETWEEN  '$fromsupplier1' and '$tosupplier1' and purchases.purchase_date <= $todate) ";	
											// $querydelivery= $querydelivery.	" And Items.ledger_number1 between  '$fromsupplier1' and '$tosupplier1' ";

if($Module_expiredate==1 && $edatechk == 1)
	$querydelivery=$querydelivery." and date_format(DeliveryDt_ExpireDate,'%Y-%m-%d') between ifNull(". $fromedate.",date_format(DeliveryDt_ExpireDate,'%Y-%m-%d')) and ifNull(". $toedate.",date_format(DeliveryDt_ExpireDate,'%Y-%m-%d')) ";
						  
if ($showsales == 1 && $showretsales == 1)
	$querydelivery= $querydelivery." And DeliveryDt.Journal_Type in ('DI','DR') ";
else if ($showsales == 1)
	$querydelivery= $querydelivery." And DeliveryDt.Journal_Type = 'DI' ";
else if ($showretsales == 1)
	$querydelivery= $querydelivery." And DeliveryDt.Journal_Type = 'DR' ";
				
if ($subproj != 'Null')
	$querydelivery= $querydelivery." And ifNull(DeliveryDt.project_code,'-1')  Like ".$subproj; 
if ($subcostcent != 'Null')
	$querydelivery= $querydelivery." And ifNull(DeliveryDt.Costcent_Code,'-1')  Like ".$subcostcent;  

if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
	$querydelivery= $querydelivery." And DeliveryDt.warehouse_code In (select distinct warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  
if ($groupexist > 0)
	$querydelivery= $querydelivery." And Items.group_code In (select distinct group_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."')  ";  

if ($cashtype != '')
	$querydelivery= $querydelivery." and upper(deliveries.delivery_cashType) = upper('$cashtype') ";


// read from transdt
if ($showDBN == 1){
	$querydelivery .= " union 
					Select trans.Trans_Reference As Reference, Date_Format(trans.Trans_Date,'%d/%m/%Y') As StkDate, trans.Trans_Date As OrderDate, if($prtdt=1, if($masterby=1, transdt.Ledger_number, null),'') As MasterCode, ".
			    " if($prtdt=1, if($masterby=1, Clients.Ledger_Name, null),'') As MasterDescription , if($prtsubdt=1, if($masterby=1, trans_type, transdt.Ledger_number), '') As DetailCode, ".
				" if($prtsubdt=1, if($masterby=1, concat('Sales From ',trans_type,' REF ',trans.Trans_Reference), Clients.Ledger_Name), '') As DetailDescription , transdt.Ledger_number As ClientCode, Clients.Ledger_Name As ClientName, ".
				" trans_type As ItemCode, concat('Sales From ',trans_type) As ItemDescription, null as ItemWeight, null as Item_UnitSalesDesc, null as Item_UnitPurchaseDesc, null As SalesmanCode,null As SalesmanName, ".
				" null As SupplierCode,null As SupplierName, ifNull(Costcent.Parent_Code, Costcent.Costcent_Code) As ParentCostcenterCode,Costcent.Costcent_Name As ParentCostcenterName, ".
				" trans.Costcent_Code As CostcenterCode,Costcent.Costcent_Name As CostcenterName, ifNull(Project.Parent_Code, Project.Project_Code) As ParentProjectCode, Project.Project_Name As ParentProjectName, ".
				" trans.Project_Code As ProjectCode,Project.Project_Name As ProjectName, null As ParentGroupCode, null As ParentGroupName, null As GroupCode, null As GroupName, ".
				" null As ParentSubGroupCode, null As ParentSubGroupName, null As SubGroupCode, null As SubGroupName, ifNull(Area.Parent_Code, Clients.Area_Code) As ParentAreaCode, Area.Area_Name As ParentAreaName, ".
				" Clients.Area_Code As AreaCode ,Area.Area_Name As AreaName, null As CategoryCode, null As CategoryName, Clients.ProfitCenter_Code As ProfitCenter, Clients.ProfitCenter_Code As ProfitGroup, ".
				" Clients.Client_BusinessType As BusinessType, Clients.Project_Code As MasterProject, Clients.CostCenter_Code As MasterCostcent, ".
				" ifNull(Project1.Parent_Code, Clients.Project_Code) As ParentMasterProject, ifNull(Costcent1.Parent_Code, Clients.CostCenter_Code) As ParentMasterCostcent, null As WarehouseCode,".
				" null As ParentWarehouseCode, if(upper($curr)='".$Base1."', '".$Base1."', if(upper($curr)='".$Base2."', '".$Base2."', transdt.Currency_code))  As Currency,  0 As DeliveryDt_discountper, ".
				" if($showsellprice != 1, if(upper($curr)='".$Base1."',Transdt_Amount1,if(upper($curr)='".$Base2."',Transdt_Amount2, Transdt_Amount)) , 0) As UnitPrice, 0 TransportAmount, ".
				" 0 As ItemVat, 0 as ItemTax1, 0 as ItemTax2, 0 as ItemTax3, 0 as ItemTax4, 0 as ItemTax5, 0 As DiscountAmount, 0 as MeanCostAmount, if (trans_type='DV',1,-1) As QtyNetSold, Null As QtyExists, 
				if (trans_type='DV',1,0) As QtySold, 0 As Qty2Sold, if (trans_type='CV',1,0) As QtyReturn,";
	if ($packitem == 1) 				
		$querydelivery .= " null as Item_CodePacked, 1 QtyPack, ";
			   		
		$querydelivery .= "  null as Item_ExpireDate, Trans_Type ".
				" from transdt ".
				" inner join trans on trans.trans_id = transdt.trans_id ".
				" Inner Join Clients on Clients.Ledger_Number = transdt.Ledger_Number ".
				" Left Join Area on Area.Area_Code = Clients.Area_Code ".
				" Left Join Costcent on Costcent.Costcent_Code = trans.Costcent_Code ".
				" Left Join Project on Project.Project_Code = trans.Project_Code ".
				" Left Join Costcent As Costcent1 on Costcent1.Costcent_Code = Clients.CostCenter_Code ".
				" Left Join Project As Project1 on Project1.Project_Code = Clients.Project_Code ";
				
	if ($projectexist >	0 && $FI_RepRestrictProject == 1)
	  $querydelivery= $querydelivery." 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 trans.project_code like concat(Q1.project_code,'%')  ";
								 
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
	  $querydelivery= $querydelivery." 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 trans.Costcent_Code like concat(Q2.costcent_code,'%')  ";			
										
	$querydelivery= $querydelivery.						  
						  " Where (Trans_Reference Is Not Null And Trans_Reference != '') And trans_type in ('DV', 'CV')  ".
						  " And Date_format(trans.Trans_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(trans.Trans_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(trans.Trans_Date,'%Y-%m-%d'))  ".
						  " And transdt.Ledger_number between ifNull(".$fromclient.",transdt.Ledger_number) and ifNull(". $toclient.",transdt.Ledger_number) ".
						  " And ifNull(trans.project_code,'-1')   Like Concat(ifNull(".$fromproject.",ifNull(trans.project_code,'-1')),'%')  ".
						  " And ifNull(trans.Costcent_Code,'-1')  Like Concat(ifNull(".$fromcostcent.",ifNull(trans.Costcent_Code,'-1')),'%')  ".
						  " And ifNull(Clients.area_code,'-1')     Like Concat( 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)) ";

	 
if ($subproj != 'Null')
	$querydelivery= $querydelivery." And ifNull(trans.project_code,'-1')  Like ".$subproj; 
if ($subcostcent != 'Null')
	$querydelivery= $querydelivery." And ifNull(trans.Costcent_Code,'-1')  Like ".$subcostcent;  
							
}
$querydelivery= $querydelivery." ) Q1 ";

if ($packitem == 1) {
    $querydelivery= $querydelivery." ) Q3 ".
	                               " Group By Groupby1Code, Groupby2Code, Groupby3Code, MasterCode, DetailCode, WarehouseCode, Reference, StkDate ";
}

if ($option == 1) {
    $querydelivery= $querydelivery." ) Q2 ".
	                               " Group By Groupby1Code, Groupby2Code, Groupby3Code, MasterCode, DetailCode ";
}
if ($showDBN == 1)
	$querydelivery= $querydelivery." Order by Groupby1Code, Groupby2Code, Groupby3Code, MasterCode, Trans_Type, DetailCode, OrderDate ";
else 
	$querydelivery= $querydelivery." Order by Groupby1Code, Groupby2Code, Groupby3Code, MasterCode, DetailCode, OrderDate ";
	
//echo "<BR>".$querydelivery; //exit;
 // echo SqlFormatter::format($querydelivery);
$ArrayTotalByReport   = Array();
$ArrayTotalByMaster   = Array();
$ArrayTotalByGroup1   = Array();
$ArrayTotalByGroup2   = Array();
$ArrayTotalByGroup3   = Array();

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

$MainGroup1 = '';
$MainGroup2 = '';
$MainGroup3 = '';
$groupby1desc = '';
$groupby2desc = '';
$groupby3desc = '';

$ArrayActiveTaxes   = Array();
$ArrayActiveTaxes['ModuleTaxes'] = $Module_AdditionalTaxes;
$ArrayActiveTaxes['Tax1'] = $Setup_Tax1Active;
$ArrayActiveTaxes['Tax2'] = $Setup_Tax2Active;
$ArrayActiveTaxes['Tax3'] = $Setup_Tax3Active;
$ArrayActiveTaxes['Tax4'] = $Setup_Tax4Active;
$ArrayActiveTaxes['Tax5'] = $Setup_Tax5Active;

if($masterby != 1) $showwht = 0;
if($Module_Delivery == 0 ) $showwht = 0;
if($Module_Delivery == 1 )
  $resultstktransaction=mysql_query($querysales,$connection) or die(mysql_error());
else
  $resultstktransaction=mysql_query($querydelivery,$connection) or die(mysql_error());
 
$col=0; 
$tempref = '';

while($rowstktransaction=mysql_fetch_row($resultstktransaction)){
	
	if($col%2==0){
		$color = "style='background-color:".$report_color1."'";
	}else{
		$color = "style='background-color:".$report_color2."'";
	}
	
    // Master By Options Names and Totals
	if (($prtdt == 1 && $prtsubdt == 1) && (($MasterByCode != $rowstktransaction[2] && $MasterByCode != '') || ($MainGroup3 != $rowstktransaction[12] && $MainGroup3 != '') || ($MainGroup2 != $rowstktransaction[29] && $MainGroup2 != '') || ($MainGroup1 != $rowstktransaction[27] && $MainGroup1 != ''))) {
		    
		echo "<tr>";
		
		echo " <td>&nbsp;</td>  <td colspan='$ColsCountsub'><hr width='100%' color='grey' size='1'></td>";
		echo "</tr>";
		
		$StyleClass  = 'totals';
		if ($masterby == 1) $TotalsLabel = 'Total by Client: '.$MasterByName;
		else $TotalsLabel = 'Total by Item';
		DisplayTotals(1, $option, $FI_ShowCostPrice, $prtcost, $prtamt, $prtvat, $prtamtvat, $prtdisc, $pricettc, $prfmarby, $showweight, $showunit2qty, $ArrayTotalByMaster, $DecimalBase, $ArrayActiveTaxes, $TotalsLabel, $StyleClass, $PrtTransp, $showwht);
		//$ArrayTotalByMaster['totalWHTAmount'] = 0;	
	}
		
	//Group By Options Level 3 Totals
	if ( ($groupby3 != 1 && $prtdt == 1) && (($MainGroup3 != $rowstktransaction[12] && $MainGroup3 != '') || ($MainGroup2 != $rowstktransaction[29] && $MainGroup2 != '') || ($MainGroup1 != $rowstktransaction[27] && $MainGroup1 != ''))  ){
		
		echo "<tr>";
		echo "   <td>&nbsp;</td> <td colspan='$ColsCountsub'><hr width='100%' color='grey' size='1'></td>";
		echo "</tr>";
				
		$StyleClass  = 'grouplevel3total';
		$TotalsLabel = 'Total 3 - '.$groupby3name.' : '. str_replace('*',' --> ',$groupby3code);
		DisplayTotals(2, $option, $FI_ShowCostPrice, $prtcost, $prtamt, $prtvat, $prtamtvat, $prtdisc, $pricettc, $prfmarby, $showweight, $showunit2qty, $ArrayTotalByGroup3, $DecimalBase, $ArrayActiveTaxes, $TotalsLabel, $StyleClass, $PrtTransp, $showwht);	
					
	}
		
	//Group By Options Level 2 Totals
	if ( ($groupby2 != '' && ($prtdt == 1 || $groupby3 != 1)) && (($MainGroup2 != $rowstktransaction[29] && $MainGroup2 != '') || ($MainGroup1 != $rowstktransaction[27] && $MainGroup1 != ''))  ){
	  
		echo "<tr>";
		echo "   <td>&nbsp;</td> <td colspan='$ColsCountsub'><hr width='100%' color='grey' size='1'></td>";
		echo "</tr>";
				

		$StyleClass  = 'grouplevel2total';
		$TotalsLabel = 'Total 2 - '.$groupby2name.' : '.$groupby2code;
		DisplayTotals(3, $option, $FI_ShowCostPrice, $prtcost, $prtamt, $prtvat, $prtamtvat, $prtdisc, $pricettc, $prfmarby, $showweight, $showunit2qty, $ArrayTotalByGroup2, $DecimalBase, $TotalsLabel, $StyleClass, $PrtTransp, $showwht);

		
	}
		
	//Group By Options Level 1 Totals
	
	
	if ( ($groupby1 != '' && ($prtdt == 1 || $groupby2 != '' || $groupby3 != 1)) && ($MainGroup1 != $rowstktransaction[27] && $MainGroup1 != '') ){
	  
		echo "<tr>";
		echo "   <td colspan='$ColsCountmain'><hr width='100%' color='black' size='1'></td>";
		echo "</tr>";
				
		
		$StyleClass  = 'grouplevel1total';
		$TotalsLabel = 'Total 1 - '.$groupby1name.' : '.$groupby1code;
		DisplayTotals(4, $option, $FI_ShowCostPrice, $prtcost, $prtamt, $prtvat, $prtamtvat, $prtdisc, $pricettc, $prfmarby, $showweight, $showunit2qty, $ArrayTotalByGroup1, $DecimalBase, $ArrayActiveTaxes, $TotalsLabel, $StyleClass, $PrtTransp, $showwht);	

	}
		
	if ( ($groupby1 != ''  && $MainGroup1 != '' && $MainGroup1 != $rowstktransaction[27]) || 
		 ($groupby2 != ''  && $MainGroup2 != '' && $MainGroup2 != $rowstktransaction[29]) ||
		 ($groupby3 != 1   && $MainGroup3 != '' && $MainGroup3 != $rowstktransaction[12])  )
	{
		echo "<tr>";
		echo "   <td align='left' valign='top' colspan='$ColsCount'>&nbsp;</td>";
		echo "</tr>"; 
	}
		
	//Group By Options Level 1 Names 
	if ( ($groupby1 != '' && ($prtdt == 1 || $groupby2 != '' || $groupby3 != 1)) && ($MainGroup1 == '' || $MainGroup1 != $rowstktransaction[27])  ){
			
		$groupby1code = '';
		if ($rowstktransaction[27] == -1)
		    $groupby1code = '';
		else
            $groupby1code = $rowstktransaction[27];			
			   
		echo "<tr height='20'><td>&nbsp;</td>";
		echo "   <td align='left' valign='top' colspan='$ColsCount' class='grouplevel1' >1 -  ". $groupby1name." :&nbsp;&nbsp;". 
		         str_replace('*',' --> ',$groupby1code) . " - ". 
                 str_replace('*',' --> ',$rowstktransaction[28]) ."</td>";
		echo "</tr>"; 
				
						
		
		$MainGroup1   = $rowstktransaction[27];
		$groupby1desc = $rowstktransaction[28];
		
		$MainGroup2   = '';
		$groupby2desc = '';
		$MainGroup3   = '';
		$groupby3desc = '';	
		$MasterByCode = '';
		$MasterByName = '';
		
		unset($ArrayTotalByMaster);
		unset($ArrayTotalByGroup1);		
		unset($ArrayTotalByGroup2);		
		unset($ArrayTotalByGroup3);

	}
		
	//Group By Options Level 2 Names 
	if ( ($groupby2 != '' && ($prtdt == 1 || $groupby3 != 1)) && ($MainGroup2 == '' || $MainGroup2 != $rowstktransaction[29])  ){
			
		$groupby2code = '';
		if ($rowstktransaction[29] == -1)
		    $groupby2code = '';
		else
            $groupby2code = $rowstktransaction[29];			
			   
		echo "<tr height='20'><td>&nbsp;</td>";
		echo "   <td align='left' valign='top' colspan='$ColsCount' class='grouplevel2'>2 -  ". $groupby2name." :&nbsp;&nbsp;". 
		         str_replace('*',' --> ',$groupby2code) ." - ".
				 str_replace('*',' --> ',$rowstktransaction[30]) ."</td>";
		echo "</tr>"; 
				
						
		$MainGroup2   = $rowstktransaction[29];
		$groupby2desc = $rowstktransaction[30];
		
		
		$MainGroup3   = '';
		$groupby3desc = '';	
		$MasterByCode = '';
		$MasterByName = '';
		
		unset($ArrayTotalByMaster);
		unset($ArrayTotalByGroup2);		
		unset($ArrayTotalByGroup3);
		
	}
		
	//Group By Options Level 3 Names 
	if ( ($groupby3 != 1 && $prtdt == 1) && ($MainGroup3 == '' || $MainGroup3 != $rowstktransaction[12])  ){
	
		$groupby3code = '';
		if ($rowstktransaction[12] == -1)
		    $groupby3code = '';
		else
            $groupby3code = $rowstktransaction[12];			
			   
		echo "<tr><td>&nbsp;</td>";
		echo "   <td align='left' valign='top' colspan='$ColsCount' class='grouplevel3'>3 -  ". $groupby3name." :&nbsp;&nbsp;". 
			         str_replace('*',' --> ',$groupby3code) ."&nbsp;&nbsp; - &nbsp;&nbsp;".
			         str_replace('*',' --> ',$rowstktransaction[13]) ."</td>";
		echo "</tr>"; 
				
		echo "<tr>";
		echo "   <td align='left' valign='top' colspan='$ColsCount'>&nbsp;</td>";
		echo "</tr>"; 
						
		$MainGroup3   = $rowstktransaction[12];
		$groupby3desc = $rowstktransaction[13];
		
		$MasterByCode = '';
		$MasterByName = '';
		
		unset($ArrayTotalByMaster);	
		unset($ArrayTotalByGroup3);
		
	}
	
	if ($MasterByCode == '' || $MasterByCode != $rowstktransaction[2]) { 	
		if($prtsubdt == 1 && $prtdt == 1) {
			echo "<tr class='group'>";
			echo "   <td align='left' valign='top'>". $rowstktransaction[2] ."</td>";
			echo "   <td align='left' valign='top' colspan='14'>". $rowstktransaction[3] ."</td>";
			echo "</tr>"; 
		}
		
		$MasterByCode = $rowstktransaction[2];
		$MasterByName = $rowstktransaction[3];
		
		unset($ArrayTotalByMaster);
		
	}
	
	
	echo "<tr class='subgroup' $color>"; 
	
	if ($prtdt == 1 && $prtsubdt == 0 && ($masterby == 1 || $masterby == 2)) {
		echo "<td align='left'   valign='top' style='border-right:1px solid black'>". $rowstktransaction[2] ." </td>";
		if($option == 1) 
			echo "<td align='left' valign='top' colspan='2' style='border-right:1px solid black; padding-left:2px;'>". $rowstktransaction[3] ."</td>";
		else 
			echo "<td align='left' valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rowstktransaction[3] ."</td>";
	} 
	else if ($prtdt == 0 && $prtsubdt == 0 && $groupby1 != '' && $groupby2 == '' && $groupby3 == 1) {
		if($option == 1) 
			echo "<td align='left' valign='top' colspan='3'>".str_replace('*',' --> ',$rowstktransaction[27])."  -  ".str_replace('*',' --> ',$rowstktransaction[28])."</td>";
		else
			echo "<td align='left' valign='top' colspan='2'>".str_replace('*',' --> ',$rowstktransaction[27])."  -  ".str_replace('*',' --> ',$rowstktransaction[28])."</td>";
	}
	else if ($prtdt == 0 && $prtsubdt == 0 && $groupby2 != '' && $groupby3 == 1) {
		if($option == 1) 
			echo "<td align='left' valign='top' colspan='3'>".str_replace('*',' --> ',$rowstktransaction[29])."  -  ".str_replace('*',' --> ',$rowstktransaction[30])."</td>";
		else
			echo "<td align='left' valign='top' colspan='2'>".str_replace('*',' --> ',$rowstktransaction[29])."  -  ".str_replace('*',' --> ',$rowstktransaction[30])."</td>";
	}
	else if ($prtdt == 0 && $prtsubdt == 0 && $groupby3 != 1) {
		if($option == 1) 
			echo "<td align='left' valign='top' colspan='3'>".str_replace('*',' --> ',$rowstktransaction[12])."  -  ".str_replace('*',' --> ',$rowstktransaction[13])."</td>";
		else
			echo "<td align='left' valign='top' colspan='2'>".str_replace('*',' --> ',$rowstktransaction[12])."  -  ".str_replace('*',' --> ',$rowstktransaction[13])."</td>";
	}
	else {
		echo "<td align='left'   valign='top' style='border-right:1px solid black'>". $rowstktransaction[4] ."</td>";
		if($option == 1) 
			echo "<td align='left' valign='top' colspan='2' style='border-right:1px solid black; padding-left:2px;'>". $rowstktransaction[5] ."</td>";
		else 
			echo "<td align='left' valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rowstktransaction[5] ."</td>";
	}
	
		
	if($option == 1) {
		echo "<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". $rowstktransaction[26] ."</td>";
		echo "<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". $rowstktransaction[25] ."</td>";
	} else {
		echo "<td align='left'   valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rowstktransaction[10] ."</td>";
		echo "<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". $rowstktransaction[0] ."</td>";
		echo "<td align='center' valign='top' style='border-right:1px solid black; padding-right:2px;'>". $rowstktransaction[1] ."</td>";
	}
		
	echo "<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". $rowstktransaction[23] ."</td>";
	echo "<td align='center' valign='top' style='border-right:1px solid black; padding-right:2px;'>". $rowstktransaction[32] ."</td>";
	if ($showunit2qty == 1 ) {
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;' >". $rowstktransaction[41] ."</td>";
		echo "<td align='center' valign='top' style='border-right:1px solid black; padding-right:2px;'>". $rowstktransaction[40] ."</td>";
	}
	if ($showweight == 1 ) {
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;' >". $rowstktransaction[31] ."</td>";
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". $rowstktransaction[33] ."</td>";
	}
		
	if ($packitem == 0 && $prtqtyexist == 1)
		echo "<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". $rowstktransaction[24] ."</td>";
//	else
      //     echo "<td align='right'  valign='top' >&nbsp;</td>";		
		
	echo "<td align='center' valign='top' style='border-right:1px solid black;'>". $rowstktransaction[11] ."</td>";
	
	if ($prtamt == 1)
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". format_currency($rowstktransaction[19], $DecimalBase) ."</td>";
	if ($prtvat == 1)
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". format_currency($rowstktransaction[16], $DecimalBase) ."</td>";
	
	
	$TotalTaxes = $rowstktransaction[16];
	
	if ($Module_AdditionalTaxes == 1) {
		if ($Setup_Tax1Active == 1) echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rowstktransaction[35], $DecimalBase) ."</td>";
		if ($Setup_Tax2Active == 1) echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rowstktransaction[36], $DecimalBase) ."</td>";
		if ($Setup_Tax3Active == 1) echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rowstktransaction[37], $DecimalBase) ."</td>";
		if ($Setup_Tax4Active == 1) echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rowstktransaction[38], $DecimalBase) ."</td>";
		if ($Setup_Tax5Active == 1) echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rowstktransaction[39], $DecimalBase) ."</td>";
		
		$TotalTaxes += $rowstktransaction[35] + $rowstktransaction[36] + $rowstktransaction[37] + $rowstktransaction[38] + $rowstktransaction[39];
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($TotalTaxes, $DecimalBase) ."</td>";
	}
		
	if ($prtdisc == 1) {
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rowstktransaction[17], $DecimalBase) ."</td>";
	}	
	$totalamount = $rowstktransaction[19] + $rowstktransaction[16] + $rowstktransaction[42];
	echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($totalamount, $DecimalBase) ."</td>";		
	echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rowstktransaction[15], $DecimalBase) ."</td>";		
	
	
	if ($FI_ShowCostPrice == 1 && $prtcost == 1) {
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". number_format($rowstktransaction[18], $DecimalBase) ."</td>";
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". format_currency($rowstktransaction[20], $DecimalBase) ."</td>";
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". format_currency($rowstktransaction[21], $DecimalBase) ."</td>";
		echo "<td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;'>". format_currency($rowstktransaction[22], $DecimalBase) ."</td>";
	} else
		echo "<td align='right' valign='top' colspan='4' >&nbsp;</td>";
	

	if($PrtTransp==1) 
	echo "<td  align='right' valign='top' style='border-right:1px solid black; padding-right:2px;' >". format_currency($rowstktransaction[42], $DecimalBase) ."</td>";
		
	echo "</tr>";
	
		$col+=1;
		
	$ArrayTotalByMaster['NetQty']       = $ArrayTotalByMaster['NetQty']      + $rowstktransaction[23];
	$ArrayTotalByMaster['SoldQty']      = $ArrayTotalByMaster['SoldQty']     + $rowstktransaction[25];
	$ArrayTotalByMaster['RetQty']     	= $ArrayTotalByMaster['RetQty']      + $rowstktransaction[26];
	$ArrayTotalByMaster['SellAmt']      = $ArrayTotalByMaster['SellAmt']     + $rowstktransaction[19];
	$ArrayTotalByMaster['VatAmt']  		= $ArrayTotalByMaster['VatAmt']      + $rowstktransaction[16];
	$ArrayTotalByMaster['DiscAmt']   	= $ArrayTotalByMaster['DiscAmt']     + $rowstktransaction[17];
	$ArrayTotalByMaster['TotMeanCost']  = $ArrayTotalByMaster['TotMeanCost'] + $rowstktransaction[20];
	$ArrayTotalByMaster['ProfitAmt']    = $ArrayTotalByMaster['ProfitAmt']   + $rowstktransaction[21];
	$ArrayTotalByMaster['TotalWeight']  = $ArrayTotalByMaster['TotalWeight'] + $rowstktransaction[33];
	$ArrayTotalByMaster['TaxAmt1']  	= $ArrayTotalByMaster['TaxAmt1'] 	 + $rowstktransaction[35];
	$ArrayTotalByMaster['TaxAmt2']  	= $ArrayTotalByMaster['TaxAmt2'] 	 + $rowstktransaction[36];
	$ArrayTotalByMaster['TaxAmt3']  	= $ArrayTotalByMaster['TaxAmt3'] 	 + $rowstktransaction[37];
	$ArrayTotalByMaster['TaxAmt4']  	= $ArrayTotalByMaster['TaxAmt4'] 	 + $rowstktransaction[38];
	$ArrayTotalByMaster['TaxAmt5']  	= $ArrayTotalByMaster['TaxAmt5'] 	 + $rowstktransaction[39];
	$ArrayTotalByMaster['TotalTaxes']  	= $ArrayTotalByMaster['TotalTaxes']  + $TotalTaxes;
	$ArrayTotalByMaster['TotalTransp'] 	= $ArrayTotalByMaster['TotalTransp'] + $rowstktransaction[42];
	$ArrayTotalByMaster['NetSellAmt']   = $ArrayTotalByMaster['SellAmt'] 	 + $ArrayTotalByMaster['TotalTaxes'] + $ArrayTotalByMaster['TotalTransp'];
	$ArrayTotalByMaster['TotalQty2']  	= $ArrayTotalByMaster['TotalQty2'] 	 + $rowstktransaction[41];
	
	
	$ArrayTotalByReport['NetQty']       = $ArrayTotalByReport['NetQty']      + $rowstktransaction[23];
	$ArrayTotalByReport['SoldQty']      = $ArrayTotalByReport['SoldQty']     + $rowstktransaction[25];
	$ArrayTotalByReport['RetQty']     	= $ArrayTotalByReport['RetQty']      + $rowstktransaction[26];
	$ArrayTotalByReport['SellAmt']      = $ArrayTotalByReport['SellAmt']     + $rowstktransaction[19];
	$ArrayTotalByReport['VatAmt']  		= $ArrayTotalByReport['VatAmt']      + $rowstktransaction[16];
	$ArrayTotalByReport['DiscAmt']   	= $ArrayTotalByReport['DiscAmt']     + $rowstktransaction[17];
	$ArrayTotalByReport['TotMeanCost']  = $ArrayTotalByReport['TotMeanCost'] + $rowstktransaction[20];
	$ArrayTotalByReport['ProfitAmt']    = $ArrayTotalByReport['ProfitAmt']   + $rowstktransaction[21];
	$ArrayTotalByReport['TotalWeight']  = $ArrayTotalByReport['TotalWeight'] + $rowstktransaction[33];
	$ArrayTotalByReport['TaxAmt1']  	= $ArrayTotalByReport['TaxAmt1'] 	 + $rowstktransaction[35];
	$ArrayTotalByReport['TaxAmt2']  	= $ArrayTotalByReport['TaxAmt2'] 	 + $rowstktransaction[36];
	$ArrayTotalByReport['TaxAmt3']  	= $ArrayTotalByReport['TaxAmt3'] 	 + $rowstktransaction[37];
	$ArrayTotalByReport['TaxAmt4']  	= $ArrayTotalByReport['TaxAmt4'] 	 + $rowstktransaction[38];
	$ArrayTotalByReport['TaxAmt5']  	= $ArrayTotalByReport['TaxAmt5'] 	 + $rowstktransaction[39];
	$ArrayTotalByReport['TotalTaxes']  	= $ArrayTotalByReport['TotalTaxes']  + $TotalTaxes;
	$ArrayTotalByReport['TotalTransp'] 	= $ArrayTotalByReport['TotalTransp'] + $rowstktransaction[42];
	$ArrayTotalByReport['NetSellAmt']   = $ArrayTotalByReport['SellAmt'] 	 + $ArrayTotalByReport['TotalTaxes'] + $ArrayTotalByReport['TotalTransp'];
	$ArrayTotalByReport['TotalQty2']  	= $ArrayTotalByReport['TotalQty2'] 	 + $rowstktransaction[41];
	
	
	$ArrayTotalByGroup1['NetQty']       = $ArrayTotalByGroup1['NetQty']      + $rowstktransaction[23];
	$ArrayTotalByGroup1['SoldQty']      = $ArrayTotalByGroup1['SoldQty']     + $rowstktransaction[25];
	$ArrayTotalByGroup1['RetQty']     	= $ArrayTotalByGroup1['RetQty']      + $rowstktransaction[26];
	$ArrayTotalByGroup1['SellAmt']      = $ArrayTotalByGroup1['SellAmt']     + $rowstktransaction[19];
	$ArrayTotalByGroup1['VatAmt']  		= $ArrayTotalByGroup1['VatAmt']      + $rowstktransaction[16];
	$ArrayTotalByGroup1['DiscAmt']   	= $ArrayTotalByGroup1['DiscAmt']     + $rowstktransaction[17];
	$ArrayTotalByGroup1['TotMeanCost']  = $ArrayTotalByGroup1['TotMeanCost'] + $rowstktransaction[20];
	$ArrayTotalByGroup1['ProfitAmt']    = $ArrayTotalByGroup1['ProfitAmt']   + $rowstktransaction[21];
	$ArrayTotalByGroup1['TotalWeight']  = $ArrayTotalByGroup1['TotalWeight'] + $rowstktransaction[33];
	$ArrayTotalByGroup1['TaxAmt1']  	= $ArrayTotalByGroup1['TaxAmt1'] 	 + $rowstktransaction[35];
	$ArrayTotalByGroup1['TaxAmt2']  	= $ArrayTotalByGroup1['TaxAmt2'] 	 + $rowstktransaction[36];
	$ArrayTotalByGroup1['TaxAmt3']  	= $ArrayTotalByGroup1['TaxAmt3'] 	 + $rowstktransaction[37];
	$ArrayTotalByGroup1['TaxAmt4']  	= $ArrayTotalByGroup1['TaxAmt4'] 	 + $rowstktransaction[38];
	$ArrayTotalByGroup1['TaxAmt5']  	= $ArrayTotalByGroup1['TaxAmt5'] 	 + $rowstktransaction[39];
	$ArrayTotalByGroup1['TotalTaxes']  	= $ArrayTotalByGroup1['TotalTaxes']  + $TotalTaxes;
	$ArrayTotalByGroup1['TotalTransp'] 	= $ArrayTotalByGroup1['TotalTransp'] + $rowstktransaction[42];
	$ArrayTotalByGroup1['NetSellAmt']   = $ArrayTotalByGroup1['SellAmt'] 	 + $ArrayTotalByGroup1['TotalTaxes'] + $ArrayTotalByGroup1['TotalTransp'];
	$ArrayTotalByGroup1['TotalQty2']  	= $ArrayTotalByGroup1['TotalQty2'] 	 + $rowstktransaction[41];
	
	
	$ArrayTotalByGroup2['NetQty']       = $ArrayTotalByGroup2['NetQty']      + $rowstktransaction[23];
	$ArrayTotalByGroup2['SoldQty']      = $ArrayTotalByGroup2['SoldQty']     + $rowstktransaction[25];
	$ArrayTotalByGroup2['RetQty']     	= $ArrayTotalByGroup2['RetQty']      + $rowstktransaction[26];
	$ArrayTotalByGroup2['SellAmt']      = $ArrayTotalByGroup2['SellAmt']     + $rowstktransaction[19];
	$ArrayTotalByGroup2['VatAmt']  		= $ArrayTotalByGroup2['VatAmt']      + $rowstktransaction[16];
	$ArrayTotalByGroup2['DiscAmt']   	= $ArrayTotalByGroup2['DiscAmt']     + $rowstktransaction[17];
	$ArrayTotalByGroup2['TotMeanCost']  = $ArrayTotalByGroup2['TotMeanCost'] + $rowstktransaction[20];
	$ArrayTotalByGroup2['ProfitAmt']    = $ArrayTotalByGroup2['ProfitAmt']   + $rowstktransaction[21];
	$ArrayTotalByGroup2['TotalWeight']  = $ArrayTotalByGroup2['TotalWeight'] + $rowstktransaction[33];
	$ArrayTotalByGroup2['TaxAmt1']  	= $ArrayTotalByGroup2['TaxAmt1'] 	 + $rowstktransaction[35];
	$ArrayTotalByGroup2['TaxAmt2']  	= $ArrayTotalByGroup2['TaxAmt2'] 	 + $rowstktransaction[36];
	$ArrayTotalByGroup2['TaxAmt3']  	= $ArrayTotalByGroup2['TaxAmt3'] 	 + $rowstktransaction[37];
	$ArrayTotalByGroup2['TaxAmt4']  	= $ArrayTotalByGroup2['TaxAmt4'] 	 + $rowstktransaction[38];
	$ArrayTotalByGroup2['TaxAmt5']  	= $ArrayTotalByGroup2['TaxAmt5'] 	 + $rowstktransaction[39];
	$ArrayTotalByGroup2['TotalTaxes']  	= $ArrayTotalByGroup2['TotalTaxes']  + $TotalTaxes;
	$ArrayTotalByGroup2['TotalTransp'] 	= $ArrayTotalByGroup2['TotalTransp'] + $rowstktransaction[42];
	$ArrayTotalByGroup2['NetSellAmt']   = $ArrayTotalByGroup2['SellAmt'] 	 + $ArrayTotalByGroup2['TotalTaxes'] + $ArrayTotalByGroup2['TotalTransp'];
	$ArrayTotalByGroup2['TotalQty2']  	= $ArrayTotalByGroup2['TotalQty2'] 	 + $rowstktransaction[41];
	
	
	$ArrayTotalByGroup3['NetQty']       = $ArrayTotalByGroup3['NetQty']      + $rowstktransaction[23];
	$ArrayTotalByGroup3['SoldQty']      = $ArrayTotalByGroup3['SoldQty']     + $rowstktransaction[25];
	$ArrayTotalByGroup3['RetQty']     	= $ArrayTotalByGroup3['RetQty']      + $rowstktransaction[26];
	$ArrayTotalByGroup3['SellAmt']      = $ArrayTotalByGroup3['SellAmt']     + $rowstktransaction[19];
	$ArrayTotalByGroup3['VatAmt']  		= $ArrayTotalByGroup3['VatAmt']      + $rowstktransaction[16];
	$ArrayTotalByGroup3['DiscAmt']   	= $ArrayTotalByGroup3['DiscAmt']     + $rowstktransaction[17];
	$ArrayTotalByGroup3['TotMeanCost']  = $ArrayTotalByGroup3['TotMeanCost'] + $rowstktransaction[20];
	$ArrayTotalByGroup3['ProfitAmt']    = $ArrayTotalByGroup3['ProfitAmt']   + $rowstktransaction[21];
	$ArrayTotalByGroup3['TotalWeight']  = $ArrayTotalByGroup3['TotalWeight'] + $rowstktransaction[33];
	$ArrayTotalByGroup3['TaxAmt1']  	= $ArrayTotalByGroup3['TaxAmt1'] 	 + $rowstktransaction[35];
	$ArrayTotalByGroup3['TaxAmt2']  	= $ArrayTotalByGroup3['TaxAmt2'] 	 + $rowstktransaction[36];
	$ArrayTotalByGroup3['TaxAmt3']  	= $ArrayTotalByGroup3['TaxAmt3'] 	 + $rowstktransaction[37];
	$ArrayTotalByGroup3['TaxAmt4']  	= $ArrayTotalByGroup3['TaxAmt4'] 	 + $rowstktransaction[38];
	$ArrayTotalByGroup3['TaxAmt5']  	= $ArrayTotalByGroup3['TaxAmt5'] 	 + $rowstktransaction[39];
	$ArrayTotalByGroup3['TotalTaxes']  	= $ArrayTotalByGroup3['TotalTaxes']  + $TotalTaxes;
	$ArrayTotalByGroup3['TotalTransp'] 	= $ArrayTotalByGroup3['TotalTransp'] + $rowstktransaction[42];		
	$ArrayTotalByGroup3['NetSellAmt']   = $ArrayTotalByGroup3['SellAmt'] 	 + $ArrayTotalByGroup3['TotalTaxes'] + $ArrayTotalByGroup3['TotalTransp'];
	$ArrayTotalByGroup3['TotalQty2']  	= $ArrayTotalByGroup3['TotalQty2'] 	 + $rowstktransaction[41];
	
	
	if($showwht == 1 && $tempref != $rowstktransaction[0] ){
		
		if($MasterByCode != $rowstktransaction[2]) $ArrayTotalByMaster['totalWHTAmount'] = 0;	
		$ArrayTotalByMaster['totalWHTAmount'] = $ArrayTotalByMaster['totalWHTAmount'] + $rowstktransaction[43];
		$ArrayTotalByReport['finaltotalWHTAmount'] = $ArrayTotalByReport['finaltotalWHTAmount'] + $rowstktransaction[43];
		
		$tempref = $rowstktransaction[0];
	}
}

// Display Totals By Master	
if ($MasterByCode != '' && $prtdt == 1 && $prtsubdt == 1) {
		    
	echo "<tr>";
	echo "   <td colspan='$ColsCountmain'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
			
	$StyleClass  = 'totals';
	if ($masterby == 1) $TotalsLabel = 'Total by Client: '.$MasterByName;
	else $TotalsLabel = 'Total by Item';
	DisplayTotals(1, $option, $FI_ShowCostPrice, $prtcost, $prtamt, $prtvat, $prtamtvat, $prtdisc, $pricettc, $prfmarby, $showweight, $showunit2qty, $ArrayTotalByMaster, $DecimalBase, $ArrayActiveTaxes, $TotalsLabel, $StyleClass, $PrtTransp, $showwht);

			
}

//Display Totals By Group Level 3 
if ($groupby3 != 1 && $prtdt == 1){

	echo "<tr>";
	echo "   <td colspan='$ColsCountmain'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
				
	$StyleClass  = 'grouplevel3total';
	$TotalsLabel = 'Total 3 - '.$groupby3name.' : '. str_replace('*',' --> ',$groupby3code);
	DisplayTotals(2, $option, $FI_ShowCostPrice, $prtcost, $prtamt, $prtvat, $prtamtvat, $prtdisc, $pricettc, $prfmarby, $showweight, $showunit2qty, $ArrayTotalByGroup3, $DecimalBase, $ArrayActiveTaxes, $TotalsLabel, $StyleClass, $PrtTransp, $showwht);	

}

//Display Totals By Group Level 2 
if ($groupby2 != '' && ($prtdt == 1 || $groupby3 != 1)){

	echo "<tr>";
	echo "   <td colspan='$ColsCountmain'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
				

	$StyleClass  = 'grouplevel2total';
	$TotalsLabel = 'Total 2 - '.$groupby2name.' : '.$groupby2code;
	DisplayTotals(3, $option, $FI_ShowCostPrice, $prtcost, $prtamt, $prtvat, $prtamtvat, $prtdisc, $pricettc, $prfmarby, $showweight, $showunit2qty, $ArrayTotalByGroup2, $DecimalBase, $ArrayActiveTaxes, $TotalsLabel, $StyleClass, $PrtTransp, $showwht);

}

	
//Display Totals By Group Level 1 
if ($groupby1 != '' && ($prtdt == 1 || $groupby2 != '' || $groupby3 != 1)){

	echo "<tr>";
	echo "   <td colspan='$ColsCountmain'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
				
		
	$StyleClass  = 'grouplevel1total';
	$TotalsLabel = 'Total 1 - '.$groupby1name.' : '.$groupby1code;
	DisplayTotals(4, $option, $FI_ShowCostPrice, $prtcost, $prtamt, $prtvat, $prtamtvat, $prtdisc, $pricettc, $prfmarby, $showweight, $showunit2qty, $ArrayTotalByGroup1, $DecimalBase, $ArrayActiveTaxes, $TotalsLabel, $StyleClass, $PrtTransp, $showwht);	

}

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


$StyleClass  = 'summary';
$TotalsLabel = 'TOTALS';
DisplayTotals(5, $option, $FI_ShowCostPrice, $prtcost, $prtamt, $prtvat, $prtamtvat, $prtdisc, $pricettc, $prfmarby, $showweight, $showunit2qty, $ArrayTotalByReport, $DecimalBase, $ArrayActiveTaxes, $TotalsLabel, $StyleClass, $PrtTransp, $showwht);	

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

function DisplayTotals($PTotalOptions, $POption, $FI_ShowCostPrice, $PPrtCost, $PPrtAmt, $PPrtVat, $PPrtAmtVat, $PPrtDisc, $PPriceTTC, $PPrfmarby, $PShowWeight, $PShowUnit2Qty, $PArrayTotal, $PDecimalBase, $PArrayActiveTaxes, $PTotalsLabel, $PStyleClass,$PrtTransp, $showwht) {

	if ($PPrfmarby == 1)
		$ProfMargin = (($PArrayTotal['SellAmt'] - $PArrayTotal['TotMeanCost']) / $PArrayTotal['SellAmt']) * 100;
	else
	    $ProfMargin = (($PArrayTotal['SellAmt'] - $PArrayTotal['TotMeanCost']) / $PArrayTotal['TotMeanCost']) * 100;
		   
	echo "<tr class='".$PStyleClass."'>";
	echo "   <td align='left'  valign='top' >&nbsp;</td>";
	echo "   <td align='left'  valign='top' colspan='2' >".$PTotalsLabel."</td>";
				
	if($POption == 1) {
		echo "   <td align='right' valign='top' >". number_format($PArrayTotal['RetQty'],2) ."</td>";
		echo "   <td align='right' valign='top' >". number_format($PArrayTotal['SoldQty'],2) ."</td>";
	} else
		echo "   <td align='left'  valign='top' colspan='2'>&nbsp;</td>";
									
	echo "   <td align='right' valign='top' >". number_format($PArrayTotal['NetQty'],2) ."</td>";
	echo "   <td align='right'> &nbsp; </td>";
	if ($PShowUnit2Qty == 1) {
		echo "   <td align='right' >".number_format($PArrayTotal['TotalQty2'],2)." </td>"; 
		echo "   <td align='right'> &nbsp; </td>"; 
	}
	if ($PShowWeight == 1) {
		echo "   <td align='right'> &nbsp; </td>"; 
		echo "   <td align='right' >".number_format($PArrayTotal['TotalWeight'],2)." </td>"; 
	}
	
	echo "   <td align='left'  valign='top'  colspan='1'>&nbsp;</td>";
	
	if ($PPrtAmt == 1)
		echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['SellAmt'], $PDecimalBase) ."</td>";
	if ($PPrtVat == 1)
		echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['VatAmt'] , $PDecimalBase) ."</td>";
	
	
	if ($PArrayActiveTaxes['ModuleTaxes'] == 1) {
	
		if ($PArrayActiveTaxes['Tax1'] == 1) {
			echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['TaxAmt1'], $PDecimalBase) ."</td>";
		}
		if ($PArrayActiveTaxes['Tax2'] == 1) {
			echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['TaxAmt2'], $PDecimalBase) ."</td>";
		}
		if ($PArrayActiveTaxes['Tax3'] == 1) {
			echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['TaxAmt3'], $PDecimalBase) ."</td>";
		}
		if ($PArrayActiveTaxes['Tax4'] == 1) {
			echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['TaxAmt4'], $PDecimalBase) ."</td>";
		}
		if ($PArrayActiveTaxes['Tax5'] == 1) {
			echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['TaxAmt5'], $PDecimalBase) ."</td>";
		}
		
		echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['TotalTaxes'], $PDecimalBase) ."</td>";
	}
	
	
	//If Case Showing Report Totals
	if($PTotalOptions == 5) {
		if ($PPrtDisc == 1) {
			echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['DiscAmt'], $PDecimalBase) ."</td>";
		} 	
		
		if ($PPrtAmtVat == 1)
			echo "   <td align='center' valign='top' colspan='2'><i>&nbsp;&nbsp; Net  S+V=". format_currency($PArrayTotal['NetSellAmt'], $PDecimalBase) ."</i></td>";
		else	
			echo "   <td align='center' valign='top' colspan='2'>&nbsp;</td>";
	} 
	else {
		if ($PPrtDisc == 1) {
			echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['DiscAmt'], $PDecimalBase) ."</td>";
		}	
		
		if ($PPrtAmtVat == 1)
			echo "   <td align='center' valign='top' colspan='2'>&nbsp;<i> Net  S+V=". format_currency($PArrayTotal['NetSellAmt'], $PDecimalBase) ."</i></td>";
		else	
			echo "   <td align='center' valign='top' colspan='2'>&nbsp;</td>";
	}
	
	if ($FI_ShowCostPrice == 1 && $PPrtCost == 1) {
		echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['TotMeanCost'], $PDecimalBase) ."</td>";
		echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['ProfitAmt'], $PDecimalBase) ."</td>";
		echo "   <td align='right' valign='top' >". format_currency($ProfMargin , $PDecimalBase) ." %</td>";
		
		if($PrtTransp==1)
			echo "   <td align='right'  valign='top' colspan='2'>". format_currency($PArrayTotal['TotalTransp'], $PDecimalBase) ."</td>";
		else
			echo "   <td align='left'  valign='top' colspan='2'>&nbsp;</td>";
	} else {
		echo "   <td align='left'  valign='top' colspan='3'>&nbsp;</td>";
		if($PrtTransp==1)
			echo "   <td align='right'  valign='top' >". format_currency($PArrayTotal['TotalTransp'], $PDecimalBase) ."</td>";
		}
 
	echo "</tr>"; 
	if($PTotalOptions == 1 && $showwht == 1) {
		echo "<tr class='".$PStyleClass."'><td></td><td>Total WHT Amount: </td>";
		echo "<td align='right'  valign='top' >". format_currency($PArrayTotal['totalWHTAmount'], $PDecimalBase) ."</td></tr>";
		
	}
	
	if($PTotalOptions == 5 && $showwht == 1) { 
		echo "<tr class='".$PStyleClass."'><td></td><td>Total WHT Amount: </td>";
		echo "<td align='right'  valign='top' >". format_currency($PArrayTotal['finaltotalWHTAmount'], $PDecimalBase) ."</td></tr>";
	}	
	//If Case Showing Master Totals
	if($PTotalOptions == 1) {
				
		echo "<tr class='".$PStyleClass."'>";
		echo "   <td align='left'  valign='top' colspan='10'>&nbsp;</td>";
				
		//if ($PPriceTTC == 0)
		//	echo "   <td align='left' valign='top' colspan='2'><i> Net  S+V=". format_currency($PArrayTotal['NetSellAmt'], $PDecimalBase) ."</i></td>";
		//else
			//echo "   <td align='left' valign='top' colspan='2'> Net  S+V=". format_currency($PArrayTotal['SellAmt']   , $PDecimalBase) ."</td>";
					
		echo "   <td align='left'  valign='top' colspan='2'>&nbsp;</td>";
		echo "</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;

?>