<?php
 
session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}


print <<< HERE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<TITLE> Aging Report </TITLE>
<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">
<style type="text/css">



/*
table.params td { font-size: 12px; 
                  font-family:Times-New-Roman;
                 }

			 
table.master th { font-size: 14px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
				 }
				 
table.master td { font-size: 12px; 
                  font-family:Times-New-Roman;
				  word-wrap: break-word; 
				  word-break:break-all;
                 }
				 
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  { table-layout:fixed;
				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;
						  }				  
				
	*/			 


</style>




</HEAD>
HERE;
include("config.inc.php");
include("function.inc.php");

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

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

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
//maroun 30.03.2011
$querylog="SELECT print as printaccess from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}


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

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


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


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

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

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

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

//maroun
$querysalesmen=" select distinct clientsalesmen ".
			   " from ".$_SESSION['dbLabel'].".loginstk ".
			   " where user_account='".$_SESSION['useraccount']."' ".
			   " and (clientsalesmen is not null and clientsalesmen != '' ) ";
$salesmenresult = mysql_query($querysalesmen,$connection) or die(mysql_error());
$salesmenexist   = mysql_num_rows($salesmenresult);


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


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

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

$SelectedOptions = "Filter by: <br>";
if ($fromdate != '')      $SelectedOptions .= "-> Date From: ". $fromdate . "  To: ". $todate ."<br>";	
if ($agingdate != '')     $SelectedOptions .= "-> Aging Date: ". $agingdate ."<br>";	
if ($displaycurr != '')   $SelectedOptions .= "-> Currency: ". $displaycurr ."<br>";	
if ($fromledger != '')    $SelectedOptions .= "-> Ledger From: ". $fromledger . "  To: ". $toledger ."<br>";
if ($fromsalesman != '')  $SelectedOptions .= "-> Salesman From: ". $fromsalesman . "  To: ". $tosalesman ."<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($agingdate))
   $agingdate = explodeword($agingdate);   
if (!empty($todate))
   $todate = explodeword($todate);     
      
$fromledger      = GetSQLValueString($fromledger, 'text');
$toledger        = GetSQLValueString($toledger, 'text');
$fromsalesman    = GetSQLValueString($fromsalesman, 'text');
$tosalesman      = GetSQLValueString($tosalesman, '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');   
$agingdate       = GetSQLValueString($agingdate, 'date');   
$rangefrom       = GetSQLValueString($rangefrom, 'double');
$rangeto         = GetSQLValueString($rangeto, 'double');
$subproj 	     = GetSQLValueString($subproj, 'text');
$subcostcent     = GetSQLValueString($subcostcent, 'text');
 
if (empty($duebal)) $duebal = 1;

if ($accountno == 1) {
  $title = 'Suppliers';
  $tablename = 'Suppliers';
}  
else if ($accountno == 2) {
  $title = 'Clients';
  $tablename = 'Clients';
}  
else if ($accountno == 3)  {
  $title = 'Salesmen';
  $tablename = 'Clients';
}     

if ($lastbal == 1) {
	if($balorderby == 1)
		$OrderByCond = 'Q7.Balance Asc';
	else	 
		$OrderByCond = 'Q7.Balance Desc';

} else
{
	if($orderby == 1) 
		$OrderByCond = 'Q7.Ledger_number';
	else	 
		$OrderByCond = 'Q7.Ledger_Name';
}


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

$SelSalesman = 0;
$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 == 3 ) {	
			$SelSalesman 	  = 1;
			$groupby3name    .= 'Salesman';
			$QryGroupby3Code .= 'ifNull(SalesmanCode,"None")';
			$QryGroupby3Name .= 'ifNull(SalesmanName,"None")';
		}
		else 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 == 3 ) {	
	    $SelSalesman 	  = 1;
		$groupby1name    .= 'Salesman';
		$QryGroupby1Code .= 'ifNull(SalesmanCode,"None")';
		$QryGroupby1Name .= 'ifNull(SalesmanName,"None")';
	}
	else 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 == 3 ) {	
		$SelSalesman 	  = 1;
		$groupby2name    .= 'Salesman';
		$QryGroupby2Code .= 'ifNull(SalesmanCode,"None")';
		$QryGroupby2Name .= 'ifNull(SalesmanName,"None")';
	}
	else 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;



echo "<table border=0 width=100% cellspacing=0 cellpadding=0>";

echo "<tr><td align='left'>";
	
if ($prtheader == 1){
	ShowReportHeader("Aging-$title",'landscape', $connection);
} else {
	ShowReportTitle("Aging-$title",'landscape', $connection);
}
		
echo"</td></tr><tbody>";

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

</table>
</td></tr>
HERE;

$queryperiods  = " select period from aging order by period ";
$resultperiods = mysql_query($queryperiods,$connection) or die(mysql_error());
$numrows = mysql_num_rows($resultperiods);

$ArrayPeriods = Array();
$i = 0;
while($rows=mysql_fetch_array($resultperiods)){
	$ArrayPeriods[$i] = $rows[0];
	$i += 1;
}

echo"<tr><td>";
echo "<table width='100%' border='0' class='report-master' align='center' cellpadding='0' cellspacing='0'>";
echo"<thead>";
echo "  <tr><td colspan='3'>";

//Create Table Columns
CreateTableStructure($numrows, $accountno, $shownondues, $riskbal);		

echo"	<tr>";

if ($showdetail == 0 && ($groupby1 != '' || $groupby2 != '' || $groupby3 != 1)) {
	echo"<th align='left' colspan='4'>Grouping Description</th>";
}
else {
    echo"<th align='left'>Account No.</th>
		 <th >Account Name</th>
		 <th>PT</th> 
		 <th>CL</th>";
}



if ($riskbal == 1 && $accountno == 2) {	
	echo "<th align='right'>CheckBal</th>
		  <th align='right'>Balance</th>";
}
	
echo "<th>Cur.</th><th align='right'>Total Bal</th>";
if ($shownondues == 1) {
	if ($duebal	== 1) echo"<th align='right'>Non Dues</th>";
	else echo"<th align='right'>Dues</th>";
}	
echo"<th align='right'>Extra Payment</th>";

$PrevRange = 0;
for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
	echo "<th align='right'>".$PrevRange.'-'.$ArrayPeriods[$d]."</th>";
	$PrevRange = $ArrayPeriods[$d] + 1;
}

echo"<th align='right'> > ".($PrevRange - 1)." </th>";

echo"     </tr>";

echo"	</table></td></tr>";
echo"</thead>";
echo"  <tr><td colspan='3'></td></tr>";


 
$MainCompanyName=explode('_',$_SESSION['dbName']);  
$QueryDir = " Select Concat(CompanyName, '_', DirYear) As DirSchema ".
			" From ".$_SESSION['dbLabel'].".Directories ". 
			" Where Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
			" And ( (ifNull(Date_Format(". $fromdate.",'%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) >= Date_Format(StartFinancialDate,'%Y%m') and ifNull(Date_Format(". $todate.",'%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) <= Date_Format(EndFinancialDate,'%Y%m')) or   ".
			//"  		(ifNull(Date_Format(". $fromdate.",'%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) <= Date_Format(StartFinancialDate,'%Y%m') and ifNull(Date_Format(". $todate.",'%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) >= Date_Format(EndFinancialDate,'%Y%m')) or ".
			"       (Date_Format(StartFinancialDate,'%Y%m') >= ifNull(Date_Format(". $fromdate.",'%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) and Date_Format(StartFinancialDate,'%Y%m') <= ifNull(Date_Format(". $todate.",'%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) ) or ".
            "       (Date_Format(EndFinancialDate,'%Y%m') >= ifNull(Date_Format(". $fromdate.",'%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) and Date_Format(EndFinancialDate,'%Y%m') <= ifNull(Date_Format(". $todate.",'%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) ) ".
			"      )  ".
			" Order By DirYear ";
			
//echo $QueryDir; exit;
$ResultDir=mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir1=mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir2=mysql_query($QueryDir,$connection) or die(mysql_error());
$RowsDirCount = mysql_num_rows($ResultDir);



if ($fromproject != 'Null' || $fromcst != 'Null') {
  $QueryCstJour ='CstJour.Cst_increment is null';
}  else
{
  $QueryCstJour ='True';
}

$result = mysql_query("start transaction", $connection);
$resultvars = mysql_query("set @PrevAmount :=0.0, @PrevBal:=0.0 ,@RecordNum:=0,@VarGrouping:='x' ", $connection);

$queryjournal = '';

if ($showdetail == 0) {
	$queryjournal=  " Select Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, Groupby3Code, Groupby3Name, Null As Ledger_number, Null As Ledger_name, ".
					" CreditLimits, PaymentTerms, ProjectCode, ProjectName, CostcentCode, CostcentName, Currency_code, Sum(PrevDebitAmount), Sum(PrevCreditAmount), ".
					" Sum(PrevBalance), Days, Sum(Balance), Sum(AgingAmount) As AgingAmount, RecordNum, OrdDate, ".
					" Sum(NonDueAmount), Sum(CheckBalance), Sum(TotalBalance), Sum(NotAllocatedAmt), ";
					
					$PrevRange = 0;	
					for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
						$queryjournal= $queryjournal." Sum(Amount".$ArrayPeriods[$d].") As Amount".$ArrayPeriods[$d].", ";
						$PrevRange = $ArrayPeriods[$d] + 1;
					}
					
					$queryjournal= $queryjournal.
						" Sum(Amount".$PrevRange.") As Amount".$PrevRange.
						" from (  ";
}

$queryjournal= $queryjournal.				
				" Select Groupby1Code, Groupby1Name, Groupby2Code, Groupby2Name, Groupby3Code, Groupby3Name, Ledger_number, Ledger_name, CreditLimits, PaymentTerms, ".
				" ProjectCode, ProjectName, CostcentCode, CostcentName, Currency_code, ifNull(PrevDebitAmount,0) as PrevDebitAmount, ifNull(PrevCreditAmount,0) as PrevCreditAmount, ".
				" ifNull(PrevBalance,0) as PrevBalance, Days, ifNull(Balance,0) as Balance, Sum(AgingAmount) As AgingAmount, RecordNum, OrdDate, ".
				" Sum(NonDueAmount) As NonDueAmount, ifNull(CheckBalance,0) as CheckBalance, (ifNull(Balance,0) - ifNull(CheckBalance,0)) As TotalBalance,  ".
				" if(ifNull(Balance,0) > 0, 0, abs(Balance)) As NotAllocatedAmt, ";
				
			$PrevRange = 0;	
			for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
				$queryjournal= $queryjournal." Sum(Amount".$ArrayPeriods[$d].") As Amount".$ArrayPeriods[$d].", ";
				$PrevRange = $ArrayPeriods[$d] + 1;
			}
			
			/*$queryjournal= $queryjournal.
				" Sum(Amount".$PrevRange.") As Amount".$PrevRange.
				" from (  ".
                " Select Q6.Groupby1Code, Q6.Groupby1Name, Q6.Groupby2Code, Q6.Groupby2Name, Q6.Groupby3Code, Q6.Groupby3Name, Q6.Ledger_number, Q6.Ledger_name, ".
				" Q6.CreditLimits, Q6.PaymentTerms, Q6.ProjectCode, Q6.ProjectName, Q6.CostcentCode, Q6.CostcentName, Q6.Currency_code, Q6.PrevDebitAmount, Q6.PrevCreditAmount, ".
				" Q6.PrevBalance, Q6.Days, Q6.Balance, Q6.AgingAmount, Q6.RecordNum, Q6.CheckBalance, Q6.OrdDate, ".
				" if($accountno!=1, if(Q6.TotalCredits >= Q6.PrevBalance, if (Q6.AgingBalance > 0, 0, abs(Q6.AgingBalance)), Q6.AgingBalance), if(Q6.TotalDebits >= Q6.PrevBalance, if (Q6.AgingBalance > 0, 0, Q6.AgingBalance), Q6.AgingBalance)) as AgingBalance, ";
			*/
			$queryjournal= $queryjournal.
				" Sum(Amount".$PrevRange.") As Amount".$PrevRange.
				" from (  ".
                " Select Q6.Groupby1Code, Q6.Groupby1Name, Q6.Groupby2Code, Q6.Groupby2Name, Q6.Groupby3Code, Q6.Groupby3Name, Q6.Ledger_number, Q6.Ledger_name, ".
				" Q6.CreditLimits, Q6.PaymentTerms, Q6.ProjectCode, Q6.ProjectName, Q6.CostcentCode, Q6.CostcentName, Q6.Currency_code, Q6.PrevDebitAmount, Q6.PrevCreditAmount, ".
				" Q6.PrevBalance, Q6.Days, Q6.Balance, Q6.AgingAmount, Q6.RecordNum, Q6.CheckBalance, Q6.OrdDate, ".
				" if($accountno!=1, if(Q6.TotalCredits >= Q6.PrevBalance, if (Q6.AgingBalance > 0, Q6.AgingBalance*-1, abs(Q6.AgingBalance)), Q6.AgingBalance), if(Q6.TotalDebits >= Q6.PrevBalance, if (Q6.AgingBalance > 0, Q6.AgingBalance*-1, Q6.AgingBalance), Q6.AgingBalance)) as AgingBalance, ";
				
			if ($duebal	== 1) {
				$queryjournal = $queryjournal." if(Q6.Days < 0, Q6.AgingAmount, 0) As NonDueAmount, ";
			} else {	
				$queryjournal = $queryjournal." if(Q6.Days >= 0, Q6.AgingAmount, 0) As NonDueAmount, ";
			}
			
			$PrevRange = 0;	
			for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
				if ($duebal	== 1) {
					$queryjournal= $queryjournal." if(".$ArrayPeriods[$d]." > 0, if(Q6.Days Between ".$PrevRange." and ".$ArrayPeriods[$d].",Q6.AgingAmount, 0), Null) As Amount".$ArrayPeriods[$d].", ";
				} else {
					$queryjournal= $queryjournal." if(".$ArrayPeriods[$d]." > 0, if(Q6.Days < 0 and abs(Q6.Days) Between ".$PrevRange." and ".$ArrayPeriods[$d].",Q6.AgingAmount, 0), Null) As Amount".$ArrayPeriods[$d].", ";
				}
				$PrevRange = $ArrayPeriods[$d] + 1;
			}				
			
			if ($duebal	== 1) {
				$queryjournal = $queryjournal." if($PrevRange > 0, if(Q6.Days >= $PrevRange, Q6.AgingAmount, 0), Null) As Amount".$PrevRange;
			} else {
				$queryjournal = $queryjournal." if($PrevRange > 0, if(Q6.Days < 0 and abs(Q6.Days) >= $PrevRange, Q6.AgingAmount, 0), Null) As Amount".$PrevRange;
			}
				
			$queryjournal= $queryjournal.
				" from (  ". 
				" Select Q5.Groupby1Code, Q5.Groupby1Name, Q5.Groupby2Code, Q5.Groupby2Name, Q5.Groupby3Code, Q5.Groupby3Name, Q5.JournalDt_ID, Q5.Ledger_number, Q5.Ledger_name, ".
                " Q5.CreditLimits, Q5.PaymentTerms, Q5.ProjectCode, Q5.ProjectName, Q5.CostcentCode, Q5.CostcentName, Q5.Currency_code, Q5.PrevDebitAmount, Q5.PrevCreditAmount, ".
                " Q5.PrevBalance, Q5.JournalDt_DBCD, Q5.JDate, Q5.OrdDate, Q5.Days, Q5.Balance, Q5.CheckBalance, Q5.TotalCredits, Q5.TotalDebits, ".
				" if((Q5.GroupingOptions != Concat(Q5.Groupby1Code, Q5.Groupby2Code, Q5.Groupby3Code, Q5.Ledger_number, Q5.Currency_code, ifNull(Q5.ProjectCode,''), ifNull(Q5.CostcentCode,''))),@RecordNum:=1,@RecordNum:=(ifNull(@RecordNum,0)+1)) As RecordNum, ".
				" if((Q5.GroupingOptions != Concat(Q5.Groupby1Code, Q5.Groupby2Code, Q5.Groupby3Code, Q5.Ledger_number, Q5.Currency_code, ifNull(Q5.ProjectCode,''), ifNull(Q5.CostcentCode,''))),@PrevBal:=0.0,0), ".
				" IF((Q5.GroupingOptions != Concat(Q5.Groupby1Code, Q5.Groupby2Code, Q5.Groupby3Code, Q5.Ledger_number, Q5.Currency_code, ifNull(Q5.ProjectCode,''), ifNull(Q5.CostcentCode,''))),@hiderow:=0,0), ". 
				" if($accountno!=1, if(@RecordNum=1, @PrevBal:=if(Q5.TotalCredits >= Q5.PrevBalance, (Q5.TotalCredits-Q5.PrevBalance-Q5.AgingAmount), (Q5.PrevBalance-Q5.TotalCredits+Q5.AgingAmount)), @PrevBal:=if(Q5.TotalCredits >= Q5.PrevBalance, (@PrevBal - Q5.AgingAmount), (@PrevBal + Q5.AgingAmount))), ".
				" 					if(@RecordNum=1, @PrevBal:=if(Q5.TotalDebits >= Q5.PrevBalance, if (Q5.PrevBalance>=0, (Q5.TotalDebits-Q5.PrevBalance-Q5.AgingAmount),(Q5.TotalDebits+Q5.PrevBalance-Q5.AgingAmount)), (Q5.PrevBalance-Q5.TotalDebits+Q5.AgingAmount)), @PrevBal:=if(Q5.TotalDebits >= Q5.PrevBalance, (@PrevBal - Q5.AgingAmount), (@PrevBal + Q5.AgingAmount)))) As AgingBalance, ";
			$queryjournal= $queryjournal.	
				" if(Q5.Balance > 0, if(abs(@PrevBal) < Q5.AgingAmount, abs(@PrevBal), Q5.AgingAmount), 0) As AgingAmount,";
			
				//echo $queryjournal;exit;
			$queryjournal= $queryjournal.
				"  if(ifNull(Balance,0) >= 0,IF(@PrevBal < 0 or @hiderow=1,@hiderow:=1, @hiderow:=0), Balance)  AS showrow ".
				"  from (  ".
        		" Select Q4.Groupby1Code, Q4.Groupby1Name, Q4.Groupby2Code, Q4.Groupby2Name, Q4.Groupby3Code, Q4.Groupby3Name, Q4.JournalDt_ID, Q4.Ledger_number, Q4.Ledger_name, ".
                " Q4.CreditLimits, Q4.PaymentTerms, Q4.ProjectCode, Q4.ProjectName, Q4.CostcentCode, Q4.CostcentName, Q4.Currency_code, Q4.PrevDebitAmount, Q4.PrevCreditAmount, ".
				" Q4.PrevBalance, Q4.JournalDt_DBCD, Q4.JDate, Q4.OrdDate, Q4.Days, Q4.Amount as AgingAmount, Q4.Balance, Q4.CheckBalance, Q4.TotalCredits, Q4.TotalDebits, ".
				" @VarGrouping As GroupingOptions, ".
				" @VarGrouping := Concat(Q4.Groupby1Code, Q4.Groupby2Code, Q4.Groupby3Code, Q4.Ledger_number, Q4.Currency_code, ifNull(Q4.ProjectCode,''), ifNull(Q4.CostcentCode,'')) ".
				" from ".
				" ( ".
				" Select Q1.Groupby1Code, Q1.Groupby1Name, Q1.Groupby2Code, Q1.Groupby2Name, Q1.Groupby3Code, Q1.Groupby3Name, Q2.JournalDt_ID, Q1.Ledger_number, Q1.Ledger_name, ".
                " Q1.CreditLimits, Q1.PaymentTerms, Q1.ProjectCode, Q1.ProjectName, Q1.CostcentCode, Q1.CostcentName, Q1.Currency_code, Q1.PrevDebitAmount, Q1.PrevCreditAmount, ".
				" (Q1.PrevDebitAmount - Q1.PrevCreditAmount) As PrevBalance, Q2.JournalDt_DBCD, Q2.JDate, Q2.OrdDate, ifNull(Q2.Days,0) As Days, ifNull(Q2.Amount,0) As Amount, ".
				" (Q1.Balance + (Q1.PrevDebitAmount - Q1.PrevCreditAmount)) As Balance, ifNull(Q1.TotalCredits,0) As TotalCredits, ifNull(Q1.TotalDebits,0) As TotalDebits, ";

if ($riskbal == 1 && $accountno == 2)				
	$queryjournal =	$queryjournal." QCheckBal.CheckBalance As CheckBalance ";
else	
	$queryjournal =	$queryjournal." 0 As CheckBalance ";			
	
$queryjournal =	$queryjournal.	
				" from ".
				"(  ";
				

$j = 0;				
$k = 0; // Count For First Existsing Db
$QueryDirSchema = '';

$QueryDirSchema = " Select Ledger_number, Ledger_name, CreditLimits, ifNull(PaymentTerms,0) As PaymentTerms, Currency_code, ProjectCode, ProjectName, CostcentCode, CostcentName, ";
$QueryDirSchema = $QueryDirSchema.$QryGroupby1Code . $QryGroupby1Name.
								  $QryGroupby2Code . $QryGroupby2Name.
								  $QryGroupby3Code . $QryGroupby3Name;
								
$QueryDirSchema = $QueryDirSchema.
				  ", Sum(PrevDebitAmount) As PrevDebitAmount, Sum(PrevCreditAmount) As PrevCreditAmount, Sum(Balance) As Balance, Sum(TotalCredits) As TotalCredits, Sum(TotalDebits) As TotalDebits ".
				  " from ".
				  " (  ";
					 
// Reading Data For Many Years Or Different Directories					 
while($RowsDir=mysql_fetch_row($ResultDir)){

    $j = $j + 1;    
	//if ($RowsDirCount > 1)
	   $DirSchema = $RowsDir[0];
	//else
       //$DirSchema = '';	
	   
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
	    $k = $k + 1;    
	
					if ($riskbal == 1 && $accountno == 2) 
					   $QueryDirSchema= $QueryDirSchema."  Select clients.Ledger_number As Ledger_number, clients.Ledger_name As Ledger_name, ";
					else
					   $QueryDirSchema= $QueryDirSchema."  Select JournalDt.Ledger_number As Ledger_number, ledger.Ledger_name As Ledger_name,  ";
			
					if ($accountno == 1) {
					  $QueryDirSchema= $QueryDirSchema."Suppliers.Supplier_CreditLimit CreditLimits, Supplier_PaymentTerms PaymentTerms, Null BusinessType, Null ProfitCenter, Null SalesmanCode, Null SalesmanName, ";
					}  
					else if ($accountno == 2) {
					  $QueryDirSchema= $QueryDirSchema."Clients.Client_CreditLimit CreditLimits, Client_PaymentTerms PaymentTerms, Clients.Client_BusinessType As BusinessType, Clients.ProfitCenter_Code As ProfitCenter, Salesmen.Ledger_Number SalesmanCode,Salesmen.Ledger_Name SalesmanName, ";
					}  
					else if ($accountno == 3)  {
					  $QueryDirSchema= $QueryDirSchema."Salesmen.Salesman_CreditLimit CreditLimits, Null PaymentTerms, Null BusinessType, Null ProfitCenter, Salesmen.Ledger_Number SalesmanCode, Salesmen.Ledger_Name SalesmanName, ";
					} 
					
					
					if ($SelProject == 1 || $SelCostCenter == 1) 
						$QueryDirSchema= $QueryDirSchema." 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
						$QueryDirSchema= $QueryDirSchema." 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) 
						$QueryDirSchema= $QueryDirSchema." if($SelMasterProject = 1, ifNull($tablename.project_code,'None'), '') As MasterProjectCode, if($SelMasterProject = 1, Project1.Project_Name, '') As MasterProjectName, if($SelMasterCostCenter = 1, ifNull($tablename.Costcenter_Code,'None'), '') As MasterCostcentCode, if($SelMasterCostCenter = 1, Costcent1.Costcent_name, '') As MasterCostcentName, ".
														 " if($SelMasterProject = 1, ifNull(Project1.Parent_Code, $tablename.Project_Code), '') As ParentMasterProjectCode, if($SelMasterProject = 1, Project1.Project_Name, '') As ParentMasterProjectName, ".
														 " if($SelMasterCostCenter = 1, ifNull(Costcent1.Parent_Code, $tablename.CostCenter_Code), '') As ParentMasterCostcentCode, if($SelMasterCostCenter = 1, Costcent1.Costcent_name, '') As ParentMasterCostcentName, ";
					else
						$QueryDirSchema= $QueryDirSchema." Null As MasterProjectCode, Null As MasterProjectName, Null As MasterCostcentCode, Null As MasterCostcentName, Null As ParentMasterProjectCode, Null As ParentMasterProjectName, Null As ParentMasterCostcentCode, Null As ParentMasterCostcentName, ";
					
					
					
				    $QueryDirSchema= $QueryDirSchema." if(upper($curr) = '".$Base1."', '".$Base1."', if(upper($curr) = '".$Base2."', '".$Base2."', JournalDt.Currency_code)) Currency_code , ";
					
					if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {
				       $QueryDirSchema= $QueryDirSchema." sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) , if(Journaldt_dbcd = 'D', if(upper($curr) = '".$Base1."', ifNull(Cstjour_amount1,Journaldt_amount1), if(upper($curr) = '".$Base2."', ifNull(Cstjour_amount2,Journaldt_amount2), ifNull(Cstjour_amount,Journaldt_amount))), 0),0)) PrevDebitAmount, ".
													    " sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) , if(Journaldt_dbcd = 'C', if(upper($curr) = '".$Base1."', ifNull(Cstjour_amount1,Journaldt_amount1), if(upper($curr) = '".$Base2."', ifNull(Cstjour_amount2,Journaldt_amount2), ifNull(Cstjour_amount,Journaldt_amount))), 0),0)) PrevCreditAmount, ".
													    " Sum(if(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')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D', ifNull(Cstjour_amount1,Journaldt_amount1), (-1)*ifNull(Cstjour_amount1,Journaldt_amount1)), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D', ifNull(Cstjour_amount2,Journaldt_amount2), (-1)*ifNull(Cstjour_amount2,Journaldt_amount2)), if(Journaldt_dbcd = 'D', ifNull(Cstjour_amount,Journaldt_amount), (-1)*ifNull(Cstjour_amount,Journaldt_amount)))),0) ) Balance, ".
														" Sum(if(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')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'C'   AND NOT(JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount1,Journaldt_amount1), 0), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'C'   AND NOT(JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount2,Journaldt_amount2), 0), if(Journaldt_dbcd = 'C'   AND NOT(JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount,Journaldt_amount), 0))),0) ) TotalCredits, ".
														" Sum(if(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')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount1,Journaldt_amount1), 0), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount2,Journaldt_amount2), 0), if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount,Journaldt_amount), 0))),0) ) TotalDebits ";
                    } else {
					   $QueryDirSchema= $QueryDirSchema." sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) , if(Journaldt_dbcd = 'D', if(upper($curr) = '".$Base1."', Journaldt_amount1, if(upper($curr) = '".$Base2."', Journaldt_amount2, Journaldt_amount)), 0),0)) PrevDebitAmount, ".
													    " sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) , if(Journaldt_dbcd = 'C', if(upper($curr) = '".$Base1."', Journaldt_amount1, if(upper($curr) = '".$Base2."', Journaldt_amount2, Journaldt_amount)), 0),0)) PrevCreditAmount, ".
													    " Sum(if(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')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D', Journaldt_amount1, (-1)*Journaldt_amount1), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D', Journaldt_amount2, (-1)*Journaldt_amount2), if(Journaldt_dbcd = 'D', Journaldt_amount, (-1)*Journaldt_amount))),0) ) Balance, ".
														" Sum(if(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')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'C' AND NOT(JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount1, 0), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'C' AND NOT(JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount2, 0), if(Journaldt_dbcd = 'C' AND NOT(JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount, 0))),0) ) TotalCredits, ".
														" Sum(if(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')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount1, 0), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount2, 0), if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount, 0))),0) ) TotalDebits ";
					}
					
					$QueryDirSchema= $QueryDirSchema.
				    " from $DirSchema.JournalDt As JournalDt ".
				    " Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ";
				    //" Inner join $tablename on JournalDt.Ledger_number = $tablename.Ledger_number ";
					
					
					if ($riskbal == 1 && $accountno == 2) {
					   $QueryDirSchema= $QueryDirSchema."   Inner join ".
													"   ( select  clients.ledger_number, ledger.Ledger_name, clients.ledger_number accountnumber, Clients.Client_CreditLimit, Clients.Client_PaymentTerms, Clients.Client_BusinessType, Clients.ProfitCenter_Code, Clients.Salesmen_Code, Clients.project_code, Clients.CostCenter_Code  ".
													"     from clients ".
													"     Inner join ledger on clients.Ledger_number = ledger.Ledger_number ".
													"     where Clients.Ledger_Number between ifNull(".$fromledger.",Clients.Ledger_Number) and ifNull(". $toledger.",Clients.Ledger_Number) ".
													"     And upper(ifNull(Clients.CostCenter_Code,'-1')) like ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))   ".
													//maroun
													"     And upper(ifNull(Clients.Project_Code,'-1')) like ifNull(upper(".$cltprj."), upper(ifNull(Clients.Project_Code,'-1')))   ".
													"     union ".
                                                    "     select clients.ledger_number, ledger.Ledger_name, concat(acctypesetup.ledger_number,substr(clients.ledger_number,5,length(clients.ledger_number))) accountnumber, Clients.Client_CreditLimit, Clients.Client_PaymentTerms, Clients.Client_BusinessType, Clients.ProfitCenter_Code, Clients.Salesmen_Code, Clients.project_code, Clients.CostCenter_Code ".
                                                    "     from clients ".
													"     Inner join ledger on clients.Ledger_number = ledger.Ledger_number ".
													"     left join acctype on substr(clients.ledger_number,1,4) = acctype.acctype_ledger ".
													"     left join acctypesetup on upper(acctypesetup.type_code) = upper(acctype.acctype_code) ".
													"     where Clients.Ledger_Number between ifNull(".$fromledger.",Clients.Ledger_Number) and ifNull(". $toledger.",Clients.Ledger_Number) ".
													"     And upper(ifNull(Clients.CostCenter_Code,'-1')) like ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))   ".
													//maroun
													"     And upper(ifNull(Clients.Project_Code,'-1')) like ifNull(upper(".$cltprj."), upper(ifNull(Clients.Project_Code,'-1')))   ".
													"     And acctypesetup.ledger_number Is Not Null ".
													"    ) Clients on JournalDt.Ledger_Number = Clients.accountnumber  ";
													
					} else {
					   $QueryDirSchema= $QueryDirSchema." Inner join ledger on JournalDt.Ledger_number = ledger.Ledger_number ".
				              					        " Inner join $tablename on JournalDt.Ledger_number = $tablename.Ledger_number ";
					}
			   
					if ($SelMasterProject == 1 || $SelMasterCostCenter == 1) {
						$QueryDirSchema= $QueryDirSchema." Left Join Project As Project1 on $tablename.Project_Code = Project1.Project_Code ".
														 " Left Join Costcent As Costcent1 on $tablename.Costcenter_Code = Costcent1.Costcent_Code ";
					}

					if ($accountno == 2 || $accountno == 3 )			   
					  $QueryDirSchema= $QueryDirSchema."  Left Join Salesmen As Salesmen On Clients.Salesmen_Code = Salesmen.Ledger_Number ";

                    if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {
						$QueryDirSchema= $QueryDirSchema." Left outer Join $DirSchema.CstJour As 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)
							$QueryDirSchema= $QueryDirSchema." Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
															 "			    where loginstk.user_account='".$_SESSION['useraccount']."' ".
															 "              and (project_code is not null and project_code != '') ".
															 "			  ) PrjQry on CstJour.project_code like concat(PrjQry.project_code,'%') ";
														 
						if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
							$QueryDirSchema= $QueryDirSchema." Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
															 "			    where loginstk.user_account='".$_SESSION['useraccount']."' ".
															 "              and (costcent_code is not null and costcent_code != '') ".
															 "			  ) CstQry on CstJour.Costcent_code like concat(CstQry.costcent_code,'%')  ";								 
                    		
					}

					
					//maroun
					if (($accountno == 2 || $accountno == 3) && $projectmasterexist > 0) {	
					    $QueryDirSchema= $QueryDirSchema." inner join ( select distinct Masterproject from ".$_SESSION['dbLabel'].".loginstk ".
														 "			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
														 "             and (Masterproject is not null and Masterproject != '') ".
														 "			 ) PrjMasterQry on Clients.project_code like concat(PrjMasterQry.Masterproject,'%') ";
						
					}
			
					//maroun
					if (($accountno == 2 || $accountno == 3) && $costcentermasterexist > 0) {	
					    $QueryDirSchema= $QueryDirSchema." inner join ( select distinct Mastercostcenter from ".$_SESSION['dbLabel'].".loginstk ".
														 "			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
														 "             and (Mastercostcenter is not null and Mastercostcenter != '') ".
														 "			 ) CstMasterQry on Clients.CostCenter_Code like concat(CstMasterQry.Mastercostcenter,'%') ";
						
					}
						
						
						
						
                    if ($riskbal == 1 && $accountno == 2)
					    //$QueryDirSchema= $QueryDirSchema." where JournalDt.JournalDt_Amount1 <> 0 ";
						$QueryDirSchema= $QueryDirSchema." where 1 = 1 ";
					else {	
					    if ($accountno == 3) {
							$QueryDirSchema= $QueryDirSchema." where Salesmen.Ledger_number between ifNull(".$fromledger.",Salesmen.Ledger_number) and ifNull(". $toledger.",Salesmen.Ledger_number)  ";
															 //" And JournalDt.JournalDt_Amount1 <> 0 ";
						} else {							 
						    $QueryDirSchema= $QueryDirSchema." where JournalDt.Ledger_number between ifNull(".$fromledger.",JournalDt.Ledger_number) and ifNull(". $toledger.",JournalDt.Ledger_number)  ";
															 //" And JournalDt.JournalDt_Amount1 <> 0 ";
						}								 
					}
					
					//maroun
					if (($accountno == 2 || $accountno == 3) && $salesmenexist > 0) {
						$QueryDirSchema = $QueryDirSchema . " and clients.Salesmen_Code in 
															(select distinct clientsalesmen from ".$_SESSION['dbLabel'].".loginstk where user_account = '".$_SESSION['useraccount']."'
															 and (clientsalesmen !='' and clientsalesmen is not null)
															)";	
					}
					
					if ($RowsDirCount > 1 && $k != 1)	
						$QueryDirSchema= $QueryDirSchema." And Journal.Journal_Type <> 'OP' ";
					
                    if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {					
						$QueryDirSchema= $QueryDirSchema." 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 ($subproj != 'Null' && ($SelProject == 1 || $SelCostCenter == 1))
						$QueryDirSchema= $QueryDirSchema." And ifNull(CstJour.project_code,'-1')  Like ".$subproj; 
					if ($subcostcent != 'Null' && ($SelProject == 1 || $SelCostCenter == 1))
						$QueryDirSchema= $QueryDirSchema." And ifNull(CstJour.Costcent_Code,'-1')  Like ".$subcostcent;  
	
					
					if ($riskbal == 0 && $accountno == 2) {
                        $QueryDirSchema= $QueryDirSchema." And upper(ifNull(Clients.CostCenter_Code,'-1')) like ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))   ";
						//maroun
						$QueryDirSchema= $QueryDirSchema." And upper(ifNull(Clients.Project_Code,'-1')) like ifNull(upper(".$cltprj."), upper(ifNull(Clients.Project_Code,'-1')))   ";
					}	
					
					//if ($accountno == 2 && $SelSalesman == 1) {
					if ($accountno == 2) {
                        $QueryDirSchema= $QueryDirSchema." And ifNull(Clients.Salesmen_Code,'-1') between ifNull(".$fromsalesman.",ifNull(Clients.Salesmen_Code,'-1')) and ifNull(". $tosalesman.",ifNull(Clients.Salesmen_Code,'-1'))  ";
					}	
					
					
					$QueryDirSchema= $QueryDirSchema." group by Ledger_number, Ledger_name, Currency_code, CreditLimits, BusinessType, SalesmanCode, SalesmanName, ProjectCode, CostcentCode, MasterProjectCode, MasterCostcentCode ";
									

                   	if ($RowsDirCount > 1 && $j < $RowsDirCount)	
                        $QueryDirSchema= $QueryDirSchema." Union ";
	}			
} // End Loop For Directories

$QueryDirSchema= $QueryDirSchema." order by Ledger_number, Currency_code, ProjectCode, CostcentCode, MasterProjectCode, MasterCostcentCode ";
$QueryDirSchema= $QueryDirSchema.
				 " ) QDirMaster ".
				 " Group By Groupby1Code, Groupby2Code, Groupby3Code, ProjectCode, CostcentCode, Ledger_number, Currency_code ".
                 " Order By Groupby1Code, Groupby2Code, Groupby3Code, Ledger_number, Currency_code, ProjectCode, CostcentCode ";
	

	
//echo $QueryDirSchema; exit;					

$queryjournal= $queryjournal." ".$QueryDirSchema.
				 " ) As Q1 Left Join  ". 
				 " (  ";
				 
$j = 0;				
$k = 0;
$QueryDirSchemaDt = '';

$QueryDirSchemaDt = " Select JournalDt_ID, Ledger_number,  Currency_code, ProjectCode, CostcentCode, Journaldt_desc, Journal_folio, ".
				    " JournalDt_DBCD, JDate, OrdDate, Days, Amount ".
					" from ".
					" (  ";

// Reading Data For Many Years Or Different Directories					 
while($RowsDir=mysql_fetch_row($ResultDir1)){

    $j = $j + 1;    
	//if ($RowsDirCount > 1)
	   $DirSchema = $RowsDir[0];
	//else
       //$DirSchema = '';	
    
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
		$k = $k + 1;    		
		$QueryDirSchemaDt= $QueryDirSchemaDt.   
				 "  Select JournalDt.JournalDt_ID, ";
				 
		//if ($accountno == 3)		 
			//$QueryDirSchemaDt= $QueryDirSchemaDt." Salesmen.Ledger_number, ";
		//else
			$QueryDirSchemaDt= $QueryDirSchemaDt." JournalDt.Ledger_number, ";
				 
		$QueryDirSchemaDt= $QueryDirSchemaDt.   		 
				 "  if(upper($curr) = '".$Base1."', '".$Base1."', if(upper($curr) = '".$Base2."', '".$Base2."', JournalDt.Currency_code)) Currency_code, ".
				 "  Journaldt_desc, Journal_folio, JournalDt_DBCD, if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate) JDate, Cast(if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate) As Date) As OrdDate, ".
                 "  DATEDIFF(date_format(".$agingdate.",'%Y-%m-%d'), date_format(if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate),'%Y-%m-%d')) Days, ";
					
					if ($SelProject == 1 || $SelCostCenter == 1) 
						$QueryDirSchemaDt= $QueryDirSchemaDt." if($SelProject = 1, ifNull(CstJour.project_code,'None'), '') As ProjectCode, if($SelCostCenter = 1, ifNull(CstJour.Costcent_Code,'None'), '') As CostcentCode, ";
					else
						$QueryDirSchemaDt= $QueryDirSchemaDt." Null As ProjectCode, Null As CostcentCode, ";
						
						
					if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) 
					    //$QueryDirSchemaDt= $QueryDirSchemaDt."  if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D'  OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount1,Journaldt_amount1), (-1)*ifNull(Cstjour_amount1,Journaldt_amount1)), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D'  OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount2,Journaldt_amount2), (-1)*ifNull(Cstjour_amount2,Journaldt_amount2)), if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount,Journaldt_amount), (-1)*ifNull(Cstjour_amount,Journaldt_amount))))*(if(journaldt_dbcd='D',1,-1)) Amount ";
						$QueryDirSchemaDt= $QueryDirSchemaDt."  if(upper($curr) = '".$Base1."',  ifNull(Cstjour_amount1,Journaldt_amount1), if(upper($curr) = '".$Base2."', ifNull(Cstjour_amount2,Journaldt_amount2), ifNull(Cstjour_amount,Journaldt_amount)))*IF(JOURNALDT_DBCD='C' AND JOURNAL_TYPE IN ('DR','SR'),-1,1) Amount ";
					else
					    //$QueryDirSchemaDt= $QueryDirSchemaDt."  if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount1, (-1)*Journaldt_amount1), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount2, (-1)*Journaldt_amount2), if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount, (-1)*Journaldt_amount)))*(if(journaldt_dbcd='D',1,-1)) Amount ";
						 $QueryDirSchemaDt= $QueryDirSchemaDt."  if(upper($curr) = '".$Base1."',  Journaldt_amount1,if(upper($curr) = '".$Base2."', Journaldt_amount2,  Journaldt_amount))*IF(JOURNALDT_DBCD='C' AND JOURNAL_TYPE IN ('DR','SR'),-1,1) Amount ";
					
					$QueryDirSchemaDt= $QueryDirSchemaDt."  from $DirSchema.JournalDt As JournalDt ".
														 "  Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ";
														 //"  Inner join $tablename on JournalDt.Ledger_number = $tablename.Ledger_number ".
					if ($accountno == 3 ) {			   
						$QueryDirSchemaDt= $QueryDirSchemaDt." Inner join Clients on JournalDt.Ledger_number = Clients.Ledger_number ".
															 " Left Join Salesmen As Salesmen On Clients.Salesmen_Code = Salesmen.Ledger_Number ";
					} else {
						$QueryDirSchemaDt= $QueryDirSchemaDt."  Inner join $tablename on JournalDt.Ledger_number = $tablename.Ledger_number ";
					}	
					  
				    if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {	
					    $QueryDirSchemaDt= $QueryDirSchemaDt."  Left outer Join $DirSchema.CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ";
					  
						if ($projectexist > 0  && $FI_RepRestrictProject == 1)
							$QueryDirSchemaDt= $QueryDirSchemaDt." Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
																 "			    where loginstk.user_account='".$_SESSION['useraccount']."' ".
																 "              and (project_code is not null and project_code != '') ".
															     "		      ) PrjQry1 on CstJour.project_code like concat(PrjQry1.project_code,'%') ";
															   
						if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
							$QueryDirSchemaDt= $QueryDirSchemaDt." Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
															     "			    where loginstk.user_account='".$_SESSION['useraccount']."' ".
														         "              and (costcent_code is not null and costcent_code != '') ".
														         "			  ) CstQry1 on CstJour.Costcent_code like concat(CstQry1.costcent_code,'%')  ";									   
					 
				    }	
					
						
						


					//if($dateoption == 1) 
						$QueryDirSchemaDt= $QueryDirSchemaDt." 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'))   ";
					//else
						//$QueryDirSchemaDt= $QueryDirSchemaDt." where date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d'))   ";

                    if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {	
						$QueryDirSchemaDt= $QueryDirSchemaDt." 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 ($subproj != 'Null' && ($SelProject == 1 || $SelCostCenter == 1))
						$QueryDirSchemaDt= $QueryDirSchemaDt." And ifNull(CstJour.project_code,'-1')  Like ".$subproj; 
					if ($subcostcent != 'Null' && ($SelProject == 1 || $SelCostCenter == 1))
						$QueryDirSchemaDt= $QueryDirSchemaDt." And ifNull(CstJour.Costcent_Code,'-1')  Like ".$subcostcent;  
					
					
					if ($accountno != 3) 
					    $QueryDirSchemaDt= $QueryDirSchemaDt." And JournalDt.Ledger_Number between ifNull(".$fromledger.",JournalDt.Ledger_Number) and ifNull(". $toledger.",JournalDt.Ledger_Number) ";
					else
                        $QueryDirSchemaDt= $QueryDirSchemaDt." And Salesmen.Ledger_number between ifNull(".$fromledger.",Salesmen.Ledger_number) and ifNull(". $toledger.",Salesmen.Ledger_number)  ";					
					

					
					$QueryDirSchemaDt= $QueryDirSchemaDt." And (($accountno=1 and Journaldt_dbcd = 'C') or ($accountno!=1 and (Journaldt_dbcd = 'D'  OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')))  )) ";
					$QueryDirSchemaDt= $QueryDirSchemaDt." And (JournalDt.JournalDt_Amount <> 0 or JournalDt.JournalDt_Amount1 <> 0 or JournalDt.JournalDt_Amount2 <> 0) ";
														 
					if ($RowsDirCount > 1 && $k != 1)	
						$QueryDirSchemaDt= $QueryDirSchemaDt." And Journal.Journal_Type <> 'OP' ";
						
	                
					if ($RowsDirCount > 1 && $j < $RowsDirCount)	
                        $QueryDirSchemaDt= $QueryDirSchemaDt." Union ";
	}					
}


$QueryDirSchemaDt= $QueryDirSchemaDt." ) QDirDetail ".
									 " Order by Ledger_number, Currency_code, ProjectCode, CostcentCode, OrdDate, Journal_folio, JournalDt_ID ";

//echo $QueryDirSchemaDt;exit;					 
$queryjournal= $queryjournal." ".$QueryDirSchemaDt.						
					") Q2 on Q2.Ledger_Number = Q1.Ledger_Number And Q2.Currency_Code = Q1.Currency_Code ";
					
if ($SelProject == 1 || $SelCostCenter == 1)					
	$queryjournal= $queryjournal." And Q2.ProjectCode = Q1.ProjectCode And Q2.CostcentCode = Q1.CostcentCode ";
				
if ($riskbal == 1 && $accountno == 2) {					
	$queryjournal= $queryjournal." Left Outer Join (  ";
				

$j = 0;				
$k = 0; // Count For First Existsing Db
$QueryCheckBal = '';

$QueryCheckBal = " Select Ledger_number, Currency_code, ProjectCode, CostcentCode, Sum(CheckBalance) As CheckBalance ".
				 " from ".
				 " (  ";

// Reading Data For Many Years Or Different Directories					 
while($RowsDir=mysql_fetch_row($ResultDir2)){		

    $j = $j + 1;    
	//if ($RowsDirCount > 1)
	   $DirSchema = $RowsDir[0];
	//else
       //$DirSchema = '';	
	   
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
	    $k = $k + 1;    
	
		$QueryCheckBal= $QueryCheckBal."  Select clients.Ledger_number, if(upper($curr) = '".$Base1."', '".$Base1."', if(upper($curr) = '".$Base2."', '".$Base2."', JournalDt.Currency_code)) Currency_code , ";
		
		if ($SelProject == 1 || $SelCostCenter == 1) 
			$QueryCheckBal= $QueryCheckBal." if($SelProject = 1, ifNull(CstJour.project_code,'None'), '') As ProjectCode, if($SelCostCenter = 1, ifNull(CstJour.Costcent_Code,'None'), '') As CostcentCode, ";
		else
			$QueryCheckBal= $QueryCheckBal." Null As ProjectCode, Null As CostcentCode, ";
						
		/*if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {
		    $QueryCheckBal= $QueryCheckBal." Sum(if(date_format(if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate),'%Y-%m-%d') between ifNull(". $fromdate.",date_format(if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate),'%Y-%m-%d')) and ifNull(". $todate.",date_format(if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate),'%Y-%m-%d')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D', ifNull(Cstjour_amount1,Journaldt_amount1), (-1)*ifNull(Cstjour_amount1,Journaldt_amount1)), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D', ifNull(Cstjour_amount2,Journaldt_amount2), (-1)*ifNull(Cstjour_amount2,Journaldt_amount2)), if(Journaldt_dbcd = 'D', ifNull(Cstjour_amount,Journaldt_amount), (-1)*ifNull(Cstjour_amount,Journaldt_amount)))),0) ) As  CheckBalance ";
        } else {
		    $QueryCheckBal= $QueryCheckBal." Sum(if(date_format(if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate),'%Y-%m-%d') between ifNull(". $fromdate.",date_format(if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate),'%Y-%m-%d')) and ifNull(". $todate.",date_format(if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate),'%Y-%m-%d')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D', Journaldt_amount1, (-1)*Journaldt_amount1), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D', Journaldt_amount2, (-1)*Journaldt_amount2), if(Journaldt_dbcd = 'D', Journaldt_amount, (-1)*Journaldt_amount))),0) ) As CheckBalance ";
		}*/
		
		if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {
		    $QueryCheckBal= $QueryCheckBal." Sum(if(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')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D'  OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount1,Journaldt_amount1), (-1)*ifNull(Cstjour_amount1,Journaldt_amount1)), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount2,Journaldt_amount2), (-1)*ifNull(Cstjour_amount2,Journaldt_amount2)), if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), ifNull(Cstjour_amount,Journaldt_amount), (-1)*ifNull(Cstjour_amount,Journaldt_amount)))),0) ) As  CheckBalance ";
        } else {
		    $QueryCheckBal= $QueryCheckBal." Sum(if(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')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount1, (-1)*Journaldt_amount1), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount2, (-1)*Journaldt_amount2), if(Journaldt_dbcd = 'D' OR (Journaldt_dbcd = 'C' AND JOURNAL_TYPE IN ('DR','SR')), Journaldt_amount, (-1)*Journaldt_amount))),0) ) As CheckBalance ";
		}
					
		$QueryCheckBal= $QueryCheckBal." from $DirSchema.JournalDt As JournalDt ".
		                               " Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ";
				    
					
	    $QueryCheckBal= $QueryCheckBal."   Inner join ".
										"   ( select clients.ledger_number, concat(acctypesetup.ledger_number,substr(clients.ledger_number,5,length(clients.ledger_number))) accountnumber ".
                                        "     from clients ".
										"     Inner join ledger on clients.Ledger_number = ledger.Ledger_number ".
										"     left join acctype on substr(clients.ledger_number,1,4) = acctype.acctype_ledger ".
										"     left join acctypesetup on upper(acctypesetup.type_code) = upper(acctype.acctype_code) ".
										"     where Clients.Ledger_Number between ifNull(".$fromledger.",Clients.Ledger_Number) and ifNull(". $toledger.",Clients.Ledger_Number) ".
										"     And upper(ifNull(Clients.CostCenter_Code,'-1')) like ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))   ".
										//maroun
										"     And upper(ifNull(Clients.Project_Code,'-1')) like ifNull(upper(".$cltprj."), upper(ifNull(Clients.Project_Code,'-1')))   ".
										"     And acctypesetup.ledger_number Is Not Null ".
										"    ) Clients on JournalDt.Ledger_Number = Clients.accountnumber  ";
													
					


        if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {
			$QueryCheckBal= $QueryCheckBal." Left outer Join $DirSchema.CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ";

			if ($projectexist > 0  && $FI_RepRestrictProject == 1)
				$QueryCheckBal= $QueryCheckBal." left join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
											   "			 where loginstk.user_account='".$_SESSION['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)
				$QueryCheckBal= $QueryCheckBal." Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
											   "			  where loginstk.user_account='".$_SESSION['useraccount']."' ".
											   "              and (costcent_code is not null and costcent_code != '') ".
											   "			) CstQry on CstJour.Costcent_code like concat(CstQry.costcent_code,'%')  ";								   
	
		}
													 
	    //$QueryCheckBal= $QueryCheckBal." where JournalDt.JournalDt_Amount1 <> 0 ";
		$QueryCheckBal= $QueryCheckBal." where 1 = 1 ";
					
					
		if ($RowsDirCount > 1 && $k != 1)	
			$QueryCheckBal= $QueryCheckBal." And Journal.Journal_Type <> 'OP' ";
					
        if ($fromproject != 'Null' || $fromcst != 'Null' || $SelProject == 1 || $SelCostCenter == 1) {					
			$QueryCheckBal= $QueryCheckBal." 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 ($subproj != 'Null' && ($SelProject == 1 || $SelCostCenter == 1))
			$QueryCheckBal= $QueryCheckBal." And ifNull(CstJour.project_code,'-1')  Like ".$subproj; 
		if ($subcostcent != 'Null' && ($SelProject == 1 || $SelCostCenter == 1))
			$QueryCheckBal= $QueryCheckBal." And ifNull(CstJour.Costcent_Code,'-1')  Like ".$subcostcent;  
								
					
        $QueryCheckBal= $QueryCheckBal." group by clients.Ledger_number, JournalDt.Currency_code, ProjectCode, CostcentCode ";

       	if ($RowsDirCount > 1 && $j < $RowsDirCount)	
            $QueryCheckBal= $QueryCheckBal." Union ";
	}			
} // End Loop For Directories


$QueryCheckBal= $QueryCheckBal." ) QDirCheckBal ".
							   " Group By Ledger_number, Currency_code, ProjectCode, CostcentCode ".
							   " Order By Ledger_number, Currency_code, ProjectCode, CostcentCode ";
	
//echo $QueryCheckBal; exit;					

$queryjournal= $queryjournal." ".$QueryCheckBal.
					" ) As QCheckBal on QCheckBal.Ledger_Number = Q1.Ledger_Number And QCheckBal.Currency_Code = Q1.Currency_Code  ";
					
if ($SelProject == 1 || $SelCostCenter == 1)					
	$queryjournal= $queryjournal." And QCheckBal.ProjectCode = Q1.ProjectCode And QCheckBal.CostcentCode = Q1.CostcentCode ";	
	
}					

  /*xxxxxxxxx$queryjournal= $queryjournal.					
				" 	Order By Q1.Groupby1Code, Q1.Groupby2Code, Q1.Groupby3Code, Q2.Ledger_Number, Q2.Currency_code, Q2.ProjectCode, Q2.CostcentCode, Q2.OrdDate, Q2.Journal_folio, Q2.JournalDt_ID ".				
				" 	) As Q4  ".
				" Order By Q4.Groupby1Code, Q4.Groupby2Code, Q4.Groupby3Code, Q4.Ledger_Number, Q4.Currency_code, Q4.ProjectCode, Q4.CostcentCode, Q4.OrdDate, Q4.JournalDt_ID ".
				" ) As Q5 ".
				" Order By Q5.Groupby1Code, Q5.Groupby2Code, Q5.Groupby3Code, Q5.Ledger_Number, Q5.Currency_code, Q5.ProjectCode, Q5.CostcentCode, Q5.OrdDate, Q5.JournalDt_ID  ".
				" ) Q6  ".
				" where (($showbal=1 and Q6.Balance Between ifNull($rangefrom,0) and ifNull($rangeto,0)) or ($showbal=0 and 1=1)) ".
				" And (($accountno=1 and if(Q6.TotalDebits >= Q6.PrevBalance, Q6.AgingBalance < 0, 1 = 1)) or ($accountno!=1 and if(Q6.TotalCredits >= Q6.PrevBalance and Q6.Balance > 0, Q6.AgingBalance < 0, 1 = 1) )) ".
				" And Q6.Balance != 0 ";
				//" And (($accountno=1 and ((Q6.RecordNum > 1 and Q6.AgingBalance <= 0)) or (Q6.RecordNum <= 1 and 1 = 1)) or ($accountno!=1 and ((Q6.RecordNum > 1 and Q6.AgingBalance >= 0) or (Q6.RecordNum <= 1 and 1 = 1))) ) ";
				//" And (($accountno!=1 and Q6.Balance != 0) or ($accountno=1 and 1=1))   ";
	*/
   $queryjournal= $queryjournal.					
				" 	Order By Q1.Groupby1Code, Q1.Groupby2Code, Q1.Groupby3Code, Q2.Ledger_Number, Q2.Currency_code, Q2.ProjectCode, Q2.CostcentCode, Q2.OrdDate, Q2.Journal_folio, Q2.JournalDt_ID ".				
				" 	) As Q4  ".
				" Order By Q4.Groupby1Code, Q4.Groupby2Code, Q4.Groupby3Code, Q4.Ledger_Number, Q4.Currency_code, Q4.ProjectCode, Q4.CostcentCode, Q4.OrdDate, Q4.JournalDt_ID ".
				" ) As Q5 ".
				" Order By Q5.Groupby1Code, Q5.Groupby2Code, Q5.Groupby3Code, Q5.Ledger_Number, Q5.Currency_code, Q5.ProjectCode, Q5.CostcentCode, Q5.OrdDate, Q5.JournalDt_ID  ".
				" ) Q6  ".
				" where (($showbal=1 and Q6.Balance Between ifNull($rangefrom,0) and ifNull($rangeto,0)) or ($showbal=0 and 1=1)) ".
				" And (($accountno=1 and if(Q6.TotalDebits >= Q6.PrevBalance,  showrow= 1, 1 = 1)) or ($accountno!=1 and if(Q6.TotalCredits >= Q6.PrevBalance and Q6.Balance > 0,  showrow= 1, 1 = 1) )) ".
				" And Q6.Balance != 0 ";
				//" And (($accountno=1 and ((Q6.RecordNum > 1 and Q6.AgingBalance <= 0)) or (Q6.RecordNum <= 1 and 1 = 1)) or ($accountno!=1 and ((Q6.RecordNum > 1 and Q6.AgingBalance >= 0) or (Q6.RecordNum <= 1 and 1 = 1))) ) ";
				//" And (($accountno!=1 and Q6.Balance != 0) or ($accountno=1 and 1=1))   ";
		
				$queryjournal= $queryjournal." ) Q7  Group By Groupby1Code, Groupby2Code, Groupby3Code, ProjectCode, CostcentCode, Ledger_number, Ledger_name, Currency_code  ";
				$queryjournal= $queryjournal." order by Q7.Groupby1Code, Q7.Groupby2Code, Q7.Groupby3Code, $OrderByCond, Q7.Currency_code, Q7.OrdDate  ";
				  
if ($showdetail == 0) {				
	$queryjournal= $queryjournal." ) Q8 Group By Groupby1Code, Groupby2Code, Groupby3Code, Currency_code ";
	
}
	
//xxxxxecho $queryjournal;exit;

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

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


$resultjournal=mysql_query($queryjournal,$connection) or die(mysql_error());
$col=0;
while($rowsjournal=mysql_fetch_row($resultjournal)){
	if($col%2==0){
		$color = "style='background-color:".$report_color1."'";
	}else{
		$color = "style='background-color:".$report_color2."'";
	}
	
	//Group By Options Level 3 Totals
	if ( ($groupby3 != 1 && $showdetail == 1) && (($MainGroup3 != $rowsjournal[4] && $MainGroup3 != '') || ($MainGroup2 != $rowsjournal[2] && $MainGroup2 != '') || ($MainGroup1 != $rowsjournal[0] && $MainGroup1 != ''))  ){
	  
		echo "<tr>";
		echo "   <td colspan='3'><hr width='100%' color='black' size='1'></td>";
		echo "</tr>";
				
		echo "<tr><td colspan='3'>";

		$StyleClass  = 'grouplevel3total';
		$TotalsLabel = 'Total 3 - '.$groupby3name.' : '. str_replace('*',' --> ',$groupby3code);
		DisplayTotals($numrows, $accountno, $shownondues, $riskbal, $ArrayTotalByGroup3, $DecimalBase, $TotalsLabel, $StyleClass);

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

		$StyleClass  = 'grouplevel2total';
		$TotalsLabel = 'Total 2 - '.$groupby2name.' : '.$groupby2code;
		DisplayTotals($numrows, $accountno, $shownondues, $riskbal, $ArrayTotalByGroup2, $DecimalBase, $TotalsLabel, $StyleClass);

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

		$StyleClass  = 'grouplevel1total';
		$TotalsLabel = 'Total 1 - '.$groupby1name.' : '.$groupby1code;
		DisplayTotals($numrows, $accountno, $shownondues, $riskbal, $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='3'>&nbsp;</td>";
		echo "</tr>"; 
	}
	
	//Group By Options Level 1 Names 
	if ( ($groupby1 != '' && ($showdetail == 1 || $groupby2 != '' || $groupby3 != 1)) && ($MainGroup1 == '' || $MainGroup1 != $rowsjournal[0])  ){
			
		$groupby1code = '';
		if ($rowsjournal[0] == -1)
		   $groupby1code = '';
		else
            $groupby1code = $rowsjournal[0];			
		
		echo "<tr><td width='70px'>&nbsp;</td>";
		echo "   <td align='left' valign='top' colspan='3' 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='3'>&nbsp;</td>";
			echo "</tr>";
		}
				
						
		$MainGroup1   = $rowsjournal[0];
		$groupby1desc = $rowsjournal[1];
		
		$MainGroup2   = '';
		$groupby2desc = '';
		$MainGroup3   = '';
		$groupby3desc = '';	
		
		unset($ArrayTotalByGroup1);		
		unset($ArrayTotalByGroup2);		
		unset($ArrayTotalByGroup3);
		
	}
	
   
   //Group By Options Level 2 Names 
	if ( ($groupby2 != '' && ($showdetail == 1 || $groupby3 != 1)) && ($MainGroup2 == '' || $MainGroup2 != $rowsjournal[2])  ){
			
		$groupby2code = '';
		if ($rowsjournal[2] == -1)
		   $groupby2code = '';
		else
              $groupby2code = $rowsjournal[2];			
		
		echo "<tr><td>&nbsp;</td>";
		echo "   <td align='left' valign='top' colspan='3' 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='3'>&nbsp;</td>";
			echo "</tr>";
		}
				
						
		$MainGroup2   = $rowsjournal[2];
		$groupby2desc = $rowsjournal[3];
		
		$MainGroup3   = '';
		$groupby3desc = '';	
		
		unset($ArrayTotalByGroup2);		
		unset($ArrayTotalByGroup3);

	}
		
	//Group By Options Level 3 Names 
	if ( ($groupby3 != 1 && $showdetail == 1) && ($MainGroup3 == '' || $MainGroup3 != $rowsjournal[4])  ){
			
		$groupby3code = '';
		if ($rowsjournal[4] == -1)
		   $groupby3code = '';
		else
            $groupby3code = $rowsjournal[4];			
			   
		echo "<tr><td>&nbsp;</td>";
		echo "   <td align='left' valign='top' colspan='3' 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='3'>&nbsp;</td>";
		echo "</tr>"; 
						
		$MainGroup3   = $rowsjournal[4];
		$groupby3desc = $rowsjournal[5];
			
		unset($ArrayTotalByGroup3);
	}
	

	echo "<tr class='group'><td colspan='3'>";
	
	//Create Table Columns
	CreateTableStructure($numrows, $accountno, $shownondues, $riskbal);

	echo"	<tr class='group' $color>";
//<span style='word-wrap: break-word; word-break:break-all;white-space: pre-wrap;'>	
	if ($showdetail == 1) {
		echo "<td align='left'   valign='top' style='border-right:1px solid black;'>". $rowsjournal[6] ."</td>";
		echo "<td align='left'   valign='top' style='border-right:1px solid black; padding-left:2px;'>". $rowsjournal[7] ."</td>";
		echo "<td align='center' valign='top' style='border-right:1px solid black;'>". $rowsjournal[9] ."</td>";
		echo "<td align='right'  valign='top' style='border-right:1px solid black; padding-right:2px;'>". format_currency($rowsjournal[8], $DecimalBase) ."</td>";
	
	} 
	else if ($showdetail == 0 && $groupby1 != '' && $groupby2 == '' && $groupby3 == 1) {
		echo "<td align='left' valign='top' colspan='4'>".str_replace('*',' --> ',$rowsjournal[0])."  -  ".str_replace('*',' --> ',$rowsjournal[1])."</td>";
	}
	else if ($showdetail == 0 && $groupby2 != '' && $groupby3 == 1) {
		echo "<td align='left' valign='top' colspan='4'>".str_replace('*',' --> ',$rowsjournal[2])."  -  ".str_replace('*',' --> ',$rowsjournal[3])."</td>";
	}
	else if ($showdetail == 0 && $groupby3 != 1) {
		echo "<td align='left' valign='top' colspan='4'>".str_replace('*',' --> ',$rowsjournal[4])."  -  ".str_replace('*',' --> ',$rowsjournal[5])."</td>";
	}
	
				
					
	if ($riskbal == 1 && $accountno == 2) {	
		echo "<td align='right' valign='top' style='border-right:1px solid black;padding-right:2px;'>". format_currency($rowsjournal[24], $DecimalBase) ."</td>";
		echo "<td align='right' valign='top' style='border-right:1px solid black;padding-right:2px;'>". format_currency($rowsjournal[25], $DecimalBase) ."</td>";
	}
	
	echo "<td align='center' valign='top' style='border-right:1px solid black;'>". $rowsjournal[14] ."</td>";
	echo "<td align='right' valign='top' style='border-right:1px solid black;padding-right:2px;'>". format_currency($rowsjournal[19], $DecimalBase) ."</td>";
	
	if ($shownondues == 1)
		echo "<td align='right' valign='top' style='border-right:1px solid black;padding-right:2px;'>". format_currency($rowsjournal[23], $DecimalBase) ."</td>";
		
	echo "<td align='right' valign='top' style='border-right:1px solid black;padding-right:2px;'>". format_currency($rowsjournal[26], $DecimalBase) ."</td>";
	
	
	for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
		$j = 27 + $d;
		echo "<td align='right' valign='top' style='border-right:1px solid black;padding-right:2px;'>"; if($rowsjournal[$j] != '') echo format_currency($rowsjournal[$j], $DecimalBase); else $rowsjournal[$j]; echo"</td>";
	}
	
	echo "<td align='right' valign='top' style='border-right:1px solid black;padding-right:2px;'>"; if($rowsjournal[$j+1] != '') echo format_currency($rowsjournal[$j+1], $DecimalBase); else $rowsjournal[$j+1]; echo"</td>";		
			
	echo"   </tr>";	
	echo"</table></td></tr>";

	
	/*echo "<tr>";
	echo "<td colspan='3'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";*/
	
	
	$ArrayTotalByReport['Balance']  	= $ArrayTotalByReport['Balance'] 	  + $rowsjournal[19];
	$ArrayTotalByReport['NonDues'] 		= $ArrayTotalByReport['NonDues'] 	  + $rowsjournal[23];
	$ArrayTotalByReport['NonAllocated'] = $ArrayTotalByReport['NonAllocated'] + $rowsjournal[26];
	
	for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
		$j = 27 + $d;
		$ArrayTotalByReport['Amount'][$d]  = $ArrayTotalByReport['Amount'][$d] + $rowsjournal[$j];
		
		if ($d + 1 == count($ArrayPeriods))
			$ArrayTotalByReport['Amount'][$d + 1]  = $ArrayTotalByReport['Amount'][$d + 1] + $rowsjournal[$j + 1];
	}
	
			
	$ArrayTotalByGroup1['Balance']  	= $ArrayTotalByGroup1['Balance'] 	  + $rowsjournal[19];
	$ArrayTotalByGroup1['NonDues']  	= $ArrayTotalByGroup1['NonDues'] 	  + $rowsjournal[23];
	$ArrayTotalByGroup1['NonAllocated'] = $ArrayTotalByGroup1['NonAllocated'] + $rowsjournal[26];
	
	for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
		$j = 27 + $d;
		$ArrayTotalByGroup1['Amount'][$d]  = $ArrayTotalByGroup1['Amount'][$d] + $rowsjournal[$j];
		
		if ($d + 1 == count($ArrayPeriods))
			$ArrayTotalByGroup1['Amount'][$d + 1]  = $ArrayTotalByGroup1['Amount'][$d + 1] + $rowsjournal[$j + 1];
	}
	
	$ArrayTotalByGroup2['Balance']  	= $ArrayTotalByGroup2['Balance'] 	  + $rowsjournal[19];
	$ArrayTotalByGroup2['NonDues']  	= $ArrayTotalByGroup2['NonDues'] 	  + $rowsjournal[23];
	$ArrayTotalByGroup2['NonAllocated'] = $ArrayTotalByGroup2['NonAllocated'] + $rowsjournal[26];
	
	for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
		$j = 27 + $d;
		$ArrayTotalByGroup2['Amount'][$d]  = $ArrayTotalByGroup2['Amount'][$d] + $rowsjournal[$j];
		
		if ($d + 1 == count($ArrayPeriods))
			$ArrayTotalByGroup2['Amount'][$d + 1]  = $ArrayTotalByGroup2['Amount'][$d + 1] + $rowsjournal[$j + 1];
	}
	
	$ArrayTotalByGroup3['Balance']  	= $ArrayTotalByGroup3['Balance'] 	  + $rowsjournal[19];
	$ArrayTotalByGroup3['NonDues']  	= $ArrayTotalByGroup3['NonDues'] 	  + $rowsjournal[23];
	$ArrayTotalByGroup3['NonAllocated'] = $ArrayTotalByGroup3['NonAllocated'] + $rowsjournal[26];
	
	for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
		$j = 27 + $d;
		$ArrayTotalByGroup3['Amount'][$d]  = $ArrayTotalByGroup3['Amount'][$d] + $rowsjournal[$j];
		
		if ($d + 1 == count($ArrayPeriods))
			$ArrayTotalByGroup3['Amount'][$d + 1]  = $ArrayTotalByGroup3['Amount'][$d + 1] + $rowsjournal[$j + 1];
	}				
		$col+=1;
}

$result = mysql_query("rollback", $connection);

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

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

				
	$StyleClass  = 'grouplevel3total';
	$TotalsLabel = 'Total 3 - '.$groupby3name.' : '. str_replace('*',' --> ',$groupby3code);
	DisplayTotals($numrows, $accountno, $shownondues, $riskbal, $ArrayTotalByGroup3, $DecimalBase, $TotalsLabel, $StyleClass);

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

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

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

				
	$StyleClass  = 'grouplevel2total';
	$TotalsLabel = 'Total 2 - '.$groupby2name.' : '. str_replace('*',' --> ',$groupby2code);
	DisplayTotals($numrows, $accountno, $shownondues, $riskbal, $ArrayTotalByGroup2, $DecimalBase, $TotalsLabel, $StyleClass);

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

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

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

				
	$StyleClass  = 'grouplevel1total';
	$TotalsLabel = 'Total 1 - '.$groupby1name.' : '. str_replace('*',' --> ',$groupby1code);
	DisplayTotals($numrows, $accountno, $shownondues, $riskbal, $ArrayTotalByGroup1, $DecimalBase, $TotalsLabel, $StyleClass);

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

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

$StyleClass  = 'summary';
$TotalsLabel = 'Total';
DisplayTotals($numrows, $accountno, $shownondues, $riskbal, $ArrayTotalByReport, $DecimalBase, $TotalsLabel, $StyleClass);

echo"	</td></tr>";
	
	
	
echo "</table></td></tr></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 (Round(abs($amount), $DecimalBase) == 0)
		return number_format(abs($amount), $DecimalBase); 
	else if($amount < 0) 
        return "(".number_format(abs($amount),$DecimalBase).")"; 
    else 
		return number_format($amount, $DecimalBase); 
} 


function CreateTableStructure($PColsCount, $PAccountNo, $PShowNonDues, $PRiskBal) {
	
	echo "    <table  border='0' align='left' class='report-master' style='table-layout:fixed; width:100%;' cellpadding='0' cellspacing='0'>
				<col width=80>
				<col width=150>
				<col width=50>
				<col width=80>";

	if ($PRiskBal == 1 && $PAccountNo == 2) echo" <col width=100> <col width=100>";
	
	echo" <col width=40> <col width=110>";
	
	if ($PShowNonDues == 1) echo" <col width=110>";
	echo" <col width=110>";
	
	for ( $d = 1; $d <= $PColsCount; $d += 1) {
		echo" <col width=110>";
	}
	
	echo" <col width=110>";
	

}

function DisplayTotals($PColsCount, $PAccountNo, $PShowNonDues, $PRiskBal, $PArrayTotal, $PDecimalBase, $PTotalsLabel, $PStyleClass) {
	
	echo "    <table  border='0' align='left'  style='table-layout:fixed; width:100%;' cellpadding='0' cellspacing='0'>
				<col width=80>
				<col width=150>
				<col width=50>
				<col width=80>";

	if ($PRiskBal == 1 && $PAccountNo == 2) echo" <col width=100> <col width=100>";
	
	echo" <col width=40> <col width=110>";
	
	if ($PShowNonDues == 1) echo" <col width=110>";
	echo" <col width=110>";
	
	for ( $d = 1; $d <= $PColsCount; $d += 1) {
		echo" <col width=110>";
	}
	
	echo" <col width=110>";
	
	echo"<tr class='".$PStyleClass."'>";
	//echo "   <td align='left'  valign='top' >&nbsp;</td>";
	if ($PRiskBal == 1 && $PAccountNo == 2)
		echo "  <td align='right' valign='top' colspan='7'>".$PTotalsLabel."</td>";
	else	
		echo "  <td align='right' valign='top' colspan='5'>".$PTotalsLabel."</td>";			
		
	echo "<td align='right' valign='top'>". format_currency($PArrayTotal['Balance'], 0) ."</td>";
	
	if ($PShowNonDues == 1)
		echo "<td align='right' valign='top'>". format_currency($PArrayTotal['NonDues'], 0) ."</td>";
		
	echo "<td align='right' valign='top'>". format_currency($PArrayTotal['NonAllocated'], 0) ."</td>";
	
	for ( $d = 0; $d < $PColsCount; $d += 1) {
		echo "<td align='right' valign='top'>". format_currency($PArrayTotal['Amount'][$d], 0) ."</td>";
		
		if ($d + 1 == $PColsCount)
			echo "<td align='right' valign='top'>". format_currency($PArrayTotal['Amount'][$d + 1], 0) ."</td>";
	}
	
	echo"     </tr>";	
	echo"	</table>";
	
}

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

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

?>