<?php

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

print <<< HERE
<HTML>
<HEAD>
<TITLE> Sales Order Report </TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">

<style type="text/css">
table.params td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }
				 
table.main tr.group { font-size: 14px; 
					  font-weight: bold;
                      font-family:Times-New-Roman;
                    }	

table.main td.grouplevel1 { font-size: 14px; 
						    font-weight: bold;
                            font-family:Times-New-Roman;
						    color: #0000FF;
							background-color: #F0F0F0;
                           }
table.main td.grouplevel2 { font-size: 14px; 
                            font-family:Times-New-Roman;
						    color: #FF0000;
							background-color: #F0F0F0;
                           }	
table.main td.grouplevel3 { font-size: 13px; 
							font-style: italic;
                            font-family:Times-New-Roman;
						    color: #336600;
							background-color: #F0F0F0;
                           }					

table.master th { font-size: 14px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                }				 
table.master td { font-size: 14px; 
                  font-family:Times-New-Roman;
                }
table.master tr.group { font-size: 14px; 
                        font-weight: bold;
                        font-family:Times-New-Roman;
                      }				 				

table.master tr.totals { font-size: 12px; 
                         font-weight: bold;
                         font-family:Times-New-Roman;
                       }
table.master tr.summary { font-size: 12px; 
                          font-weight: bold;
                          font-family:Times-New-Roman;
						  background-color: #F0F0F0;
                        }					   

table.master tr.grouplevel1total { font-size: 14px; 
								   font-weight: bold;
								   font-family:Times-New-Roman;
								   color: #0000FF;
								   background-color: #F0F0F0;
								 }				 
table.master tr.grouplevel2total { font-size: 14px; 
							       font-family:Times-New-Roman;
							       color: #FF0000;
							       background-color: #F0F0F0;
						         }										 
table.master tr.grouplevel3total { font-size: 13px; 
							       font-style: italic;
							       font-family:Times-New-Roman;
							       color: #336600;
							       background-color: #F0F0F0;
						          }						   
				
table.group td { font-size: 12px; 
                 font-weight: bold;
				 font-style: italic;
                 font-family:Times-New-Roman;
               }				 
			   
			   
table.detail th { font-size: 12px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
				}  
			   
table.detail td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }
				 
table.detail td.totals { font-size: 12px; 
                         font-weight: bold;
                         font-family:Times-New-Roman;
                       }				 				 
		 
				 

</style>
</HEAD>


HERE;


include("config.inc.php");

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

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


$querylog="SELECT print as printaccess from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['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, Company_Name As CompanyName, ".
			" Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultsetup)){
  extract($rows);
} 

//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC, ifNull(Sale_MinPendingQty,0) As Sale_MinPendingQty, ifNull(Sale_MaxExceedQty,0) As Sale_MaxExceedQty From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}


$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 ".$HTTP_SESSION_VARS['dbLabel'].".login where user_account='".$HTTP_SESSION_VARS['useraccount']."' and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['dbName']."') ";
$resultlog=mysql_query($querylog) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}


$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$HTTP_SESSION_VARS['dbLabel'].".loginstk on project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%') ".
			  " where user_account='".$HTTP_SESSION_VARS['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 ".$HTTP_SESSION_VARS['dbLabel'].".loginstk on costcent.costcent_code like concat(ifnull(loginstk.costcent_code,costcent.costcent_code),'%') ".
			   " where user_account='".$HTTP_SESSION_VARS['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 ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
		 "                                          where user_account='".$HTTP_SESSION_VARS['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 ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['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]);

print <<< HERE
<table width="100%" border="0" align="center">
<tr>
  <td width='30%'><b>$CompanyName</b></td>
  <td width='50%' align='center'><font size=4><b>Sales Order Report</b></font></td>
  <td width='10%'><font size=1><b> Printed Date: </b> <br><b>Time: </b>
  <td width='10%'><font size=1>
HERE;

echo $printdate[2]."/".$printdate[1]."/".$printdate[0];
//echo DATE("d"."/"."m"."/"."Y");
echo "<br>".$dt[1]." ".$dt[2];


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


$SelectedOptions = "Filter by: <br>";
if ($fromdate != '')      $SelectedOptions .= "-> Date From: ". $fromdate . "  To: ". $todate ."<br>";	
if ($displaycur != '')    $SelectedOptions .= "-> Currency: ". $displaycur ."<br>";	
if ($fromitem != '')      $SelectedOptions .= "-> Item From: ". $fromitem . "  To: ". $toitem ."<br>";
if ($fromgroup != '')     $SelectedOptions .= "-> Group From: ". $fromgroup . "  To: ". $togroup ."<br>";
if ($fromsubgroup != '')  $SelectedOptions .= "-> SubGroup From: ". $fromsubgroup . "  To: ". $tosubgroup ."<br>";
if ($fromproject != '')   $SelectedOptions .= "-> Project From: ". $fromproject . "<br>";
if ($fromcostcent != '')  $SelectedOptions .= "-> Costcent From: ". $fromcostcent . "<br>";
if ($fromclient != '')    $SelectedOptions .= "-> Client From: ". $fromclient . "  To: ". $toclient ."<br>";
if ($fromsalesman != '')  $SelectedOptions .= "-> Salesman From: ". $fromsalesman . "  To: ". $tosalesman ."<br>";
if ($fromwarehouse != '') $SelectedOptions .= "-> Warehouse From: ". $fromwarehouse . "<br>";

  
if (!empty($fromdate)) $fromdate = explodeword($fromdate);
if (!empty($todate))   $todate = explodeword($todate);  
   
$fromitem      = GetSQLValueString($fromitem, 'text');
$toitem        = GetSQLValueString($toitem, 'text');
$fromproject   = GetSQLValueString($fromproject, 'text');
$fromcostcent  = GetSQLValueString($fromcostcent, 'text');
$fromgroup     = GetSQLValueString($fromgroup, 'text');
$togroup       = GetSQLValueString($togroup, 'text');
$fromsubgroup  = GetSQLValueString($fromsubgroup, 'text');
$tosubgroup    = GetSQLValueString($tosubgroup, 'text');
$fromwarehouse = GetSQLValueString($fromwarehouse, 'text');
$fromclient    = GetSQLValueString($fromclient, 'text');
$toclient      = GetSQLValueString($toclient, 'text');
$fromsalesman  = GetSQLValueString($fromsalesman, 'text');
$tosalesman    = GetSQLValueString($tosalesman, 'text');
$fromdate  	   = GetSQLValueString($fromdate, 'date');
$todate        = GetSQLValueString($todate, 'date');     
	
$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 == 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 == 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")';
		}
		
	}
	
	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 == 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 == 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 {
		$groupby1name    .= '';				
		$QryGroupby1Code .= "-1";
		$QryGroupby1Name .= "'None'";
	}
		
	
	$QryGroupby1Code .= ' As Groupby1Code, ';
	$QryGroupby1Name .= ' As Groupby1Name, ';

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

if ($groupby2 != '' ) {
		
	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 == 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 {
		$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
</font></td>
</tr>
<tr>
   <td colspan='4' width='100%'> <hr width='100%' color='black' size='1'> </td>
</tr>
</table>


<table class="params" width="100%" border="0" align="center" >
<tr>
  <td width="100%" valign='top'><b>$SelectedOptions</b></td>
</tr>
<tr>
   <td width='100%'> <hr width='100%' color='black' size='1'> </td>
</tr>
</table>
HERE;

echo "<table  border='0' width='100%' class='main' align='center' cellpadding='0' cellspacing='0'>";
echo"<tr><td>";

if ($masterby == 1) {
	if ($prtdt == 1) {
		CreateTableHeader($masterby, 'master');
		echo"</table>";
		echo"</td></tr>";
	}	
	if ($prtsubdt == 1) {
		echo"<tr><td>";
		CreateTableDetail($masterby, $prtpend, 'detail');
		echo"</table>";
		echo"</td></tr>";
	}	
}	
else if ($masterby == 2) {
	if ($prtdt == 1) {
		CreateTableDetail($masterby, $prtpend, 'master');
		echo"</table>";
		echo"</td></tr>";
	}	
	if ($prtsubdt == 1){
		echo"<tr><td>";
		CreateTableHeader($masterby, 'detail');
		echo"</table>";
		echo"</td></tr>";
	}
}	
 


echo"<tr><td ><hr width='100%' color='black' size='2'></td></tr>";
 

$query = '';

$query = $query." Select Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, Groupby3Code, Groupby3Name, MasterCode, MasterDescription, ".
				" DetailCode, DetailDescription, SorderReference, SorderDate, ClientCode, ClientName, SorderRemark, ItemCode, ItemDescription, ".
				" WarehouseCode, Currency, Quantity, UnitPrice, TotalDiscAmt, ";
				
if($prtsubdt == 1) $query = $query." TotalAmount ";
else $query = $query." Sum(TotalAmount) As TotalAmount ";

$query = $query.", SorderNetTotal, RemainQty ";
$query = $query." From ( ";
				
$query = $query." Select SorderReference, SorderDate, SorderRemark, MasterCode, MasterDescription, DetailCode, DetailDescription, ClientCode, ClientName, ".
				" ItemCode, ItemDescription, WarehouseCode, Currency, Quantity, UnitPrice, if($prtpend = 1,((RemainQty*UnitPrice*DiscountPer/100) + DiscountAmount*RemainQty/Quantity),((Quantity*UnitPrice*DiscountPer/100) + DiscountAmount)) As TotalDiscAmt, ".
				" if($prtpend = 1,((RemainQty*UnitPrice) - (RemainQty*UnitPrice*DiscountPer/100) - DiscountAmount*RemainQty/Quantity),((Quantity*UnitPrice) - (Quantity*UnitPrice*DiscountPer/100) - DiscountAmount)) As TotalAmount, SorderNetTotal, RemainQty, ";
				
$query = $query.$QryGroupby1Code . $QryGroupby1Name.
                $QryGroupby2Code . $QryGroupby2Name.
				$QryGroupby3Code . $QryGroupby3Name;
	
$query = $query." From ( ".
				" Select Sorder.Sorder_Reference As SorderReference, Date_Format(Sorder.Sorder_Date,'%d/%m/%Y') As SorderDate, ".
			    " if($prtdt=1, if($masterby=1, Sorder.Client_Code, SorderDt.Item_Code),'') As MasterCode, ".
				" if($prtdt=1, if($masterby=1, Clients.Ledger_Name, Items.Item_Description),'') As MasterDescription , ".
				" if($prtsubdt=1, if($masterby=1, SorderDt.Item_Code, Sorder.Client_Code), '') As DetailCode, ".
				" if($prtsubdt=1, if($masterby=1, Items.Item_Description, Clients.Ledger_Name), '') As DetailDescription , ".
				" Sorder.Client_Code As ClientCode, Clients.Ledger_Name As ClientName, ".
				" SorderDt.Item_Code As ItemCode, Items.Item_Description As ItemDescription, ".
				" Sorder.Salesman_Code As SalesmanCode,Salesmen.Ledger_Name As SalesmanName, ".
				" ifNull(Costcent.Parent_Code, Costcent.Costcent_Code) As ParentCostcenterCode,Costcent.Costcent_Name As ParentCostcenterName, ".
				" Sorder.Costcent_Code As CostcenterCode,Costcent.Costcent_Name As CostcenterName, ".
				" ifNull(Project.Parent_Code, Project.Project_Code) As ParentProjectCode, Project.Project_Name As ParentProjectName, ".
				" Sorder.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, ".
				" Items.Category_Code As CategoryCode, Category.Category_Name As CategoryName, ".
				" 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, ".
				" SorderDt.Warehouse_Code As WarehouseCode, ifNull(Warehouse1.Warehouse_Code, SorderDt.Warehouse_Code) As ParentWarehouseCode,  ".
				" Sorder.Sorder_Remark As SorderRemark, Sorder.Currency_Code As Currency, SorderDt.SorderDt_Quantity As Quantity, ".
				" if($pricettc=1, if(ifNull(SorderDt.SorderDt_PriceTTC,0)=0, 0,  ".
				" ifNull(if(upper($curr)='".$Base1."',ifNull(convertcurfunc(Sorder.Currency_Code, '".$Base1."', Sorder.Sorder_Date, 0, 0, '', '', ifNull(SorderDt.SorderDt_PriceTTC,0)),0), ".
				"        if(upper($curr)='".$Base2."',ifNull(convertcurfunc(Sorder.Currency_Code, '".$Base2."', Sorder.Sorder_Date, 0, 0, '', '', ifNull(SorderDt.SorderDt_PriceTTC,0)),0), SorderDt.SorderDt_PriceTTC)) ,0)),".
				" if(ifNull(SorderDt.SorderDt_Price,0)=0, 0,  ".
				" ifNull(if(upper($curr)='".$Base1."',SorderDt.SorderDt_PriceBase1,if(upper($curr)='".$Base2."',SorderDt.SroderDt_PriceBase2, SorderDt.SorderDt_Price)) + ".
				"         (ifNull(if(upper($curr)='".$Base1."', ifNull(SorderDt.SorderDt_PriceBase1,0), if(upper($curr)='".$Base2."', ifNull(SorderDt.SroderDt_PriceBase2,0), ifNull(SorderDt.SorderDt_Price,0))),0) * IF(Sorder_VatChckbx=1,ifNull(SorderDt.Item_Vat, 0),0)/100)  ".
				"	,0))) As UnitPrice,  ".
				" ifNull(SorderDt.Sorderdt_discount, 0) As DiscountPer, ".
				" ifNull(if(upper($curr)='".$Base1."',SorderDt.SorderDt_DiscountBase1,if(upper($curr)='".$Base2."',SorderDt.SorderDt_DiscountBase2,SorderDt.SorderDt_DiscountAmount)),0) As DiscountAmount, ".
				" Round((if($SalesTTC=1,ifNull(Sorder_Taxable,0)*(1+$Setup_VatPercentage/100),ifNull(Sorder_Taxable,0)) + ifNull(Sorder_NoneTaxable,0) + if($SalesTTC=1,0,IfNull(Sorder_VAT,0)) - IfNull(Sorder_DiscountAmount,0) + (ifNull(Sorder_Tax1,0) + ifNull(Sorder_Tax2,0) + ifNull(Sorder_Tax3,0) + ifNull(Sorder_Tax4,0) + ifNull(Sorder_Tax5,0))), ".$DecimalBase.") As SorderNetTotal ";
				
if ($prtpend == 1) {
	$query= $query.", (ifNull(Q.QuantityOrdered,0) - ifNull(Q.QuantityUsed,0)) as RemainQty ";
} else {
	$query= $query.", 0 as RemainQty ";
}	
			   
$query = $query." From SorderDt  ".
				" Inner Join Sorder on SorderDt.Sorder_ID = Sorder.Sorder_ID ".
				" Inner Join Items on SorderDt.Item_Code = Items.Item_Code ".
				" Inner Join Clients on Clients.Ledger_Number = Sorder.Client_Code ".
				" 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 Sorder.Salesman_Code = Salesmen.Ledger_Number ".
				" Left Join Costcent on Costcent.Costcent_Code = Sorder.Costcent_Code ".
				" Left Join Project on Project.Project_Code = Sorder.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 = SorderDt.Warehouse_Code ";
						  
if ($projectexist >	0 && $FI_RepRestrictProject == 1)
  $query= $query." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
								 " 			   	where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
								 "             	and (project_code is not null and project_code != '') ".
								 "			 ) Q1 on Sorder.project_code like concat(Q1.project_code,'%')  ";
							 
if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
  $query= $query." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
								 "			  	where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
								 "              and (costcent_code is not null and costcent_code != '') ".
								 "			 ) Q2 on Sorder.Costcent_Code like concat(Q2.costcent_code,'%')  ";							 
						   
if ($prtpend == 1) {
	$query= $query." Inner Join ( Select SorderDt.Sorder_ID, SorderDt.SorderDt_ID, ".
				   "              Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityUsed, ".
				   "              ifNull(Sorderdt.SorderDt_Quantity,0) As QuantityOrdered ".
				   "              From SorderDt ".
				   "              Inner Join Sorder on SorderDt.Sorder_ID = Sorder.Sorder_ID ".
				   "              Left Join DeliveryDt on (DeliveryDt.RelatedDt_ID = SorderDt.SorderDt_id And DeliveryDt.Journal_Type = 'DI') ".
				   "	          Where ifNull(Sorderdt_OldData,0) = 0  ".
				   "              And SorderDt.Client_Code between ifNull(".$fromclient.",SorderDt.Client_Code) and ifNull(". $toclient.",SorderDt.Client_Code) ".
				   " 			  And SorderDt.Item_Code between ifNull(".$fromitem.",SorderDt.Item_Code) and ifNull(". $toitem.",SorderDt.Item_Code) ".
				   "              Group by SorderDt.Sorder_id, SorderDt.SorderDt_ID ".
				   "			  Having (QuantityOrdered - QuantityUsed) > ($Sale_MinPendingQty*QuantityOrdered/100) ".
				   "	      ) As Q on Q.Sorder_ID = Sorder.Sorder_ID And Q.SorderDt_ID = SorderDt.SorderDt_ID ";

}

$query = $query." Where Sorder.Journal_Type='SO' And Sorder.Sorder_Type = 'SO' ".
				" And ifNull(Sorder.Sorder_disapproved,0) = 0 And ifNull(Sorder.Sorder_Hide,0) = 0 ".
				" And (Sorder.Sorder_Reference Is Not Null And Sorder.Sorder_Reference != '')  ".
				" And Date_format(Sorder.Sorder_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(Sorder.Sorder_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(Sorder.Sorder_Date,'%Y-%m-%d'))  ".
				" And SorderDt.item_code between ifNull(".$fromitem.",SorderDt.item_code) and ifNull(". $toitem.",SorderDt.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(Sorder.Client_Code,'-1') between ifNull(".$fromclient.",ifNull(Sorder.Client_Code,'-1')) and ifNull(". $toclient.",ifNull(Sorder.Client_Code,'-1')) ".
				" And ifNull(Sorder.Salesman_Code,'-1') between ifNull(".$fromsalesman.",ifNull(Sorder.Salesman_Code,'-1')) and ifNull(". $tosalesman.",ifNull(Sorder.Salesman_Code,'-1')) ".
				" And ifNull(Sorder.project_code,'-1')   Like Concat(ifNull(".$fromproject.",ifNull(Sorder.project_code,'-1')),'%')  ".
				" And ifNull(Sorder.Costcent_Code,'-1')  Like Concat(ifNull(".$fromcostcent.",ifNull(Sorder.Costcent_Code,'-1')),'%')  ".
				" And ifNull(SorderDt.warehouse_code,'-1') Like Concat(ifNull(". $fromwarehouse .",ifNull(SorderDt.warehouse_code,'-1')),'%')  ";

if ($confirm == 1)
	$query= $query." And ifNull(Sorder.Sorder_confirmed,0) = 1 ";
else if ($confirm == 2)
	$query= $query." And ifNull(Sorder.Sorder_confirmed,0) != 1 ";
						  
if ($whexist > 0 && $FI_RepRestrictWarehouse == 1)
	$query= $query." And SorderDt.warehouse_code In (select distinct warehouse_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['useraccount']."')  ";  
if ($groupexist > 0)
	$query= $query." And Items.group_code In (select distinct group_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['useraccount']."')  ";  

$query= $query." ) Q1 ";

$query = $query." ) Q2 ";

if($prtsubdt != 1) $query = $query." Group By MasterCode, SorderReference ";
                //" Group By Groupby1Code, Groupby2Code, Groupby3Code, MasterCode, DetailCode ";
$query = $query." Order by Groupby1Code, Groupby2Code, Groupby3Code, MasterCode, if($masterby=1, SorderReference, Null), DetailCode  ";				
	
//echo $query; exit;

$ArrayTotalByReport   = Array();
$ArrayTotalByMaster   = Array();
$ArrayTotalByGroup1   = Array();
$ArrayTotalByGroup2   = Array();
$ArrayTotalByGroup3   = Array();

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

$HeaderByCode = '';

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

$result = mysql_query($query,$connection) or die(mysql_error());
while($rows=mysql_fetch_row($result)){

   // if(($masterby == 1 && $prtsubdt == 1) || ($masterby == 2 && 1 == 1)) {
  	// Master By Options Names and Totals
		if (($prtdt == 1 && 1 == 1) && (($MasterByCode != $rows[6] && $MasterByCode != '') || ($MainGroup3 != $rows[4] && $MainGroup3 != '') || ($MainGroup2 != $rows[2] && $MainGroup2 != '') || ($MainGroup1 != $rows[0] && $MainGroup1 != ''))) {
				
			echo "<tr><td><hr width='100%' color='black' size='1'></td></tr>";
				
			$StyleClass  = 'totals';
			if ($masterby == 1) $TotalsLabel = 'Total by Client';
			else $TotalsLabel = 'Total by Item';
			DisplayTotals($masterby, $prtsubdt, $prtpend, $ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $StyleClass) ;

		}
			
		//Group By Options Level 3 Totals
		if ( ($groupby3 != 1 && $prtdt == 1) && (($MainGroup3 != $rows[4] && $MainGroup3 != '') || ($MainGroup2 != $rows[2] && $MainGroup2 != '') || ($MainGroup1 != $rows[0] && $MainGroup1 != ''))  ){
			
			echo "<tr>";
			echo "   <td><hr width='100%' color='black' size='1'></td>";
			echo "</tr>";
					
			$StyleClass  = 'grouplevel3total';
			$TotalsLabel = 'Total Group '.$groupby3name.' : '. str_replace('*',' --> ',$groupby3code);
			DisplayTotals($masterby, $prtsubdt, $prtpend, $ArrayTotalByGroup3, $DecimalBase, $TotalsLabel, $StyleClass) ;
						
		}
			
		//Group By Options Level 2 Totals
		if ( ($groupby2 != '' && ($prtdt == 1 || $groupby3 != 1)) && (($MainGroup2 != $rows[2] && $MainGroup2 != '') || ($MainGroup1 != $rows[0] && $MainGroup1 != ''))  ){
		  
			echo "<tr>";
			echo "   <td><hr width='100%' color='black' size='1'></td>";
			echo "</tr>";
					

			$StyleClass  = 'grouplevel2total';
			$TotalsLabel = 'Total Group '.$groupby2name.' : '.$groupby2code;
			DisplayTotals($masterby, $prtsubdt, $prtpend, $ArrayTotalByGroup2, $DecimalBase, $TotalsLabel, $StyleClass) ;
			
		}
			
		//Group By Options Level 1 Totals
		if ( ($groupby1 != '' && ($prtdt == 1 || $groupby2 != '' || $groupby3 != 1)) && ($MainGroup1 != $rows[0] && $MainGroup1 != '') ){
		  
			echo "<tr>";
			echo "   <td><hr width='100%' color='black' size='1'></td>";
			echo "</tr>";
					
			
			$StyleClass  = 'grouplevel1total';
			$TotalsLabel = 'Total Group '.$groupby1name.' : '.$groupby1code;
			DisplayTotals($masterby, $prtsubdt, $prtpend, $ArrayTotalByGroup1, $DecimalBase, $TotalsLabel, $StyleClass) ;

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

	}
		
	//Group By Options Level 2 Names 
	if ( ($groupby2 != '' && ($prtdt == 1 || $groupby3 != 1)) && ($MainGroup2 == '' || $MainGroup2 != $rows[2])  ){
			
		$groupby2code = '';
		if ($rows[2] == -1)
		    $groupby2code = '';
		else
            $groupby2code = $rows[2];			
			   
		echo "<tr height='20'>";
		echo "   <td align='left' valign='top' class='grouplevel2'>Group by  ". $groupby2name." :&nbsp;&nbsp;". 
		         str_replace('*',' --> ',$groupby2code) ." - ".
				 str_replace('*',' --> ',$rows[3]) ."</td>";
		echo "</tr>"; 
				
						
		$MainGroup2   = $rows[2];
		$groupby2desc = $rows[3];
		
		
		$MainGroup3   = '';
		$groupby3desc = '';	
		$MasterByCode = '';
		$MasterByName = '';
		$HeaderByCode = '';
		
		unset($ArrayTotalByMaster);
		unset($ArrayTotalByGroup2);		
		unset($ArrayTotalByGroup3);
		
	}
		
	//Group By Options Level 3 Names 
	if ( ($groupby3 != 1 && $prtdt == 1) && ($MainGroup3 == '' || $MainGroup3 != $rows[4])  ){
	
		$groupby3code = '';
		if ($rows[4] == -1)
		    $groupby3code = '';
		else
            $groupby3code = $rows[4];			
			   
		echo "<tr>";
		echo "   <td align='left' valign='top' class='grouplevel3'>Group by  ". $groupby3name." :&nbsp;&nbsp;". 
			         str_replace('*',' --> ',$groupby3code) ."&nbsp;&nbsp; - &nbsp;&nbsp;".
			         str_replace('*',' --> ',$rows[5]) ."</td>";
		echo "</tr>"; 
				
		echo "<tr>";
		echo "   <td align='left' valign='top'>&nbsp;</td>";
		echo "</tr>"; 
						
		$MainGroup3   = $rows[4];
		$groupby3desc = $rows[5];
		
		$MasterByCode = '';
		$MasterByName = '';
		$HeaderByCode = '';
		
		unset($ArrayTotalByMaster);	
		unset($ArrayTotalByGroup3);
		
	}
	
	if ($MasterByCode == '' || $MasterByCode != $rows[6]) { 
		if($prtsubdt == 0 && $prtdt == 1 && $MasterByCode != $rows[6] && $MasterByCode != '') {
			echo "<tr><td><hr width='100%' color='black' size='1'></td></tr>";
		}	
		//if($prtsubdt == 1 && $prtdt == 1) {
			echo "<tr class='group'><td>".$rows[6]." - ".$rows[7]."</td></tr>";
			echo "<tr><td>&nbsp;</td></tr>";
		//}
    
		$MasterByCode = $rows[6];
		$MasterByName = $rows[7];
		
		$HeaderByCode = '';
		
		unset($ArrayTotalByMaster);

	}
	
	if ($HeaderByCode == '' || $HeaderByCode != $rows[10]) { 
	
		if($prtdt == 1) {
			if ($masterby == 1) {
				echo "<tr><td>";
				echo "<table  border='0' width='100%' align='center' class='master' style='table-layout:fixed' cellpadding='0' cellspacing='0'>";
				echo " <col width=80>
					   <col width=80>
					   <col width=100>
					   <col width=140>
					   <col width=160>
					   <col width=100>";
				echo "<tr>";
				echo "   <td align='left' valign='top'>". $rows[10] ."</td>";
				echo "   <td align='left' valign='top'>". $rows[11] ."</td>";
				echo "   <td align='left' valign='top'>". $rows[12] ."</td>";
				echo "   <td align='left' valign='top'>". $rows[13] ."</td>";
				echo "   <td align='left' valign='top'>". $rows[14] ."</td>";
				echo "   <td align='right' valign='top'>". format_currency($rows[23], $DecimalBase) ."</td>";
				echo "</tr>"; 	
				echo "</table>";	
				echo "</td></tr>";	   
				
			}	
			else if ($masterby == 2) {
				echo "<tr><td>";
				echo "<table  border='0' width='100%' align='center' class='master' style='table-layout:fixed' cellpadding='0' cellspacing='0'>";
				echo " <col width=120>
					   <col width=200>
					   <col width=80>
					   <col width=60>";
					   
				if ($prtpend == 1) echo"<col width=60>";
				
				echo " <col width=50>
					   <col width=90>
					   <col width=90>
					   <col width=120>";
				echo "<tr>";
				echo "   <td align='left' valign='top'>". $rows[15] ."</td>";
				echo "   <td align='left' valign='top'>". $rows[16] ."</td>";
				echo "   <td align='left' valign='top'>". $rows[17] ."</td>";
				echo "   <td align='right' valign='top'>". number_format($rows[19], $DecimalBase) ."</td>";
				
				if ($prtpend == 1)
					echo "<td align='right' valign='top'>". number_format($rows[24], $DecimalBase) ."</td>";
					
				echo "   <td align='center' valign='top'>". $rows[18] ."</td>";
				echo "   <td align='right' valign='top'>". format_currency($rows[20], $DecimalBase) ."</td>";
				echo "   <td align='right' valign='top'>". format_currency($rows[21], $DecimalBase) ."</td>";
				echo "   <td align='right' valign='top'>". format_currency($rows[22], $DecimalBase) ."</td>";
				echo "</tr>"; 	
				echo "</table>";	
				echo "</td></tr>";
			}
		}
    
		$HeaderByCode = $rows[10];
	}
	
	
	
	if ($prtdt == 1 && $prtsubdt == 1) {
		if ($masterby == 1) {
			echo "<tr><td>";
			echo "<table  border='0' width='100%' align='center' class='detail' style='table-layout:fixed' cellpadding='0' cellspacing='0'>";
			echo " <col width=30>
				   <col width=120>
				   <col width=200>
				   <col width=80>
				   <col width=60>";
				   
			if ($prtpend == 1) echo"<col width=60>";	   
			
			echo " <col width=50>
				   <col width=90>
				   <col width=90>
				   <col width=120>";
			echo "<tr>";
			echo "   <td align='left' valign='top'>&nbsp;</td>";
			echo "   <td align='left' valign='top'>". $rows[15] ."</td>";
			echo "   <td align='left' valign='top'>". $rows[16] ."</td>";
			echo "   <td align='left' valign='top'>". $rows[17] ."</td>";
			echo "   <td align='right' valign='top'>". number_format($rows[19], $DecimalBase) ."</td>";
			
			if ($prtpend == 1)
				echo "<td align='right' valign='top'>". number_format($rows[24], $DecimalBase) ."</td>";
					
			echo "   <td align='center' valign='top'>". $rows[18] ."</td>";
			echo "   <td align='right' valign='top'>". format_currency($rows[20], $DecimalBase) ."</td>";
			echo "   <td align='right' valign='top'>". format_currency($rows[21], $DecimalBase) ."</td>";
			echo "   <td align='right' valign='top'>". format_currency($rows[22], $DecimalBase) ."</td>";
			echo "</tr>"; 	
			echo "</table>";	
			echo "</td></tr>";
		}	
		else if ($masterby == 2) {
			echo "<tr><td>";
			echo "<table  border='0' width='100%' align='center' class='detail' style='table-layout:fixed' cellpadding='0' cellspacing='0'>";
			echo " <col width=30>
				   <col width=80>
				   <col width=80>
				   <col width=100>
			 	   <col width=200>
				   <col width=200>";
			echo "<tr>";
			echo "   <td align='left' valign='top'>&nbsp;</td>";
			echo "   <td align='left' valign='top'>". $rows[10] ."</td>";
			echo "   <td align='left' valign='top'>". $rows[11] ."</td>";
			echo "   <td align='left' valign='top'>". $rows[12] ."</td>";
			echo "   <td align='left' valign='top'>". $rows[13] ."</td>";
			echo "   <td align='left' valign='top'>". $rows[14] ."</td>";
			echo "</tr>"; 	
			echo "</table>";	
			echo "</td></tr>";	   
		}
	}
	
		
	
		
		
	$ArrayTotalByMaster['Qty']       = $ArrayTotalByMaster['Qty']       + $rows[19];
	$ArrayTotalByMaster['DiscAmt']   = $ArrayTotalByMaster['DiscAmt']   + $rows[21];
	$ArrayTotalByMaster['TotalAmt']  = $ArrayTotalByMaster['TotalAmt']  + $rows[22];
	$ArrayTotalByMaster['QtyRemain'] = $ArrayTotalByMaster['QtyRemain'] + $rows[24];
	
	$ArrayTotalByReport['Qty']       = $ArrayTotalByReport['Qty']       + $rows[19];
	$ArrayTotalByReport['DiscAmt']   = $ArrayTotalByReport['DiscAmt']   + $rows[21];
	$ArrayTotalByReport['TotalAmt']  = $ArrayTotalByReport['TotalAmt']  + $rows[22];
	$ArrayTotalByReport['QtyRemain'] = $ArrayTotalByReport['QtyRemain'] + $rows[24];
	
	$ArrayTotalByGroup1['Qty']       = $ArrayTotalByGroup1['Qty']       + $rows[19];
	$ArrayTotalByGroup1['DiscAmt']   = $ArrayTotalByGroup1['DiscAmt']   + $rows[21];
	$ArrayTotalByGroup1['TotalAmt']  = $ArrayTotalByGroup1['TotalAmt']  + $rows[22];
	$ArrayTotalByGroup1['QtyRemain'] = $ArrayTotalByGroup1['QtyRemain'] + $rows[24];
	
	$ArrayTotalByGroup2['Qty']       = $ArrayTotalByGroup2['Qty']       + $rows[19];
	$ArrayTotalByGroup2['DiscAmt']   = $ArrayTotalByGroup2['DiscAmt']   + $rows[21];
	$ArrayTotalByGroup2['TotalAmt']  = $ArrayTotalByGroup2['TotalAmt']  + $rows[22];
	$ArrayTotalByGroup2['QtyRemain'] = $ArrayTotalByGroup2['QtyRemain'] + $rows[24];
	
	$ArrayTotalByGroup3['Qty']       = $ArrayTotalByGroup3['Qty']       + $rows[19];
	$ArrayTotalByGroup3['DiscAmt']   = $ArrayTotalByGroup3['DiscAmt']   + $rows[21];
	$ArrayTotalByGroup3['TotalAmt']  = $ArrayTotalByGroup3['TotalAmt']  + $rows[22];
	$ArrayTotalByGroup3['QtyRemain'] = $ArrayTotalByGroup3['QtyRemain'] + $rows[24];
	

}

//if(($masterby == 1 && $prtsubdt == 1) || ($masterby == 2 && 1 == 1)) {
	// Display Totals By Master	
	if ($MasterByCode != '' && $prtdt == 1 ) { //&& $prtsubdt == 1
				
		echo "<tr><td><hr width='100%' color='black' size='1'></td></tr>";
				
		$StyleClass  = 'totals';
		if ($masterby == 1) $TotalsLabel = 'Total by Client';
		else $TotalsLabel = 'Total by Item';
		DisplayTotals($masterby, $prtsubdt, $prtpend, $ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $StyleClass) ;

				
	}

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

		echo "<tr><td><hr width='100%' color='black' size='1'></td></tr>";
					
		$StyleClass  = 'grouplevel3total';
		$TotalsLabel = 'Total Group '.$groupby3name.' : '. str_replace('*',' --> ',$groupby3code);
		DisplayTotals($masterby, $prtsubdt, $prtpend, $ArrayTotalByGroup3, $DecimalBase, $TotalsLabel, $StyleClass) ;

	}

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

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

		$StyleClass  = 'grouplevel2total';
		$TotalsLabel = 'Total Group '.$groupby2name.' : '.$groupby2code;
		DisplayTotals($masterby, $prtsubdt, $prtpend, $ArrayTotalByGroup2, $DecimalBase, $TotalsLabel, $StyleClass) ;

	}

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

		echo "<tr><td><hr width='100%' color='black' size='1'></td></tr>";				
			
		$StyleClass  = 'grouplevel1total';
		$TotalsLabel = 'Total Group '.$groupby1name.' : '.$groupby1code;
		DisplayTotals($masterby, $prtsubdt, $prtpend, $ArrayTotalByGroup1, $DecimalBase, $TotalsLabel, $StyleClass) ;

	}

		
	// Display Totals By Report		

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


	$StyleClass  = 'summary';
	$TotalsLabel = 'Totals';
	DisplayTotals($masterby, $prtsubdt, $prtpend, $ArrayTotalByReport, $DecimalBase, $TotalsLabel, $StyleClass) ;
//}
	
	
echo "</table>";

function CreateTableHeader($PMasterBy, $PStyleClass) {
	echo "<table  border='0' width='100%' align='center' class='".$PStyleClass."' style='table-layout:fixed' cellpadding='0' cellspacing='0'>";
	
	if($PMasterBy == 2)
		echo" <col width=30>";
		
	echo" <col width=80>
		  <col width=80>
		  <col width=100>
		  <col width=140>
		  <col width=160>
		  <col width=100>";

	echo"<tr>";	  
	
	if($PMasterBy == 2)
		echo"	<th align='left'>&nbsp;</th>";
		
	echo"	<th align='left'>Reference</th>
			<th align='left'>Date</th>
			<th align='left'>Client Code</th>
			<th align='left'>Name</th>
			<th align='left'>Remark</th>
			<th align='center'>Total Amount</th>";	
	echo"</tr>";
	

}

function CreateTableDetail($PMasterBy, $PPrtPend, $PStyleClass) {
	echo "<table  border='0' width='100%' align='center' class='".$PStyleClass."' style='table-layout:fixed' cellpadding='0' cellspacing='0'>";
	
	if($PMasterBy == 1)
		echo" <col width=30>";
		
	echo" <col width=120>
		  <col width=200>
		  <col width=80>
		  <col width=60>";
		  
	if($PPrtPend == 1)	  
		echo" <col width=60>";
		
	echo" <col width=50>
		  <col width=90>
		  <col width=90>
		  <col width=120>";

	echo"<tr>";	

	if($PMasterBy == 1)
		echo"	<th align='left'>&nbsp;</th>";
		
	echo"	<th align='left'>Item Code</th>
			<th align='left'>Description</th>
			<th align='center'>Warehouse</th>
			<th align='center'>Quantity</th>";
			
	if($PPrtPend == 1)
		echo"<th align='center'>Remain Qty</th>";
			
	echo"	<th align='center'>Currency</th>
			<th align='center'>Unit Price</th>
			<th align='center'>Discount Amt</th>
			<th align='center'>Total Amount</th>";	
	echo"</tr>";
	

}

function DisplayTotals($PMasterBy, $PPrtSubDt, $PPrtPend, $PArrayTotal, $PDecimalBase, $PTotalsLabel, $PStyleClass) {
	echo "<tr><td>";
	echo "<table  border='0' width='100%' align='center' class='master' style='table-layout:fixed' cellpadding='0' cellspacing='0'>";
	
	if ($PPrtSubDt == 1) {
		if($PMasterBy == 1)
			echo" <col width=30>";
			
		echo" <col width=120>
			  <col width=200>
			  <col width=80>
			  <col width=60>";
			  
		if($PPrtPend == 1)	  
			echo" <col width=60>";	  
			
		echo" <col width=50>
			  <col width=90>
			  <col width=90>
			  <col width=120>";

		echo "<tr class='".$PStyleClass."'>";
		
		if($PMasterBy == 1)
			echo "   <td align='left'  valign='top' >&nbsp;</td>";
			
		echo "   <td align='left'  valign='top' colspan='3' >".$PTotalsLabel."</td>";
		echo "   <td align='right' valign='top' >". number_format($PArrayTotal['Qty'], $PDecimalBase) ."</td>";
		
		if($PPrtPend == 1)
			echo "   <td align='right' valign='top' >". number_format($PArrayTotal['QtyRemain'], $PDecimalBase) ."</td>";
			
		echo "   <td align='left'  valign='top'  colspan='2'>&nbsp;</td>";
		echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['DiscAmt'], $PDecimalBase) ."</td>";
		echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['TotalAmt'], $PDecimalBase) ."</td>";
		echo "</tr>"; 
	} else {
		if($PMasterBy == 2)
			echo" <col width=30>";
			
		echo" <col width=80>
			  <col width=80>
			  <col width=100>
			  <col width=140>
			  <col width=160>
			  <col width=100>";

		echo "<tr class='".$PStyleClass."'>";
		
		if($PMasterBy == 2)
			echo"	<td align='left'>&nbsp;</td>";
			
		echo "   <td align='left'  valign='top' colspan='5' >".$PTotalsLabel."</td>";
		echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['TotalAmt'], $PDecimalBase) ."</td>";
		echo"</tr>";
	}
	
	echo "</table>"; 
	echo "</td></tr>";
	
}

function format_currency($amount, $DecimalBase) { 

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

function current_server_time($connection){

  $string="Select date_format(NOW(),'%Y-%m-%d %h:%i %p') ";
  $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;
}

function GetSQLValueString($theValue, $theType) 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "Null";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "Null";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
      break;
  }
  return $theValue;
}

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

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

?>