<?php

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

print <<< HERE
<HTML>
<HEAD>
<TITLE> Daily Report </TITLE>
<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.master th { font-size: 13px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
				 }
				 
table.master td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }
table.master tr.group { font-size: 14px; 
                        font-weight: bold;
                        font-family:Times-New-Roman;
                      }					 
				 
table.master td.grouplevel1 { font-size: 14px; 
							  font-weight: bold;
                              font-family:Times-New-Roman;
						      color: #0000FF;
							  background-color: #F0F0F0;
                            }				 									  
table.master td.grouplevel2 { font-size: 14px; 
                              font-family:Times-New-Roman;
						      color: #FF0000;
							  background-color: #F0F0F0;
                            }

table.master td.grouplevel3 { font-size: 13px; 
							  font-style: italic;
                              font-family:Times-New-Roman;
						      color: #336600;
							  background-color: #F0F0F0;
                            }					 
				 
			   
	

table.totals td { font-size: 13px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                }
table.grouplevel1total td { font-size: 14px; 
							font-weight: bold;
							font-family:Times-New-Roman;
							color: #0000FF;
							background-color: #F0F0F0;
						   }				 
table.grouplevel3total td { font-size: 13px; 
							font-style: italic;
							font-family:Times-New-Roman;
							color: #336600;
							background-color: #F0F0F0;
						  }				 
table.grouplevel2total td { font-size: 14px; 
							font-family:Times-New-Roman;
							color: #FF0000;
							background-color: #F0F0F0;
						  }				   
				
table.detail th { font-size: 12px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
				 }				 
				
table.detail td { font-size: 11px; 
                  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");

//maroun 30.03.2011
$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 from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultsetup)){
  extract($rows);
}

$querymodule=" Select ifNull(module_delivery,0) As Module_Delivery From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$querylog=" select ifNull(FI_RepRestrictProject,0) As FI_RepRestrictProject, ifNull(FI_RepRestrictCostcenter,0) As FI_RepRestrictCostcenter ".
          " 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);


$querymasterproject=" select distinct Masterproject from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
					" where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
					" and (Masterproject is not null and Masterproject != '') ";
$projectmasterresult = mysql_query($querymasterproject,$connection) or die(mysql_error());
$projectmasterexist   = mysql_num_rows($projectmasterresult);


$querymastercostcenter=" select distinct Mastercostcenter from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
					   " where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
					   " and (Mastercostcenter is not null and Mastercostcenter != '') ";
$costcentermasterresult = mysql_query($querymastercostcenter,$connection) or die(mysql_error());
$costcentermasterexist   = mysql_num_rows($costcentermasterresult);


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


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

if ($jvtype == '') $alltypes = 1;
//if (empty($jvtype))   $jvtype = 'null';      

$jvtypelen = 0;
if (!empty($jvtype))   $jvtypelen = strlen($jvtype);

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

$SelectedOptions = "Filter by: <br>";
if ($fromdate != '')      $SelectedOptions .= "-> Date From: ". $fromdate . "  To: ". $todate ."<br>";	
if ($displaycurr != '')   $SelectedOptions .= "-> Currency: ". $displaycurr ."<br>";	
if ($fromledger != '')    $SelectedOptions .= "-> Ledger From: ". $fromledger . "  To: ". $toledger ."<br>";
if ($fromproject != '')   $SelectedOptions .= "-> Project From: ". $fromproject . "<br>";
if ($fromcst != '')  	  $SelectedOptions .= "-> Costcent From: ". $fromcst . "<br>";
if ($cltprj != '')    	  $SelectedOptions .= "-> Client Project From: ". $cltprj . "<br>";
if ($cltcst != '')  	  $SelectedOptions .= "-> Client Costcent From: ". $cltcst . "<br>";
if ($subproj != '') 	  $SelectedOptions .= "-> Project Include: ". $subproj . "<br>";
if ($subcostcent != '')	  $SelectedOptions .= "-> Costcent Include: ". $subcostcent . "<br>";

if (!empty($fromdate))
   $fromdate = explodeword($fromdate);
if (!empty($todate))
   $todate = explodeword($todate);     

$fromcur	     = GetSQLValueString($fromcur, 'text');   
$fromledger      = GetSQLValueString($fromledger, 'text');
$toledger        = GetSQLValueString($toledger, 'text');
$fromproject     = GetSQLValueString($fromproject, 'text');
$fromcst  		 = GetSQLValueString($fromcst, 'text');
$cltprj     	 = GetSQLValueString($cltprj, 'text');
$cltcst      	 = GetSQLValueString($cltcst, 'text');
$fromdate  	   	 = GetSQLValueString($fromdate, 'date');
$todate          = GetSQLValueString($todate, 'date'); 
$subproj 	     = GetSQLValueString($subproj, 'text');
$subcostcent     = GetSQLValueString($subcostcent, 'text');  



$groupby1name = '';
$groupby2name = '';   
$groupby3name = '';
$QryGroupby1Code = '';
$QryGroupby2Code = '';
$QryGroupby3Code = '';
$QryGroupby1Name = '';
$QryGroupby2Name = '';
$QryGroupby3Name = '';

$SelProject = 0;
$SelMasterProject = 0;
$SelCostCenter = 0;
$SelMasterCostCenter = 0;

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 == 20 ) {	
			$SelProject 	  = 1;
			$groupby3name    .= 'Transaction Project(Parent)';
			$QryGroupby3Code .= 'ifNull(ParentProjectCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentProjectName,"None")';
		}
		else if ($pair == 4 ) {	
			$SelProject 	  = 1;
			$groupby3name    .= 'Transaction Project(Detail)';
			$QryGroupby3Code .= 'ifNull(ProjectCode,"None")';
			$QryGroupby3Name .= 'ifNull(ProjectName,"None")';
		}
		else if ($pair == 21 ) {	
			$SelMasterProject = 1;
			$groupby3name 	 .= 'Archieve Project(Parent)';
			$QryGroupby3Code .= 'ifNull(ParentMasterProjectCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentMasterProjectName,"None")';
		}
		else if ($pair == 5 ) {	
			$SelMasterProject = 1;
			$groupby3name 	 .= 'Archieve Project(Detail)';
			$QryGroupby3Code .= 'ifNull(MasterProjectCode,"None")';
			$QryGroupby3Name .= 'ifNull(MasterProjectName,"None")';
		}
		else if ($pair == 22 ) {	
			$SelCostCenter 	  = 1;
			$groupby3name    .= 'Transaction Costcenter(Parent)';	
			$QryGroupby3Code .= 'ifNull(ParentCostcentCode,"None")';
			$QryGroupby3Name .= 'ifNull(ParentCostcentName,"None")';
		}
		else if ($pair == 6 ) {	
			$SelCostCenter 	  = 1;
			$groupby3name    .= 'Transaction Costcenter(Detail)';	
			$QryGroupby3Code .= 'ifNull(CostcentCode,"None")';
			$QryGroupby3Name .= 'ifNull(CostcentName,"None")';
		}
		else if ($pair == 23 ) {
			$SelMasterCostCenter = 1;
			$groupby3name 	 	.= 'Archieve Costcenter(Parent)';	
			$QryGroupby3Code 	.= 'ifNull(ParentMasterCostcentCode,"None")';
			$QryGroupby3Name 	.= 'ifNull(ParentMasterCostcentName,"None")';
		}
		else if ($pair == 7 ) {
			$SelMasterCostCenter = 1;
			$groupby3name 	 	.= 'Archieve Costcenter(Detail)';	
			$QryGroupby3Code 	.= 'ifNull(MasterCostcentCode,"None")';
			$QryGroupby3Name 	.= 'ifNull(MasterCostcentName,"None")';
		}
		else if ($pair == 9 ) {	
			$groupby3name    .= 'Business Type';
			$QryGroupby3Code .= 'ifNull(BusinessType,"None")';
			$QryGroupby3Name .= 'ifNull(BusinessType,"None")';
		}
		else if ($pair == 10 )	{
			$groupby3name 	.= 'Profit Center';
			$QryGroupby3Code .= 'ifNull(ProfitCenter,"None")';
			$QryGroupby3Name .= 'ifNull(ProfitCenter,"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 == 20 ) {	
		$SelProject 	  = 1;
		$groupby1name    .= 'Transaction Project(Parent)';
		$QryGroupby1Code .= 'ifNull(ParentProjectCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentProjectName,"None")';
	}
	else if ($groupby1 == 4 ) {	
		$SelProject 	  = 1;
		$groupby1name    .= 'Transaction Project(Detail)';
		$QryGroupby1Code .= 'ifNull(ProjectCode,"None")';
		$QryGroupby1Name .= 'ifNull(ProjectName,"None")';
	}
	else if ($groupby1 == 21 ) {	
		$SelMasterProject = 1;
		$groupby1name 	 .= 'Archieve Project(Parent)';
		$QryGroupby1Code .= 'ifNull(ParentMasterProjectCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentMasterProjectName,"None")';
	}
	else if ($groupby1 == 5 ) {	
		$SelMasterProject = 1;
		$groupby1name 	 .= 'Archieve Project(Detail)';
		$QryGroupby1Code .= 'ifNull(MasterProjectCode,"None")';
		$QryGroupby1Name .= 'ifNull(MasterProjectName,"None")';
	}
	else if ($groupby1 == 22 ) {
		$SelCostCenter 	  = 1;
		$groupby1name    .= 'Transaction Costcenter(Parent)';	
		$QryGroupby1Code .= 'ifNull(ParentCostcentCode,"None")';
		$QryGroupby1Name .= 'ifNull(ParentCostcentName,"None")';
	}
	else if ($groupby1 == 6 ) {	
		$SelCostCenter 	  = 1;
		$groupby1name    .= 'Transaction Costcenter(Detail)';	
		$QryGroupby1Code .= 'ifNull(CostcentCode,"None")';
		$QryGroupby1Name .= 'ifNull(CostcentName,"None")';
	}
	else if ($groupby1 == 23 ) {
		$SelMasterCostCenter = 1;
		$groupby1name 	 	.= 'Archieve Costcenter(Parent)';	
		$QryGroupby1Code 	.= 'ifNull(ParentMasterCostcentCode,"None")';
		$QryGroupby1Name 	.= 'ifNull(ParentMasterCostcentName,"None")';
	}
	else if ($groupby1 == 7 ) {
		$SelMasterCostCenter = 1;
		$groupby1name 	 	.= 'Archieve Costcenter(Detail)';	
		$QryGroupby1Code 	.= 'ifNull(MasterCostcentCode,"None")';
		$QryGroupby1Name 	.= 'ifNull(MasterCostcentName,"None")';
	}
	else if ($groupby1 == 9 ) {	
		$groupby1name    .= 'Business Type';
		$QryGroupby1Code .= 'ifNull(BusinessType,"None")';
		$QryGroupby1Name .= 'ifNull(BusinessType,"None")';
	}
	else if ($groupby1 == 10 )	{
		$groupby1name 	 .= 'Profit Center';
		$QryGroupby1Code .= 'ifNull(ProfitCenter,"None")';
		$QryGroupby1Name .= 'ifNull(ProfitCenter,"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 == 20 ) {
		$SelProject 	  = 1;
		$groupby2name    .= 'Transaction Project(Parent)';
		$QryGroupby2Code .= 'ifNull(ParentProjectCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentProjectName,"None")';
	}
	else if ($groupby2 == 4 ) {	
		$SelProject 	  = 1;
		$groupby2name    .= 'Transaction Project(Detail)';
		$QryGroupby2Code .= 'ifNull(ProjectCode,"None")';
		$QryGroupby2Name .= 'ifNull(ProjectName,"None")';
	}
	else if ($groupby2 == 21 ) {
		$SelMasterProject = 1;
		$groupby2name 	 .= 'Archieve Project(Parent)';
		$QryGroupby2Code .= 'ifNull(ParentMasterProjectCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentMasterProjectName,"None")';
	}
	else if ($groupby2 == 5 ) {	
		$SelMasterProject = 1;
		$groupby2name 	 .= 'Archieve Project(Detail)';
		$QryGroupby2Code .= 'ifNull(MasterProjectCode,"None")';
		$QryGroupby2Name .= 'ifNull(MasterProjectName,"None")';
	}
	else if ($groupby2 == 22 ) {	
		$SelCostCenter 	  = 1;
		$groupby2name    .= 'Transaction Costcenter(Parent)';	
		$QryGroupby2Code .= 'ifNull(ParentCostcentCode,"None")';
		$QryGroupby2Name .= 'ifNull(ParentCostcentName,"None")';
	}
	else if ($groupby2 == 6 ) {	
		$SelCostCenter 	  = 1;
		$groupby2name    .= 'Transaction Costcenter(Detail)';	
		$QryGroupby2Code .= 'ifNull(CostcentCode,"None")';
		$QryGroupby2Name .= 'ifNull(CostcentName,"None")';
	}
	else if ($groupby2 == 23 ) {
		$SelMasterCostCenter = 1;
		$groupby2name 	 	.= 'Archieve Costcenter(Parent)';	
		$QryGroupby2Code 	.= 'ifNull(ParentMasterCostcentCode,"None")';
		$QryGroupby2Name 	.= 'ifNull(ParentMasterCostcentName,"None")';
	}
	else if ($groupby2 == 7 ) {
		$SelMasterCostCenter = 1;
		$groupby2name 	 	.= 'Archieve Costcenter(Detail)';	
		$QryGroupby2Code 	.= 'ifNull(MasterCostcentCode,"None")';
		$QryGroupby2Name 	.= 'ifNull(MasterCostcentName,"None")';
	}
	else if ($groupby2 == 9 ) {	
		$groupby2name    .= 'Business Type';
		$QryGroupby2Code .= 'ifNull(BusinessType,"None")';
		$QryGroupby2Name .= 'ifNull(BusinessType,"None")';
	}
	else if ($groupby2 == 10 )	{
		$groupby2name 	.= 'Profit Center';
		$QryGroupby2Code .= 'ifNull(ProfitCenter,"None")';
		$QryGroupby2Name .= 'ifNull(ProfitCenter,"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
<table width="100%" border="0" align="left" >
<tr><td>
<table width="100%" border="0" align="center">
<tr>
  <td width='30%'><b>$CompanyName</b></td>
  <td width='50%' align='center'><font size=4><b>Daily 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 "<br>".$dt[1]." ".$dt[2];

 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;

	
$queryjvtype="select type_name from jourtype order by type_name";
  
if (($alltypesdebit == 1) || ($alltypesdebit == 0 && $jvtype_db == '')){
	$resultjvtype = mysql_query($queryjvtype,$connection) or die(mysql_error());
	
	while($jvtype1=mysql_fetch_row($resultjvtype)){
		if ($jvtype_db == '') $jvtype_db = "'".$jvtype1[0]."'";
		else 	$jvtype_db = $jvtype_db.",'".$jvtype1[0]."'";
	}
}


if (($alltypescredit == 1) || ($alltypescredit == 0 && $jvtype_cr == '')){
	$resultjvtype = mysql_query($queryjvtype,$connection) or die(mysql_error());
	
	while($jvtype1=mysql_fetch_row($resultjvtype)){
		if ($jvtype_cr == '') $jvtype_cr = "'".$jvtype1[0]."'";
		else 	$jvtype_cr = $jvtype_cr.",'".$jvtype1[0]."'";
	}
}

if (empty($jvtype_root) || $alltypesroot == 0) $jvtype_root = "''";

$query = '';

$query = $query." Select Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, Groupby3Code, Groupby3Name, ".
				" journal_date, ledger_number, ledger_name, Journal_type, journal_id, journal_refgovernment, ".
				" jourtypegroup, typenumber, DebitAmount, CreditAmount, orderbydate ".
				" from ( ";
								
$query = $query." select journal_date, ledger_number, ledger_name, Journal_type, journal_id, journal_refgovernment, jourtypegroup, ".
			    " typenumber, journaldt_id, orderbydate, sum(DebitAmount) as DebitAmount, sum(CreditAmount) as CreditAmount, ";
$query = $query.$QryGroupby1Code . $QryGroupby1Name.
				$QryGroupby2Code . $QryGroupby2Name.
				$QryGroupby3Code . $QryGroupby3Name;		 

$query = $query." From ( ";

if ($reptype == 1) {
	$query = $query." select date_format(journal.journal_date ,'%d/%m/%Y') as journal_date, journaldt.ledger_number, ledger.ledger_name, journal.Journal_type, journal.journal_id, journal.journal_refgovernment, ";
	$query = $query." if (Journal.journal_type in (".$jvtype_root.") or $alltypesroot = 1, ifnull(jourtype1.jourtype_group,'NULL'), ifnull(jourtype.jourtype_group,'NULL')) as jourtypegroup, journaldt.journaldt_id, journal.journal_date as orderbydate, ";
	$query = $query." if(journal.Journal_type='CL' or journal.Journal_type='EX' or journal.Journal_type='JV' or journal.Journal_type='OP', journal.Journal_refgovernment, ifNull(Q1.typenumber, trans.trans_reference)) as typenumber ";
}
else {
	$query = $query." select -1 as journal_date, -1 as ledger_number, -1 as ledger_name, journal.Journal_type as Journal_type, -1 as journal_id, -1 as journal_refgovernment, ";
	$query = $query." if (Journal.journal_type in (".$jvtype_root.") or $alltypesroot = 1, ifnull(jourtype1.jourtype_group,'NULL'), ifnull(jourtype.jourtype_group,'NULL')) as jourtypegroup, ";
	$query = $query." -1 as journaldt_id, -1 as orderbydate, -1 as typenumber ";
}

if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {										
	$query=$query.", ifnull(if (Journal.journal_type in (".$jvtype_db."), if(Journaldt_dbcd = 'D', if(upper($curr)='".$Base1."', Cstjour_amount1, if(upper($curr)='".$Base2."', Cstjour_amount2, Cstjour_amount)),0),0),0) as DebitAmount ".
				  ", ifnull(if (Journal.journal_type in (".$jvtype_cr."), if(Journaldt_dbcd = 'C', if(upper($curr)='".$Base1."', Cstjour_amount1, if(upper($curr)='".$Base2."', Cstjour_amount2, Cstjour_amount)),0),0),0) as CreditAmount";
}
else
{
	$query=$query.", ifnull(if (Journal.journal_type in (".$jvtype_db."), if(Journaldt_dbcd = 'D', if(upper($curr)='".$Base1."', journaldt_amount1, if(upper($curr)='".$Base2."', journaldt_amount2, journaldt_amount)),0),0),0) as DebitAmount ".
				  ", ifnull(if (Journal.journal_type in (".$jvtype_cr."), if(Journaldt_dbcd = 'C', if(upper($curr)='".$Base1."', journaldt_amount1, if(upper($curr)='".$Base2."', journaldt_amount2, journaldt_amount)),0),0),0) as CreditAmount";
}

if ($SelProject == 1 || $SelCostCenter == 1) 
	$query = $query.", if($SelProject = 1, ifNull(CstJour.project_code,'None'), '') As ProjectCode, if($SelProject = 1, Project.Project_Name, '') As ProjectName, if($SelCostCenter = 1, ifNull(CstJour.Costcent_Code,'None'), '') As CostcentCode, if($SelCostCenter = 1, Costcent.Costcent_name, '') As CostcentName, ".
					" if($SelProject = 1, ifNull(Project.Parent_Code, Project.Project_Code), '') As ParentProjectCode, if($SelProject = 1, Project.Project_Name, '') As ParentProjectName, ".
					" if($SelCostCenter = 1, ifNull(Costcent.Parent_Code, Costcent.Costcent_Code), '') As ParentCostcentCode, if($SelCostCenter = 1, Costcent.Costcent_Name, '') As ParentCostcentName ";
else
	$query = $query.", Null As ProjectCode, Null As ProjectName, Null As CostcentCode, Null As CostcentName, Null As ParentProjectCode, Null As ParentProjectName, Null As ParentCostcentCode, Null As ParentCostcentName ";
						
if ($SelMasterProject == 1 || $SelMasterCostCenter == 1) 
	$query = $query.", if($SelMasterProject = 1, ifNull(Clients.project_code,'None'), '') As MasterProjectCode, if($SelMasterProject = 1, Project1.Project_Name, '') As MasterProjectName, if($SelMasterCostCenter = 1, ifNull(Clients.Costcenter_Code,'None'), '') As MasterCostcentCode, if($SelMasterCostCenter = 1, Costcent1.Costcent_name, '') As MasterCostcentName, ".
					" if($SelMasterProject = 1, ifNull(Project1.Parent_Code, Clients.Project_Code), '') As ParentMasterProjectCode, if($SelMasterProject = 1, Project1.Project_Name, '') As ParentMasterProjectName, ".
					" if($SelMasterCostCenter = 1, ifNull(Costcent1.Parent_Code, Clients.CostCenter_Code), '') As ParentMasterCostcentCode, if($SelMasterCostCenter = 1, Costcent1.Costcent_name, '') As ParentMasterCostcentName ";
else
	$query = $query.", Null As MasterProjectCode, Null As MasterProjectName, Null As MasterCostcentCode, Null As MasterCostcentName, Null As ParentMasterProjectCode, Null As ParentMasterProjectName, Null As ParentMasterCostcentCode, Null As ParentMasterCostcentName ";
					
					
$query = $query . ", Clients.Client_BusinessType As BusinessType, Clients.ProfitCenter_Code As ProfitCenter ".
                  " from journaldt ".
                  " Inner join Journal on JournalDt.Journal_id = Journal.Journal_id ".
				  " Inner join Ledger on JournalDt.Ledger_number = Ledger.Ledger_number ".
				  " left join Clients on Clients.Ledger_number = journaldt.Ledger_number ".
				  " left join jourtype on jourtype.type_name = journal.Journal_type ".
				  " left join jourtype as jourtype1 on jourtype1.type_name = jourtype.Related_Type ";
				  
if ($SelMasterProject == 1 || $SelMasterCostCenter == 1) {
	$query= $query." Left Join Project As Project1 on Clients.Project_Code = Project1.Project_Code ".
				   " Left Join Costcent As Costcent1 on Clients.Costcenter_Code = Costcent1.Costcent_Code ";
}

if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {
	$query = $query." Left outer Join CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ".
					" Left Join Project on CstJour.Project_Code = Project.Project_Code ".
				    " Left Join Costcent on CstJour.Costcent_Code = Costcent.Costcent_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 != '') ".
						"			  ) PrjQry on CstJour.project_code like concat(PrjQry.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 != '') ".
						"			  ) CstQry on CstJour.Costcent_code like concat(CstQry.costcent_code,'%')  ";								 
                    		
}

if ($reptype == 1) {
	$query= $query." Left Join ( ";
	$innerquery= $innerquery." select -1 as journalid, null as typenumber from dual ";

	/*if (strchr($jvtype,'CV')!='' or strchr($jvtype,'DV')!='' or strchr($jvtype,'PV')!='' or strchr($jvtype,'RV')!='' or $alltypes == 1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select trans.journal_id as journalid, trans.trans_reference as typenumber ".
								 " from trans ".
								 " where 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')) ";
	}*/
	if (strchr($jvtype,'AD')!='' or $alltypes == 1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select adjustment.journal_id as journalid, adjustment.adjustment_reference as typenumber ".
								 " from adjustment ".
								 " where date_format(adjustment.Adjustment_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(adjustment.Adjustment_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(adjustment.Adjustment_Date,'%Y-%m-%d')) ";
	}
	if ((strchr($jvtype,'SI')!='' or strchr($jvtype,'SR')!='' or strchr($jvtype,'DR')!='' or strchr($jvtype,'DI')!='' or $alltypes == 1) and $Module_Delivery==0) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select deliveries.journal_id as journalid, deliveries.Delivery_Reference as typenumber ".
								 " from deliveries ".
								 " where 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')) ";
	}
	if ((strchr($jvtype,'SI')!='' or strchr($jvtype,'SR')!='' or $alltypes == 1) and $Module_Delivery==1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select sales.journal_id as journalid, sales.sale_reference as typenumber ".
								 " from sales ".
								 " where 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')) ";
	}
	if (strchr($jvtype,'FV')!='' or $alltypes == 1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select assets.journal_id as journalid, assets.assets_ref as typenumber ".
								 " from assets ".
								 " where date_format(assets.Assets_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(assets.Assets_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(assets.Assets_date,'%Y-%m-%d')) ";
	}
	if (strchr($jvtype,'JP')!='' or $alltypes == 1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select purchasesjv.journal_id as journalid, purchasesjv.PurchaseJV_Reference as typenumber ".
								 " from purchasesjv ".
								 " where date_format(purchasesjv.PurchaseJV_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(purchasesjv.PurchaseJV_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(purchasesjv.PurchaseJV_Date,'%Y-%m-%d')) ";
	}
	if (strchr($jvtype,'JS')!='' or $alltypes == 1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select salesjv.journal_id as journalid, salesjv.salesjv_reference as typenumber ".
								 " from salesjv ".
								 " where date_format(salesjv.SalesJV_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(salesjv.SalesJV_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(salesjv.SalesJV_Date,'%Y-%m-%d')) ";
	}
	if (strchr($jvtype,'PI')!='' or strchr($jvtype,'PR')!=''  or $alltypes == 1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select purchases.journal_id as journalid, purchases.purchase_reference as typenumber ".
								 " from purchases ".
								 " where date_format(purchases.Purchase_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(purchases.Purchase_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(purchases.Purchase_Date,'%Y-%m-%d')) ";
	}
	if (strchr($jvtype,'RI')!='' or strchr($jvtype,'RR')!='' or $alltypes == 1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select retail.journal_id as journalid, retail.sale_reference as typenumber ".
								 " from retail ".
								 " where date_format(retail.Sale_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(retail.Sale_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(retail.Sale_Date,'%Y-%m-%d')) ";
	}
	if (strchr($jvtype,'SE')!='' or $alltypes == 1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select stkeval.journal_id as journalid, stkeval.stkeval_reference as typenumber ".
								 " from stkeval ".
								 " where date_format(stkeval.StkEval_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(stkeval.StkEval_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(stkeval.StkEval_Date,'%Y-%m-%d')) ";
	}
	if (strchr($jvtype,'TP')!=''  or $alltypes == 1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select transp.journal_id as journalid, transp.transp_reference as typenumber ".
								 " from transp ".
								 " where date_format(transp.Transp_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(transp.Transp_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(transp.Transp_date,'%Y-%m-%d')) ";
	}
	if (strchr($jvtype,'TV')!='' or strchr($jvtype,'SV')!=''  or $alltypes == 1) {
		$innerquery= $innerquery." union ";
		$innerquery= $innerquery." select salejour.journal_id as journalid, salejour.salejour_reference as typenumber ".
								 " from salejour ".
								 " where date_format(salejour.SaleJour_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(salejour.SaleJour_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(salejour.SaleJour_Date,'%Y-%m-%d')) ";
	}

	$query= $query.$innerquery." ) Q1 on Q1.journalid = journal.journal_id  "; 
	$query = $query. " left join trans on trans.journal_id = journal.journal_id ";
	
}	

$query = $query ." where date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) ".
				 " and ledger.Ledger_number between ifNull(".$fromledger.",ledger.Ledger_number) and ifNull(". $toledger.",ledger.Ledger_number) ";
				  


if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {	
	$query= $query." And upper(ifNull(CstJour.project_code,'-1')) like ifNull(upper(".$fromproject."), upper(ifNull(CstJour.project_code,'-1'))) ".
   				   " And upper(ifNull(CstJour.Costcent_Code,'-1')) like ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1')))   ";
                    	
}	

if ($cltcst != 'Null' || $cltprj != 'Null') {
    $query= $query." And upper(ifNull(Clients.CostCenter_Code,'-1')) like ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))   ";
	$query= $query." And upper(ifNull(Clients.Project_Code,'-1')) like ifNull(upper(".$cltprj."), upper(ifNull(Clients.Project_Code,'-1')))   ";
}

if ($subproj != 'Null' && ($SelProject == 1 || $SelCostCenter == 1))
	$query= $query." And ifNull(CstJour.project_code,'-1')  Like ".$subproj; 
if ($subcostcent != 'Null' && ($SelProject == 1 || $SelCostCenter == 1))
	$query= $query." And ifNull(CstJour.Costcent_Code,'-1')  Like ".$subcostcent;  

if (($fromcur != 'Null' ) and ($curr == 'null'))
	$query = $query." and Upper(JournalDt.Currency_code) = Upper(".$fromcur.") ";

if (empty($jvtype))   $jvtype = 'null';      
$query = $query." and (($alltypes = 1 and 1 = 1) or ($alltypes = 0 and $jvtypelen = 0 and 1 = 1) or ($alltypes = 0 and $jvtypelen > 0 and Journal.Journal_type in ($jvtype)) ) ";  


if ($ledgernumbers != ''){
	$query=$query." and ( 1=1 ";
	
	$trims = explode('-', $ledgernumbers);

	foreach ($trims as $trim) {
		$trims1 = explode(":", $trim);
		
		$query = $query ."and if(Journal.journal_type='".$trims1[0]."',journaldt.ledger_number=0 ";
		
		$ledgers  = $trims1[1];
		$ledgers = explode(",", $ledgers);
		foreach ($ledgers as $ledger) {
			$query = $query ." or journaldt.ledger_number like '".$ledger."%'";
		}
		
		$query = $query .",1=1)  ";
	}
	
	$query = $query." )";
}
	

$query = $query." 	  order by ifnull(jourtypegroup,'NULL'),JournalDt.Journal_date,journal_refgovernment ";
$query = $query." 	) Q2 ".
		   	    " 	Group By Groupby1Code, Groupby2Code, Groupby3Code, ifnull(jourtypegroup, 'NULL'), orderbydate, ledger_number, journal_refgovernment, journaldt_id ".
				" 	Order by Groupby1Code, Groupby2Code, Groupby3Code, ifnull(jourtypegroup, 'NULL'), orderbydate, journal_refgovernment  ";
$query = $query." ) Q3 ".
		   	    " Order by Groupby1Code, Groupby2Code, Groupby3Code, ifnull(jourtypegroup, 'NULL'), orderbydate, journal_refgovernment  ";				


//echo $query;exit;

 
echo "<table  border='0' width='100%' align='center' class='master' style='table-layout:fixed; border-collapse:collapse;' cellpadding='0' cellspacing='0'>";
echo"	<col width=100>
	    <col width=90>
	    <col width=200>
	    <col width=85>
	    <col width=80>
	    <col width=100>
		<col width=130>
		<col width=130>";

if ($reptype == 1) {		
	echo"<tr>
		<th align='center'>Date</th>
		<th align='center'>Cust. / Suplr./<br>Exps. Code</th>
		<th align='center'>Particulars</th>
		<th align='center'>Voucher Type</th>
		<th align='center'>Type number</th>
		<th align='center'>Voucher Number</th>
		<th align='center'>Debit Amt<br> (Inwards only)</th>
		<th align='center'>Credit Amt<br> (Outwards only) </th>";
} else {
	echo"<tr>
		<th align='center' colspan='2'>Group Description</th>
		<th align='center'>Debit Amt (Inwards only)</th>
		<th align='center' colspan='2'>Credit Amt (Outwards only) </th>
		<th align='center' colspan='3'>&nbsp;</th>";
}		
	
echo"</tr>";
	
echo"<tr><td colspan='18'><hr width='100%' color='black' size='2'></td></tr>";
 

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

$MasterGroup = '';

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


$resultdaily=mysql_query($query,$connection) or die(mysql_error());
while($rowsjournal=mysql_fetch_row($resultdaily)){

	// Master By Options Names and Totals
    if ((($MasterGroup != $rowsjournal[12] && $MasterGroup != '') || ($MainGroup3 != $rowsjournal[4] && $MainGroup3 != '') || ($MainGroup2 != $rowsjournal[2] && $MainGroup2 != '') || ($MainGroup1 != $rowsjournal[0] && $MainGroup1 != ''))  && $reptype == 1) {
		    
		echo "<tr>";
		echo "   <td colspan='8'><hr width='100%' color='black' size='1'></td>";
		echo "</tr>";
			
		echo "<tr><td colspan='8'>";

		// Display Totals By Master	
		$StyleClass  = 'totals';
		$TotalsLabel = 'Total Group '.$MasterGroup;
		DisplayTotals($reptype, $ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $StyleClass);	

		echo"</td></tr>";
		echo "<tr><td colspan='8'>&nbsp;</td></tr>";	
			
	}
	
	//Group By Options Level 3 Totals
	if ( ($groupby3 != 1) && (($MainGroup3 != $rowsjournal[4] && $MainGroup3 != '') || ($MainGroup2 != $rowsjournal[2] && $MainGroup2 != '') || ($MainGroup1 != $rowsjournal[0] && $MainGroup1 != ''))  ){
	  
		echo "<tr>";
		echo "   <td colspan='8'><hr width='100%' color='black' size='1'></td>";
		echo "</tr>";
				
		echo "<tr><td colspan='8'>";

		$StyleClass  = 'grouplevel3total';
		$TotalsLabel = 'Total Group '.$groupby3name.' : '. str_replace('*',' --> ',$groupby3code);
		DisplayTotals($reptype, $ArrayTotalByGroup3, $DecimalBase, $TotalsLabel, $StyleClass);

		echo"</td></tr>";
															
	}
		
	//Group By Options Level 2 Totals
	if ( ($groupby2 != '') && (($MainGroup2 != $rowsjournal[2] && $MainGroup2 != '') || ($MainGroup1 != $rowsjournal[0] && $MainGroup1 != ''))  ){
	  
		echo "<tr>";
		echo "   <td colspan='8'><hr width='100%' color='black' size='1'></td>";
		echo "</tr>";
				
		echo "<tr><td colspan='8'>";

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

		echo"</td></tr>";
			   
	}
		
	//Group By Options Level 1 Totals
	if ( ($groupby1 != '') && ($MainGroup1 != $rowsjournal[0] && $MainGroup1 != '')  ){
	  
		echo "<tr>";
		echo "   <td colspan='8'><hr width='100%' color='black' size='1'></td>";
		echo "</tr>";
				
		echo "<tr><td colspan='8'>";

		$StyleClass  = 'grouplevel1total';
		$TotalsLabel = 'Total Group '.$groupby1name.' : '.$groupby1code;
		DisplayTotals($reptype, $ArrayTotalByGroup1, $DecimalBase, $TotalsLabel, $StyleClass);

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

	}
		
	//Group By Options Level 3 Names 
	if ( ($groupby3 != 1) && ($MainGroup3 == '' || $MainGroup3 != $rowsjournal[4])  ){
			
		$groupby3code = '';
		if ($rowsjournal[4] == -1)
		   $groupby3code = '';
		else
            $groupby3code = $rowsjournal[4];			
			   
		echo "<tr>";
		echo "   <td align='left' valign='top' colspan='8' class='grouplevel3'>Group by  ". $groupby3name." :&nbsp;&nbsp;". 
		         str_replace('*',' --> ',$groupby3code) ."&nbsp;&nbsp; - &nbsp;&nbsp;".
		         str_replace('*',' --> ',$rowsjournal[5]) ."</td>";
		echo "</tr>"; 
				
		echo "<tr>";
		echo "   <td align='left' valign='top' colspan='8'>&nbsp;</td>";
		echo "</tr>"; 
						
		$MainGroup3   = $rowsjournal[4];
		$groupby3desc = $rowsjournal[5];
		
		$MasterGroup  = '';
			
		unset($ArrayTotalByMaster);	
		unset($ArrayTotalByGroup3);
	}
	
	if (($MasterGroup == '' || $MasterGroup!= $rowsjournal[12]) && $reptype == 1) {

		echo "<tr class='group'>";
		echo "   <td align='left' valign='top' colspan='8' > Group by ". $rowsjournal[12] ."</td>";
		echo "</tr>"; 
		echo "<tr><td colspan='8'>&nbsp;</td></tr>";
		
	    $MasterGroup = $rowsjournal[12];
		
		unset($ArrayTotalByMaster);
	}
	

	if ($reptype == 1) {
	
		echo "<tr>";
		echo "<td align='left'   valign='top'>". $rowsjournal[6] ."</td>";
		echo "<td align='left'   valign='top'>". $rowsjournal[7] ."</td>";
		echo "<td align='left'   valign='top'>". $rowsjournal[8] ."</td>";
		echo "<td align='center' valign='top'>". $rowsjournal[9] ."</td>";
		echo "<td align='center' valign='top'>". $rowsjournal[13] ."</td>";
		echo "<td align='center' valign='top'>". $rowsjournal[11] ."</td>";
		echo "<td align='right'  valign='top'>". format_currency($rowsjournal[14], $DecimalBase) ."</td>";
		echo "<td align='right'  valign='top'>". format_currency($rowsjournal[15], $DecimalBase) ."</td>";
		echo"</tr>";
	} else {
		echo "<tr>";
		echo "<td align='left'   valign='top' colspan='2'>". $rowsjournal[12] ."</td>";
		echo "<td align='right'  valign='top' >". format_currency($rowsjournal[14], $DecimalBase) ."</td>";
		echo "<td align='right'  valign='top' colspan='2'>". format_currency($rowsjournal[15], $DecimalBase) ."</td>";
		echo "<td align='left'   valign='top' colspan='3'>&nbsp;</td>";
		echo"</tr>";
	}
	
	$ArrayTotalByMaster['Debit']  = $ArrayTotalByMaster['Debit']  + $rowsjournal[14];
	$ArrayTotalByMaster['Credit'] = $ArrayTotalByMaster['Credit'] + $rowsjournal[15];
	$ArrayTotalByGroup1['Debit']  = $ArrayTotalByGroup1['Debit']  + $rowsjournal[14];
	$ArrayTotalByGroup1['Credit'] = $ArrayTotalByGroup1['Credit'] + $rowsjournal[15];
	$ArrayTotalByGroup2['Debit']  = $ArrayTotalByGroup2['Debit']  + $rowsjournal[14];
	$ArrayTotalByGroup2['Credit'] = $ArrayTotalByGroup2['Credit'] + $rowsjournal[15];
	$ArrayTotalByGroup3['Debit']  = $ArrayTotalByGroup3['Debit']  + $rowsjournal[14];
	$ArrayTotalByGroup3['Credit'] = $ArrayTotalByGroup3['Credit'] + $rowsjournal[15];
	$ArrayTotalByReport['Debit']  = $ArrayTotalByReport['Debit']  + $rowsjournal[14];
	$ArrayTotalByReport['Credit'] = $ArrayTotalByReport['Credit'] + $rowsjournal[15];
	
	
	
}


// Display Totals By Master	
if ($MasterGroup != '') {
		    
	echo "<tr>";
	echo "   <td colspan='8'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
			
	echo "<tr><td colspan='8'>";

	// Display Totals By Master	
	$StyleClass  = 'totals';
	$TotalsLabel = 'Total Group '.$MasterGroup;
	DisplayTotals($reptype, $ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $StyleClass);	

	echo"</td></tr>";
	echo "<tr><td colspan='8'>&nbsp;</td></tr>";	
			
}

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

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

				
	$StyleClass  = 'grouplevel3total';
	$TotalsLabel = 'Total Group '.$groupby3name.' : '. str_replace('*',' --> ',$groupby3code);
	DisplayTotals($reptype, $ArrayTotalByGroup3, $DecimalBase, $TotalsLabel, $StyleClass);

	echo"</td></tr>";
	//echo "<tr><td colspan='3'>&nbsp;</td></tr>";
															
}

//Display Totals By Group Level 2 
if ($groupby2 != ''){

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

				
	$StyleClass  = 'grouplevel2total';
	$TotalsLabel = 'Total Group '.$groupby2name.' : '. str_replace('*',' --> ',$groupby2code);
	DisplayTotals($reptype, $ArrayTotalByGroup2, $DecimalBase, $TotalsLabel, $StyleClass);

	echo"</td></tr>";
	//echo "<tr><td colspan='3'>&nbsp;</td></tr>";
															
}

//Display Totals By Group Level 1 
if ($groupby1 != ''){

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

				
	$StyleClass  = 'grouplevel1total';
	$TotalsLabel = 'Total Group '.$groupby1name.' : '. str_replace('*',' --> ',$groupby1code);
	DisplayTotals($reptype, $ArrayTotalByGroup1, $DecimalBase, $TotalsLabel, $StyleClass);

	echo"</td></tr>";
	//echo "<tr><td colspan='3'>&nbsp;</td></tr>";
															
}

// Totals By Report
echo "<tr>";
echo "  <td colspan='8'>&nbsp;</td>";
echo "</tr>";

echo "  <tr style='background-color: #F0F0F0;'><td colspan='8'>";

$StyleClass  = 'totals';
$TotalsLabel = 'Total';
DisplayTotals($reptype, $ArrayTotalByReport, $DecimalBase, $TotalsLabel, $StyleClass);

echo"	</td></tr>";

echo "</table>";	

	
	
function DisplayTotals($PRepType, $PArrayTotal, $PDecimalBase, $PTotalsLabel, $PStyleClass) {
	
	echo "<table  border='0' align='left' class='".$PStyleClass."' style='table-layout:fixed' cellpadding='0' cellspacing='0'>
			<col width=100>
			<col width=90>
			<col width=200>
			<col width=85>
			<col width=80>
			<col width=100>
			<col width=130>
			<col width=130>";

	if ($PRepType == 1)	{
		echo"<tr>";
		echo "  <td align='right' valign='top' colspan='2'>&nbsp;</td>";
		echo "  <td align='left'  valign='top' colspan='4'>".$PTotalsLabel."</td>";
		echo "	<td align='right' valign='top'>". format_currency($PArrayTotal['Debit'],  $PDecimalBase) ."</td>";
		echo "	<td align='right' valign='top'>". format_currency($PArrayTotal['Credit'], $PDecimalBase) ."</td>";
		echo"</tr>";	
	} else {
		echo"<tr>";
		echo "  <td align='left'  valign='top' colspan='2'>".$PTotalsLabel."</td>";
		echo "	<td align='right' valign='top'>". format_currency($PArrayTotal['Debit'],  $PDecimalBase) ."</td>";
		echo "	<td align='right' valign='top' colspan='2'>". format_currency($PArrayTotal['Credit'], $PDecimalBase) ."</td>";
		echo "  <td align='right' valign='top' colspan='3'>&nbsp;</td>";
		echo"</tr>";	
	}
	
	echo"</table>";
	
}	

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 format_currency($amount, $DecimalBase) { 

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

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;

?>