<?php

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

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($HTTP_SESSION_VARS['dbName'],$connection) or die("Could not find DB");

print <<< HERE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>
<HEAD>

<TITLE> Financial 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.group th { font-size: 14px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
				 }
						 
.report-master tr.group td { 
            
			font-weight: bold;
          }	
  
tr.detail  { font-size: 14px; 
             font-family:Times-New-Roman;
	       }		  
				 
tr.totals { font-size: 16px; 
            font-family:Times-New-Roman;
		    font-weight: bold;
			font-style: italic;
          }	
		  
tr.totalloss { font-size: 16px; 
			   font-family:Times-New-Roman;
			   font-weight: bold;
			   color: #FF0000;
			 }			  
			 
tr.totalprofit { font-size: 16px; 
			     font-family:Times-New-Roman;
			     font-weight: bold;
			     color: #0000FF;
			   }			 
			   
td.totalloss { font-size: 16px; 
			   font-family:Times-New-Roman;
			   font-weight: bold;
			   color: #FF0000;
			 }			  
			 
td.totalprofit { font-size: 16px; 
			     font-family:Times-New-Roman;
			     font-weight: bold;
			     color: #0000FF;
			   }			   
		  
				 
			 
report-master.header td { font-size: 14px; 
                  font-family:Times-New-Roman;
				  font-weight: bold;
				  font-style: italic;
                 }
table.header1 td { font-size: 16px; 
                   font-family:Times-New-Roman;
				   font-weight: bold;
				   font-style: italic;
                 }				 
			 

</style>



</HEAD>


HERE;


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

$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(loginstk.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);


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

if (empty($reportoption))   
	$reportoption = 1;

$sub_query = " Select FinancialTot_Label As ReportName, ".
             " ifNull(FinancialTot_Sign, 1) As FinancialTotSign ".
             " From FinancialTotLabel ".
             " Where FinancialTot_Code = '".$reportoption."' ";
$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
while($sub_rows = mysql_fetch_array($sub_result)){
	extract($sub_rows);
}			 
					

if ($incomebycst == 1) $ReportTitle = $ReportName." by Costcenter";
else if ($incomebyprj == 1) $ReportTitle = $ReportName." by Project";
else $ReportTitle = $ReportName;


echo "<table border=0 width=100% cellspacing=0 cellpadding=0><tr><td align='left'>";
	echo "<table border=0 width='635' cellspacing=2 cellpadding=0 class='master' style='table-layout:fixed;' >
		  <col width=115>
		  <col width=250>
		  <col width=80>
		  <col width=195>";
	echo "<thead><tr><td height='100'><img src='LogoFile.php' width='200' height='100' /></td><td colspan=2 align='center'><b><font size=5><u></u></font></td><td align='right' ><font size='8'><b>$ReportTitle</b>&nbsp;&nbsp;";
	//echo $ReportTitle;
	//echo "<br>".$dt[1]." ".$dt[2];
	//echo "<thead><tr><td align='left'>";
	//ShowReportHeader("$ReportTitle", 'landscape',$connection);
	//echo"</td></tr></thead><tbody>";
	echo "</font></td></tr>";
	echo"</td></tr></thead><tbody>";
	
HERE;
//	echo "<thead><tr><td align='left'>";
	
//	ShowReportHeader("$ReportTitle", 'landscape',$connection);
	
//	echo"</td></tr></thead><tbody>";
	
echo "</table></td></tr>";


$dispfromproject = $fromproject;
$dispfromcst     = $fromcst;
$dispfromdate    = $fromdate;
$disptodate      = $todate;

  
   

if (empty($fromproject))   
   $fromproject = 'null';
else
   $fromproject = "'".$fromproject."'";    
   
  
if (empty($fromcst))   
   $fromcst = 'null';
else
   $fromcst = "'".$fromcst."'";    
     

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

$vMonthFrom = intval(substr($fromdate, 5, 2));
$vMonthTo   = intval(substr($todate, 5, 2));
$vYearFrom  = substr($fromdate, 0, 4);
$vYearTo    = substr($todate, 0, 4);



$startdate = date ( 'Y-m-d' , strtotime ( '-1 day' , strtotime ( $fromdate ) )) . ' 23:59:59';
$enddate = $todate . ' 23:59:59';


$MainCompanyName=explode('_',$_SESSION['dbName']);  
$QueryDir = " Select Date_Format(Min(StartFinancialDate),'%Y-%m-%d') As StartFinancialDate ".
			" 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   ".
			"       (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 ";
$ResultDir  = mysql_query($QueryDir,$connection) or die(mysql_error());
$RowsDir=mysql_fetch_row($ResultDir);
$prestartdate = $RowsDir[0] . ' 00:00:00';
$preenddate   = date ( 'Y-m-d' , strtotime ( '-1 day' , strtotime ( $fromdate ) )) . ' 23:59:59';

if (empty($fromdate))   
   $fromdate = 'null';
else
   $fromdate = "'".$fromdate."'"; 
   
if (empty($todate))   
   $todate = 'null';
else
   $todate = "'".$todate."'";
   
if (empty($reportoption))   
	$reportoption = 1;
if (empty($showdetail))   
	$showdetail = 0;	
	
if (empty($treelevel))     $treelevel = 0;	
if (empty($incomebycst))   $incomebycst = 0;	
if (empty($incomebyprj))   $incomebyprj = 0;	
if (empty($parentprjcost)) $parentprjcost = 0;	
if (empty($showstock))     $showstock = 0;	
if (empty($showzerobal))   $showzerobal = 0;

print <<<HERE



<tr><td><table class="r" width="100%" border="0" style='table-layout:fixed; border-collapse:collapse;' align="center" >
<col width=50>
<col width=50>
<col width=70>
<tr>
  <td valign='top'><b>Date</b></td>
  <td ><b>From: <br>To: </b></td>
  <td >$dispfromdate <br> $disptodate</td>
  <td valign='top'>&nbsp;</td>
</tr>
</table></td></tr>
HERE;

if ($incomebycst == 0 && $incomebyprj == 0) {
	echo "<tr><td><table  border='0' width='100%' align='center' class='report-master' style='table-layout:fixed; border-collapse:collapse;' cellpadding='0' cellspacing='0'>
		  <col width=100>
		  <col width=280>
		  <col width=140>
		  <col width=140>
		  <col width=140>";
		  
	if ($monthdist == 1 ) {				
		for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

			if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
			else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
			else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
			else { $vMFrom = 1; $vMTo = 12; }
			
			for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
				echo"<col width=140>";
			}

		}
	}
		  
	echo"<thead>
	<tr>
		<th align='left'>Ledger No.</th>
		<th align='left'>Description</th>";

	if ($showprevbal == 1){
		echo"<th>Prev. Balance $curr</th>";
		echo"<th>Total Period $curr</th>";
		echo"<th>Net Balance $curr</th>";
	}	
	else {	
		echo"<th>&nbsp;</th>";
		echo"<th>Total Period $curr</th>";
		echo"<th>&nbsp;</th>";
		//echo"<th colspan='2'>&nbsp;</th>";
	}	

	if ($monthdist == 1 ) {				
		for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

			if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
			else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
			else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
			else { $vMFrom = 1; $vMTo = 12; }
			
			for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
				echo"<th>".getMonth($m).$y."</th>";
			}

		}
	}
			
	echo"</thead></tr>"; 

} else {
	echo "<tr><td><table  border='0' width='100%' align='center' class='report-master' style='table-layout:fixed; border-collapse:collapse;' cellpadding='0' cellspacing='0'>";

}	
/*
print <<<HERE
<tr>
    <td colspan='100'><hr width='100%' color='black' size='2'></td>
</tr>
 
HERE;*/
 
 if ($showledgertype==0) {
	$Ledger_Number = 'Ledger_Number';
	$Ledger_Name = 'Ledger_Name';
	}
else {
	$Ledger_Number = 'Ledger_Number2';
	$Ledger_Name = 'Ledger_Name2';
}	
 
$MainCompanyName=explode('_',$HTTP_SESSION_VARS['dbName']);  
$QueryDir = " Select Concat(CompanyName, '_', DirYear) As DirSchema ".
			" From ".$HTTP_SESSION_VARS['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 ";

$ResultDir  = mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir1 = mysql_query($QueryDir,$connection) or die(mysql_error());
$RowsDirCount = mysql_num_rows($ResultDir);

//echo $QueryDir;
$j = 0;				
$k = 0; // Count For First Existsing Db
$queryjournal = '';




$queryjournal = " Select $Ledger_Number, $Ledger_Name, Ledger_GrpDet, FinancialTot_Code, FinancialTot_Label, Financial_Order, ".
				" ProjectCode, CostcentCode, MasterRecord, FinancialTot_Level, ".
				" PrvBalanceBase1, PrvBalanceBase2, BalanceBase1, BalanceBase2, FinancialTot_LevelCode, FinancialTot_ShowResult ";

if ($monthdist == 1 ) {				
	for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

		if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
		else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
		else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
		else { $vMFrom = 1; $vMTo = 12; }
		
		for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
		
			$queryjournal = $queryjournal.", ".getMonth($m).$y."Base1, ".getMonth($m).$y."Base2 ";
		
		}

	}
}

$queryjournal = $queryjournal.				
				" From ( ".
				" Select Q1.$Ledger_Number, Q1.$Ledger_Name, Q1.Ledger_GrpDet, ".
				" Q1.FinancialTot_Code, Q1.FinancialTot_Label, Q1.Financial_Order, ".
				" Q1.ProjectCode, Q1.CostcentCode, Q1.MasterRecord, Q1.FinancialTot_Level, ".
				" SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase1, 0)) AS PrvBalanceBase1, ".
				" SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase2, 0)) AS PrvBalanceBase2, ".
				" SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase1, 0)) AS BalanceBase1, ".
				" SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase2, 0)) AS BalanceBase2, ".
				//" if (upper(Q1.FinancialTot_Label) != 'STOCK', SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase1, 0)), ".
				//"     (ifNull(GetStockValue('".$enddate."', '".$Base1."', Q1.ProjectCode, Q1.CostcentCode),0) - ifNull(GetStockValue('".$startdate."', '".$Base1."', Q1.ProjectCode, Q1.CostcentCode),0)) ) AS BalanceBase1, ".
				//" if (upper(Q1.FinancialTot_Label) != 'STOCK', SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase2, 0)), ".
				//"     (ifNull(GetStockValue('".$enddate."', '".$Base2."', Q1.ProjectCode, Q1.CostcentCode),0) - ifNull(GetStockValue('".$startdate."', '".$Base2."', Q1.ProjectCode, Q1.CostcentCode),0)) ) AS BalanceBase2, ".
				" Q1.FinancialTot_LevelCode, Q1.FinancialTot_ShowResult ";
				
if ($monthdist == 1 ) {
	for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

		if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
		else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
		else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
		else { $vMFrom = 1; $vMTo = 12; }
		
		for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
		
			$queryjournal = $queryjournal.", SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), if((MaxMon = '".$m."') and (MaxYear = '".$y."'), Q1.AmountBase1, 0), 0)) AS ".getMonth($m).$y."Base1 ".
										  ", SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), if((MaxMon = '".$m."') and (MaxYear = '".$y."'), Q1.AmountBase2, 0), 0)) AS ".getMonth($m).$y."Base2 ";
		
		}

	}
}

$queryjournal = $queryjournal.
				" 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 ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1) {
		    $queryjournal = $queryjournal.
							" Select Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, ".
							" FinancialTemplate.FinancialTot_Code, FinancialTot_Label, Financial_Order, ".
							" JournalDt.Journal_Date, ".
							" Max(Month(JournalDt.Journal_Date)) As MaxMon, Max(Year(JournalDt.Journal_Date)) As MaxYear, ".
							" Null As ProjectCode, Null As CostcentCode, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
							" if(CstJour.Cst_increment is null,JournalDt_Amount1, CstJour_Amount1), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount1, (-1)*CstJour_Amount1))) AS AmountBase1, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
							" if(CstJour.Cst_increment is null,JournalDt_Amount2, CstJour_Amount2), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount2, (-1)*CstJour_Amount2))) AS AmountBase2, ".
							" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
							" FinancialTotLabel.FinancialTot_ShowResult ".
							" From Ledger ".
							" Inner Join FinancialTemplate on (Ledger.Ledger_Number = FinancialTemplate.Ledger_Number) ".
							" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ".
							" Left Join $DirSchema.JournalDt As JournalDt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,'%')) ".
							" Left Join $DirSchema.Journal As Journal on Journal.Journal_ID = JournalDt.Journal_ID ".
							" Left Outer Join $DirSchema.CstJour As CstJour on JournalDt.JournalDt_ID = CstJour.JournalDT_ID ";
							
			if ($projectexist >	0)
				$queryjournal= $queryjournal." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
											 "		  	    where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
											 "              and (loginstk.project_code is not null and loginstk.project_code != '') ".
											 "			  ) Q1 on CstJour.project_code like concat(Q1.project_code,'%') ";				
											 
											 
			if ($costcentexist > 0)
				$queryjournal= $queryjournal." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
										   "			  where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
										   "              and (costcent_code is not null and costcent_code != '') ".
										   "			) Q2 on CstJour.costcent_code like concat(Q2.costcent_code,'%') ";							 
							 
							
		} else {
			$queryjournal = $queryjournal.
							" Select Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, ".
							" FinancialTot_Label, Financial_Order, FinancialTemplate.FinancialTot_Code, ".
							" JournalDt.Journal_Date, ".
							" Max(Month(JournalDt.Journal_Date)) As MaxMon, Max(Year(JournalDt.Journal_Date)) As MaxYear, ".
							" Null As ProjectCode, Null As CostcentCode, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount1, (-1)*JournalDt_Amount1)) AS AmountBase1, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount2, (-1)*JournalDt_Amount2)) AS AmountBase2, ".
							" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
							" FinancialTotLabel.FinancialTot_ShowResult ".
							" From Ledger ".
							" Inner Join FinancialTemplate on (Ledger.Ledger_Number = FinancialTemplate.Ledger_Number) ".
							" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ".
							" Left Join $DirSchema.JournalDt As JournalDt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,'%')) ".
							" Left Join $DirSchema.Journal As Journal on Journal.Journal_ID = JournalDt.Journal_ID ";

		}	  
				  
				  

		$queryjournal= $queryjournal.  
								" where FinancialTotLabel.FinancialTot_TreeCode = $reportoption  ".
							//stopped to show also ledgers if added
							//	" and Ledger.Ledger_grpdet = 1 
							"";
								
									  
				  
		if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 1) ){  

			$queryjournal= $queryjournal." and upper(ifNull(CstJour.project_code,'-1')) like concat(ifNull(upper(".$fromproject."), upper(ifNull(CstJour.project_code,'-1'))),'%') ".
										 " and upper(ifNull(CstJour.Costcent_Code,'-1')) like concat(ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))),'%') ";

		}
		else if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 0) ){  

			$queryjournal= $queryjournal." 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 ($RowsDirCount > 1 && $k != 1)	
			$queryjournal= $queryjournal." And Journal.Journal_Type <> 'OP' ";
					
		$queryjournal= $queryjournal." Group By Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, FinancialTot_Label, Financial_Order, ".
									 " FinancialTemplate.FinancialTot_Code, JournalDt.Journal_Date, ProjectCode, CostcentCode ";
									 
		//Option Print Group Project/Costcenter
		if (($showcostcenter == 1 || $showproject == 1) && $printgrpproject == 1) {
		
			$queryjournal= $queryjournal." Union ";
			
			$queryjournal = $queryjournal.
							" Select Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, ".
							" FinancialTemplate.FinancialTot_Code, FinancialTot_Label, Financial_Order, ".
							" JournalDt.Journal_Date, ".
							" Max(Month(JournalDt.Journal_Date)) As MaxMon, Max(Year(JournalDt.Journal_Date)) As MaxYear, ";
							
			if($showproject ==1 && $printgrpproject	== 1) 
				$queryjournal = $queryjournal." if(CstJour.Project_Code is null or CstJour.Project_Code='', '****', if($parentprjcost=1, ifNull(Project.Parent_Code, Project.Project_Code), CstJour.Project_Code )) As ProjectCode, ";
			else 
				$queryjournal = $queryjournal." Null As ProjectCode, ";
				
			if($showcostcenter ==1 && $printgrpproject	== 1) 	
				$queryjournal = $queryjournal." if(CstJour.Costcent_Code is null or CstJour.Costcent_Code='', '****', if($parentprjcost=1, ifNull(Costcent.Parent_Code, Costcent.Costcent_Code), CstJour.Costcent_Code)) As CostcentCode, ";
			else 
				$queryjournal = $queryjournal." Null As CostcentCode, ";
			
			
							
			$queryjournal = $queryjournal.				
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
							" if(CstJour.Cst_increment is null,JournalDt_Amount1, CstJour_Amount1), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount1, (-1)*CstJour_Amount1))) AS AmountBase1, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
							" if(CstJour.Cst_increment is null,JournalDt_Amount2, CstJour_Amount2), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount2, (-1)*CstJour_Amount2))) AS AmountBase2, ".
							" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
							" FinancialTotLabel.FinancialTot_ShowResult ".
							" From Ledger ".
							" Inner Join FinancialTemplate on (Ledger.Ledger_Number = FinancialTemplate.Ledger_Number) ".
							" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ".
							" Left Join $DirSchema.JournalDt As JournalDt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,'%')) ".
							" Left Join $DirSchema.Journal As Journal on Journal.Journal_ID = JournalDt.Journal_ID ".
							" 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)
				$queryjournal= $queryjournal." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
											 "		  	    where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
											 "              and (loginstk.project_code is not null and loginstk.project_code != '') ".
											 "			  ) Q1 on CstJour.project_code like concat(Q1.project_code,'%') ";				
											 
											 
			if ($costcentexist > 0)
				$queryjournal= $queryjournal." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
										   "			  where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
										   "              and (costcent_code is not null and costcent_code != '') ".
										   "			) Q2 on CstJour.costcent_code like concat(Q2.costcent_code,'%') ";							 
							 
			$queryjournal= $queryjournal.  
								" where FinancialTotLabel.FinancialTot_TreeCode = $reportoption  ";
								//" and Ledger.Ledger_grpdet = 1 ";
								
									  
			if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 1) ){  					  
			$queryjournal= $queryjournal." and upper(ifNull(CstJour.project_code,'-1')) like concat(ifNull(upper(".$fromproject."), upper(ifNull(CstJour.project_code,'-1'))),'%') ".
											 " and upper(ifNull(CstJour.Costcent_Code,'-1')) like concat(ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))),'%') ";

			}
			else if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 0) ){  					  
			$queryjournal= $queryjournal." 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 ($RowsDirCount > 1 && $k != 1)	
				$queryjournal= $queryjournal." And Journal.Journal_Type <> 'OP' ";
			
			$queryjournal= $queryjournal." Group By Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, FinancialTot_Label, Financial_Order, ".
										 " FinancialTemplate.FinancialTot_Code, JournalDt.Journal_Date, ProjectCode, CostcentCode ";
																				 
		}

		
		// Show Detail Option
		if ($showdetail == 1) {
		
			$queryjournal= $queryjournal." Union ";
		
			if ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1) {
				$queryjournal = $queryjournal.
								" Select Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, ".
								" FinancialTemplate.FinancialTot_Code, FinancialTot_Label, Financial_Order, ".
								" JournalDt.Journal_Date, ".
								" Max(Month(JournalDt.Journal_Date)) As MaxMon, Max(Year(JournalDt.Journal_Date)) As MaxYear, ".
								" Null As ProjectCode, Null As CostcentCode, ".
								" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
								" if(CstJour.Cst_increment is null,JournalDt_Amount1, CstJour_Amount1), ".
								" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount1, (-1)*CstJour_Amount1))) AS AmountBase1, ".
								" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
								" if(CstJour.Cst_increment is null,JournalDt_Amount2, CstJour_Amount2), ".
								" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount2, (-1)*CstJour_Amount2))) AS AmountBase2, ".
								" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
								" FinancialTotLabel.FinancialTot_ShowResult ".
								" From Ledger ".
								" Inner Join FinancialTemplate on (Ledger.Ledger_Number Like Concat(FinancialTemplate.Ledger_Number,'%')) ".
								" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ".
								" Left Join $DirSchema.JournalDt As JournalDt On JournalDt.Ledger_Number = Ledger.ledger_number ".
								" Left Join $DirSchema.Journal As Journal on Journal.Journal_ID = JournalDt.Journal_ID ".
								" Left Outer Join $DirSchema.CstJour As CstJour on JournalDt.JournalDt_ID = CstJour.JournalDT_ID ";
								
				if ($projectexist >	0)
					$queryjournal= $queryjournal." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
												 "		  	    where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
												 "              and (loginstk.project_code is not null and loginstk.project_code != '') ".
												 "			  ) Q1 on CstJour.project_code like concat(Q1.project_code,'%') ";				
												 
												 
				if ($costcentexist > 0)
					$queryjournal= $queryjournal." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
											   "			  where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
											   "              and (costcent_code is not null and costcent_code != '') ".
											   "			) Q2 on CstJour.costcent_code like concat(Q2.costcent_code,'%') ";							 
								 
								
			} else {
				$queryjournal = $queryjournal.
								" Select Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, ".
								" FinancialTot_Label, Financial_Order, FinancialTemplate.FinancialTot_Code, ".
								" JournalDt.Journal_Date, ".
								" Max(Month(JournalDt.Journal_Date)) As MaxMon, Max(Year(JournalDt.Journal_Date)) As MaxYear, ".
								" Null As ProjectCode, Null As CostcentCode, ".
								" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount1, (-1)*JournalDt_Amount1)) AS AmountBase1, ".
								" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount2, (-1)*JournalDt_Amount2)) AS AmountBase2, ".
								" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
								" FinancialTotLabel.FinancialTot_ShowResult ".
								" From Ledger ".
								" Inner Join FinancialTemplate on (Ledger.Ledger_Number Like Concat(FinancialTemplate.Ledger_Number,'%')) ".
								" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ".
								" Left Join $DirSchema.JournalDt As JournalDt On JournalDt.Ledger_Number = Ledger.ledger_number ".
								" Left Join $DirSchema.Journal As Journal on Journal.Journal_ID = JournalDt.Journal_ID ";

			}	  
					  
					  

			$queryjournal= $queryjournal.  
									" where FinancialTotLabel.FinancialTot_TreeCode = $reportoption  ".
									" and Ledger.Ledger_grpdet = 0 ".
									" and FinancialTemplate.Ledger_ShowDt = 1 ";
									
										  
			if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 1) ){  					  		  
				$queryjournal= $queryjournal." and upper(ifNull(CstJour.project_code,'-1')) like concat(ifNull(upper(".$fromproject."), upper(ifNull(CstJour.project_code,'-1'))),'%') ".
											 " and upper(ifNull(CstJour.Costcent_Code,'-1')) like concat(ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))),'%') ";

			}
			else if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 0) ){  					  		  
				$queryjournal= $queryjournal." 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 ($RowsDirCount > 1 && $k != 1)	
				$queryjournal= $queryjournal." And Journal.Journal_Type <> 'OP' ";
						
			$queryjournal= $queryjournal." Group By Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, FinancialTot_Label, Financial_Order, ".
										 " FinancialTemplate.FinancialTot_Code, JournalDt.Journal_Date, ProjectCode, CostcentCode ";
										 
			//Option Print Detail Project/Costcenter							 
			if (($showcostcenter == 1 || $showproject == 1) && $printdetproject == 1) {
		
				$queryjournal= $queryjournal." Union ";		
				
				$queryjournal = $queryjournal.
								" Select Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, ".
								" FinancialTemplate.FinancialTot_Code, FinancialTot_Label, Financial_Order, ".
								" JournalDt.Journal_Date, ".
								" Max(Month(JournalDt.Journal_Date)) As MaxMon, Max(Year(JournalDt.Journal_Date)) As MaxYear, ";
								
				if($showproject ==1 && $printdetproject	== 1) 
					$queryjournal = $queryjournal." if(CstJour.Project_Code is null, '****' or CstJour.Project_Code='', if($parentprjcost=1, ifNull(Project.Parent_Code, Project.Project_Code), CstJour.Project_Code )) As ProjectCode, ";
				else 
					$queryjournal = $queryjournal." Null As ProjectCode, ";
					
				if($showcostcenter ==1 && $printdetproject	== 1) 	
					$queryjournal = $queryjournal." if(CstJour.Costcent_Code is null or CstJour.Costcent_Code='', '****', if($parentprjcost=1, ifNull(Costcent.Parent_Code, Costcent.Costcent_Code), CstJour.Costcent_Code)) As CostcentCode, ";
				else 
					$queryjournal = $queryjournal." Null As CostcentCode, ";
								
				
				$queryjournal = $queryjournal.
								" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
								" if(CstJour.Cst_increment is null,JournalDt_Amount1, CstJour_Amount1), ".
								" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount1, (-1)*CstJour_Amount1))) AS AmountBase1, ".
								" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
								" if(CstJour.Cst_increment is null,JournalDt_Amount2, CstJour_Amount2), ".
								" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount2, (-1)*CstJour_Amount2))) AS AmountBase2, ".
								" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
								" FinancialTotLabel.FinancialTot_ShowResult ".
								" From Ledger ".
								" Inner Join FinancialTemplate on (Ledger.Ledger_Number Like Concat(FinancialTemplate.Ledger_Number,'%')) ".
								" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ".
								" Left Join $DirSchema.JournalDt As JournalDt On JournalDt.Ledger_Number = Ledger.ledger_number ".
								" Left Join $DirSchema.Journal As Journal on Journal.Journal_ID = JournalDt.Journal_ID ".
								" 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)
					$queryjournal= $queryjournal." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
												 "		  	    where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
												 "              and (loginstk.project_code is not null and loginstk.project_code != '') ".
												 "			  ) Q1 on CstJour.project_code like concat(Q1.project_code,'%') ";				
												 
												 
				if ($costcentexist > 0)
					$queryjournal= $queryjournal." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
											   "			  where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
											   "              and (costcent_code is not null and costcent_code != '') ".
											   "			) Q2 on CstJour.costcent_code like concat(Q2.costcent_code,'%') ";							 
								 
				$queryjournal= $queryjournal.  
										" where FinancialTotLabel.FinancialTot_TreeCode = $reportoption  ".
										" and Ledger.Ledger_grpdet = 0 ".
										" and FinancialTemplate.Ledger_ShowDt = 1 ";
										
											  
						  
				if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 1) ){

					$queryjournal= $queryjournal." and upper(ifNull(CstJour.project_code,'-1')) like concat(ifNull(upper(".$fromproject."), upper(ifNull(CstJour.project_code,'-1'))),'%') ".
												 " and upper(ifNull(CstJour.Costcent_Code,'-1')) like concat(ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))),'%') ";
				}
				else if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 0) ){

					$queryjournal= $queryjournal." 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 ($RowsDirCount > 1 && $k != 1)	
					$queryjournal= $queryjournal." And Journal.Journal_Type <> 'OP' ";

				$queryjournal= $queryjournal." Group By Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, FinancialTot_Label, Financial_Order, ".
											 " FinancialTemplate.FinancialTot_Code, JournalDt.Journal_Date, ProjectCode, CostcentCode ";
										 
			}	

		}	
		  
		if ($RowsDirCount > 1 && $j < $RowsDirCount)	
			$queryjournal= $queryjournal." Union ";
								
	}							
}

$queryjournal= $queryjournal." ) Q1  ".
                             " Group By Q1.$Ledger_Number, Q1.$Ledger_Name, Q1.Ledger_GrpDet, Q1.FinancialTot_Label, ".
							 " Q1.Financial_Order, Q1.FinancialTot_Code, Q1.ProjectCode, Q1.CostcentCode, Q1.MasterRecord, Q1.FinancialTot_Level ".
							 " Having (($showzerobal = 1 and 1 = 1) or ($showzerobal != 1 and BalanceBase1 != 0)) ".
							 " Union ".
							 " Select Null As $Ledger_Number, Null As $Ledger_Name, 1 As Ledger_GrpDet, a.FinancialTot_Code, ".
							 " a.FinancialTot_Label, 1 As Financial_Order, Q1.ProjectCode As ProjectCode, Q1.CostcentCode As CostcentCode, 3 As MasterRecord, round(a.FinancialTot_Level) as FinancialTot_Level, ".
							 " SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase1, 0)) AS PrvBalanceBase1, ".
							 " SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase2, 0)) AS PrvBalanceBase2, ".
							 //" if (upper(a.FinancialTot_Label) != 'STOCK', SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase1, 0)), ".
							 //"     (ifNull(GetStockValue('".$enddate."', '".$Base1."', Q1.ProjectCode, Q1.CostcentCode),0) - ifNull(GetStockValue('".$startdate."', '".$Base1."', Q1.ProjectCode, Q1.CostcentCode),0)) ) AS BalanceBase1, ".
							 //" if (upper(a.FinancialTot_Label) != 'STOCK', SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase2, 0)), ".
							 //"     (ifNull(GetStockValue('".$enddate."', '".$Base2."', Q1.ProjectCode, Q1.CostcentCode),0) - ifNull(GetStockValue('".$startdate."', '".$Base2."', Q1.ProjectCode, Q1.CostcentCode),0)) ) AS BalanceBase2, ".
							 " SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase1, 0)) AS BalanceBase1, ".
							 " SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), Q1.AmountBase2, 0)) AS BalanceBase2, ".
							 " a.FinancialTot_LevelCode, a.FinancialTot_ShowResult  ";

if ($monthdist == 1 ) {							 
	for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

		if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
		else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
		else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
		else { $vMFrom = 1; $vMTo = 12; }
		
		for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
		
			$queryjournal = $queryjournal.", SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), if((MaxMon = '".$m."') and (MaxYear = '".$y."'), Q1.AmountBase1, 0), 0)) AS ".getMonth($m).$y."Base1 ".
										  ", SUM(if(date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Q1.Journal_date,'%Y-%m-%d')) and date_format(Q1.Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Q1.Journal_date,'%Y-%m-%d')), if((MaxMon = '".$m."') and (MaxYear = '".$y."'), Q1.AmountBase2, 0), 0)) AS ".getMonth($m).$y."Base2 ";
		
		}

	}
}

$queryjournal = $queryjournal.							 
							 " From FinancialTotLabel As a ".
							 " Left Join FinancialTotLabel as b on a.FinancialTot_RelatedCode=b.FinancialTot_Code ".
							 " Left Join ( ";
$j = 0;				
$k = 0; // Count For First Existsing Db

// 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;   							 
							 
		if ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1) {
		    $queryjournal = $queryjournal.
							" Select Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, ".
							" FinancialTemplate.FinancialTot_Code, FinancialTot_Label, Financial_Order, ".
							" JournalDt.Journal_Date, ".
							" Max(Month(JournalDt.Journal_Date)) As MaxMon, Max(Year(JournalDt.Journal_Date)) As MaxYear, ";
							
							if($showproject ==1 && $printgrpproject	== 1) 
								$queryjournal = $queryjournal." if(CstJour.Project_Code is null or CstJour.Project_Code='', '****', CstJour.Project_Code ) As ProjectCode, ";
							else 
								$queryjournal = $queryjournal." Null As ProjectCode, ";
								
							if($showcostcenter ==1 && $printgrpproject	== 1) 	
								$queryjournal = $queryjournal." if(CstJour.Costcent_Code is null or CstJour.Costcent_Code='', '****', CstJour.Costcent_Code) As CostcentCode, ";
							else 
								$queryjournal = $queryjournal." Null As CostcentCode, ";
				
							
							//" Null As ProjectCode, Null As CostcentCode, ".
							
			$queryjournal = $queryjournal.
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
							" if(CstJour.Cst_increment is null,JournalDt_Amount1, CstJour_Amount1), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount1, (-1)*CstJour_Amount1))) AS AmountBase1, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
							" if(CstJour.Cst_increment is null,JournalDt_Amount2, CstJour_Amount2), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount2, (-1)*CstJour_Amount2))) AS AmountBase2, ".
							" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_RelatedCode , FinancialTotLabel.FinancialTot_LevelCode ".
							" From Ledger ".
							" Inner Join FinancialTemplate on (Ledger.Ledger_Number = FinancialTemplate.Ledger_Number) ".
							" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ".
							" Left Join $DirSchema.JournalDt As JournalDt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,'%')) ".
							" Left Join $DirSchema.Journal As Journal on Journal.Journal_ID = JournalDt.Journal_ID ".
							" Left Outer Join $DirSchema.CstJour As CstJour on JournalDt.JournalDt_ID = CstJour.JournalDT_ID ";
							
			if ($projectexist >	0)
				$queryjournal= $queryjournal." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
											 "		  	    where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
											 "              and (loginstk.project_code is not null and loginstk.project_code != '') ".
											 "			  ) Q1 on CstJour.project_code like concat(Q1.project_code,'%') ";				
											 
											 
			if ($costcentexist > 0)
				$queryjournal= $queryjournal." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
										   "			  where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
										   "              and (costcent_code is not null and costcent_code != '') ".
										   "			) Q2 on CstJour.costcent_code like concat(Q2.costcent_code,'%') ";							 
							 
							
		} else {
			$queryjournal = $queryjournal.
							" Select Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, ".
							" FinancialTot_Label, Financial_Order, FinancialTemplate.FinancialTot_Code, ".
							" JournalDt.Journal_Date, ".
							" Max(Month(JournalDt.Journal_Date)) As MaxMon, Max(Year(JournalDt.Journal_Date)) As MaxYear, ".
							" Null As ProjectCode, Null As CostcentCode, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount1, (-1)*JournalDt_Amount1)) AS AmountBase1, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount2, (-1)*JournalDt_Amount2)) AS AmountBase2, ".
							" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_RelatedCode, FinancialTotLabel.FinancialTot_LevelCode ".
							" From Ledger ".
							" Inner Join FinancialTemplate on (Ledger.Ledger_Number = FinancialTemplate.Ledger_Number) ".
							" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ".
							" Left Join $DirSchema.JournalDt As JournalDt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,'%')) ".
							" Left Join $DirSchema.Journal As Journal on Journal.Journal_ID = JournalDt.Journal_ID ";

		}	  
				  
				  

		$queryjournal= $queryjournal.  
								" where FinancialTotLabel.FinancialTot_TreeCode = $reportoption  ";
								//" and Ledger.Ledger_grpdet = 1 ";
								
									  
				  
		if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 1) ){

			$queryjournal= $queryjournal." and upper(ifNull(CstJour.project_code,'-1')) like concat(ifNull(upper(".$fromproject."), upper(ifNull(CstJour.project_code,'-1'))),'%') ".
										 " and upper(ifNull(CstJour.Costcent_Code,'-1')) like concat(ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))),'%') ";

		}
		else if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 0) ){

			$queryjournal= $queryjournal." 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'))) ";

		}
			
					
		$queryjournal= $queryjournal." Group By Ledger.$Ledger_Number, Ledger.$Ledger_Name, Ledger.Ledger_GrpDet, FinancialTot_Label, Financial_Order, ".
									 " FinancialTemplate.FinancialTot_Code, JournalDt.Journal_Date, ProjectCode, CostcentCode ";
									 
		if ($RowsDirCount > 1 && $j < $RowsDirCount)	
			$queryjournal= $queryjournal." Union ";
								
	}							
}							 
		
$queryjournal= $queryjournal." ) As Q1 on (Q1.FinancialTot_Level = a.FinancialTot_Level and Q1.FinancialTot_Code = a.FinancialTot_Code ) or (Q1.FinancialTot_Level > a.FinancialTot_Level and Q1.FinancialTot_LevelCode like concat(a.FinancialTot_levelCode,'%')) ".
							 " Where a.FinancialTot_TreeCode = $reportoption ".
							 " And a.FinancialTot_Level > 1 ".
							 //"  != 0 and Q1.AmountBase2 != 0) ".
							 " Group By a.FinancialTot_Label, a.FinancialTot_Code, ProjectCode, CostcentCode ".
							 " Having (($showzerobal = 1 and 1 = 1) or ($showzerobal != 1 and BalanceBase1 != 0)) ".
							 " Order By FinancialTot_LevelCode Desc, FinancialTot_Code, Financial_Order, $Ledger_Number, ProjectCode, CostcentCode ".
							 " ) As Q2 ".
							 " Where ($treelevel != 0 and FinancialTot_Level <= $treelevel) or ($treelevel = 0 and 1 = 1) ".
							 " Order by FinancialTot_LevelCode Desc, MasterRecord, FinancialTot_Code, Financial_Order, $Ledger_Number, ProjectCode, CostcentCode ";
							
					
	
//echo $queryjournal; exit;



$MasterGroup = '';
$MasterGroupName = '';
$MainGroup = '';
$PrevBalance   = 0;
$PeriodBalance = 0;
$NetBalance    = 0;

$TotalPrevBalance   = 0;
$TotalPeriodBalance = 0;
$TotalNetBalance    = 0;

$MonthlyBalance   = Array();
$ArrayCostcenter  = Array();
$ArrayBalance     = Array();
$ArraySumBalByCost  = Array();
$ArrayCostcenterTotals  = Array();

$ShowResult = 0;


if ($curr == $Base1) $Decimal = $DecimalBase1;
else $Decimal = $DecimalBase2;

if ($incomebycst == 0 && $incomebyprj == 0) {
	$resultjournal=mysql_query($queryjournal,$connection) or die(mysql_error());

	while($rowsjournal=mysql_fetch_row($resultjournal)){
	
		if ($curr == $Base1) {
			$PrevBalance   = $rowsjournal[10];
			$PeriodBalance = $rowsjournal[12];
			$NetBalance    = $PrevBalance + $PeriodBalance;
		} else {
			$PrevBalance   = $rowsjournal[11];
			$PeriodBalance = $rowsjournal[13];
			$NetBalance    = $PrevBalance + $PeriodBalance;
		}

		if ($showdetail == 1) {
			if ($rowsjournal[2] == 1) $classname = 'group'; else $classname = 'detail'; 
		} else	{
			$classname = 'detail'; 
		}

			
		if ($rowsjournal[8] == 3) {
						
			echo "<tr class='totals' height='30'>"; 
			echo "<td align='right' valign='center'>&nbsp;</td>";
			echo "<td align='left' valign='center'><b>".$rowsjournal[4]."</b></td>";
				
			if ($showprevbal == 1) {
				echo "<td align='right' valign='center'>". format_currency($PrevBalance  , $Decimal) ."</td>";
				echo "<td align='right' valign='center'>". format_currency($PeriodBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='center'>". format_currency($NetBalance   , $Decimal) ."</td>";
			} else {
				echo "<td align='right' valign='center'>&nbsp;</td>";
				echo "<td align='right' valign='center'>". format_currency($PeriodBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='center'>&nbsp;</td>";
			}
			
			// If Show Result Is True
			if ($rowsjournal[15] == 1) {
				$TotalPrevBalance   = $PrevBalance;
				$TotalPeriodBalance = $PeriodBalance;
				$TotalNetBalance    = $NetBalance;
				
				$ShowResult = 1;
			}	
			
			if ($monthdist == 1 ) {
				if ($curr == $Base1)  $i = 16; else $i = 17;
				
				for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

					if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
					else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
					else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
					else { $vMFrom = 1; $vMTo = 12; }
					
					for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
						echo "<td align='right' valign='top'>". format_currency($rowsjournal[$i], $Decimal) ."</td>";
						
						// If Show Result Is True
						if ($rowsjournal[15] == 1) 
							$MonthlyBalance[$i] = $rowsjournal[$i]; 
							
						$i = $i + 2;
					}

				}
			}
				
			echo "</tr>";
			
				
			echo "<tr>"; 
			echo "<td colspan='5'>&nbsp;</td>";
			echo "</tr>"; 
			
			
		} else {
		
		if($showledgertype!=-1) {
			echo "<tr class='$classname' height='20' >"; 
			//echo 'prj='.$rowsjournal[6].' cet= '.$rowsjournal[7];
			if ($rowsjournal[6] == '' && $rowsjournal[7] == '') {
				echo "<td align='left' valign='top'>". $rowsjournal[0] ."</td>";
				echo "<td align='left' valign='top'>". $rowsjournal[1] ."</td>";
			} else {
				echo "<td align='left' valign='top'>". $rowsjournal[6] ."</td>";
				echo "<td align='left' valign='top'>". $rowsjournal[7] ."</td>";
			}	

			if ($showprevbal == 1) {
				echo "<td align='right' valign='top'>". format_currency($PrevBalance  , $Decimal) ."</td>";
				echo "<td align='right' valign='top'>". format_currency($PeriodBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='top'>". format_currency($NetBalance   , $Decimal) ."</td>";	
			} else {
				echo "<td align='right' valign='top'>&nbsp;</td>";
				echo "<td align='right' valign='top'>". format_currency($PeriodBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='top'>&nbsp;</td>";	
			}
			
			
			if ($monthdist == 1 ) {
				if ($curr == $Base1)  $i = 16; else $i = 17;
				
				for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

					if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
					else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
					else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
					else { $vMFrom = 1; $vMTo = 12; }
					
					for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
						echo "<td align='right' valign='top'>". format_currency($rowsjournal[$i], $Decimal) ."</td>";
						$i = $i + 2;
					}

				}
			}
			
			echo "</tr>";
			}
		}
	}
	
	//Display Stock Variation
	if ($showstock == 1	) {
	    //echo "test".':', $fromcst;exit;
		if ($curr == $Base1) {	
			$StockValue = getStockValue($startdate, $enddate, $Base1, $fromproject, $fromcst, $connection);
			if ($showprevbal == 1) {
				$PrevStockValue = getStockValue($prestartdate, $preenddate, $Base1, $fromproject, $fromcst, $connection);
			}
		} else 	{
			$StockValue = getStockValue($startdate, $enddate, $Base2,$fromproject, $fromcst, $connection);
			if ($showprevbal == 1) {
				$PrevStockValue = getStockValue($prestartdate, $preenddate, $Base2, $fromproject, $fromcst, $connection);
			}
		}
		echo "<tr class='totals' height='30'>"; 
		echo "<td align='right' valign='center'>&nbsp;</td>";
		echo "<td align='left' valign='center'><b>Stock</b></td>";
		
		if ($showprevbal == 1) {
			echo "<td align='right' valign='top'>". format_currency($PrevStockValue, $Decimal) ."</td>";
			echo "<td align='right' valign='top'>". format_currency($StockValue, $Decimal) ."</td>";
			echo "<td align='right' valign='top'>". format_currency($StockValue + $PrevStockValue, $Decimal) ."</td>";	
		} else {
			echo "<td align='right' valign='top'>&nbsp;</td>";
			echo "<td align='right' valign='top'>". format_currency($StockValue, $Decimal) ."</td>";
			echo "<td align='right' valign='top'>&nbsp;</td>";	
		}
				
		/*if ($monthdist == 1 ) {
			if ($curr == $Base1)  $i = 16; else $i = 17;
					
			for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

				if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
				else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
				else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
				else { $vMFrom = 1; $vMTo = 12; }
						
				for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
					echo "<td align='right' valign='top'>". format_currency($rowsjournal[$i], $Decimal) ."</td>";
							
					// If Show Result Is True
					if ($rowsjournal[15] == 1) 
						$MonthlyBalance[$i] = $rowsjournal[$i]; 
								
					$i = $i + 2;
				}

			}
		}*/
					
		echo "</tr>";
	}	

	//Display Profit/Loss In IncomeStatement
	if ($ShowResult == 1) {
		if ($monthdist == 0 ) {
			if ($showstock == 1	) {
				$TotalPrevBalance -= $PrevStockValue;
				$TotalPeriodBalance -= $StockValue;
				$TotalNetBalance -= ($StockValue + $PrevStockValue);
			}
			
			if ($showprevbal == 1) {
				if (($FinancialTotSign == 1 && $TotalNetBalance < 0) || ($FinancialTotSign == -1 && $TotalNetBalance > 0)) {
					$totalclass = 'totalprofit';
					$totallabel = 'Total Profit';
				}  else {
					$totalclass = 'totalloss';
					$totallabel = 'Total Loss';
				}	
			} else {
				if (($FinancialTotSign == 1 && $TotalPeriodBalance < 0) || ($FinancialTotSign == -1 && $TotalPeriodBalance > 0)) {
					$totalclass = 'totalprofit';
					$totallabel = 'Total Profit';
				}  else {
					$totalclass = 'totalloss';
					$totallabel = 'Total Loss';
				}
			}	
	
			
			
			echo "<tr class='$totalclass' height='30'>"; 
			echo "<td align='right' valign='center'>&nbsp;</td>";
			echo "<td align='right' valign='center'>".$totallabel."</td>";
			
			if ($showprevbal == 1) {
				echo "<td align='right' valign='center'>". format_currency($TotalPrevBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='center'>". format_currency($TotalPeriodBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='center'>". format_currency($TotalNetBalance, $Decimal) ."</td>";
			} else {
				echo "<td align='right' valign='center'>&nbsp;</td>";
				echo "<td align='right' valign='center'>". format_currency($TotalPeriodBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='center'>&nbsp;</td>";
			}
			
			echo "</tr>";

		} else {
		
			if (($FinancialTotSign == 1 && $TotalPeriodBalance < 0) || ($FinancialTotSign == -1 && $TotalPeriodBalance > 0)) {
				$totalclass = 'totalprofit';
				$totallabel = 'Total Profit';
			}  else {
				$totalclass = 'totalloss';
				$totallabel = 'Total Loss';
			}

			echo "<tr class='$totalclass' height='30'>"; 
			echo "<td align='right' valign='center' colspan='3'>&nbsp;</td>";
			echo "<td align='center' valign='center' >".$totallabel."</td>";
			echo "<td align='right' valign='center' >&nbsp;</td>";
			
			if ($curr == $Base1)  $i = 16; else $i = 17;
				
			for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

				if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
				else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
				else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
				else { $vMFrom = 1; $vMTo = 12; }
					
				for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
				
					if (($FinancialTotSign == 1 && $MonthlyBalance[$i] < 0) || ($FinancialTotSign == -1 && $MonthlyBalance[$i] > 0)) {
						$monthlyclass = 'totalprofit';
						$monthlylabel = 'Profit';
					}  else {
						$monthlyclass = 'totalloss';
						$monthlylabel = 'Loss';
					}
					
					if ($MonthlyBalance[$i] != 0)
						echo "<td align='center' valign='center' class='$monthlyclass'>".$monthlylabel."</td>";
					else
						echo "<td align='right' valign='center'>&nbsp;</td>";
						
					$i = $i + 2;
				}

			}	
			
			echo "</tr>";
			
					
			echo "<tr height='30'>"; 
			echo "<td align='right' valign='center'>&nbsp;</td>";
			echo "<td align='right' valign='center'>Net Result</td>";
			
			if ($showprevbal == 1) {
				echo "<td align='right' valign='center' class='$totalclass'>". format_currency($TotalPrevBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='center' class='$totalclass'>". format_currency($TotalPeriodBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='center' class='$totalclass'>". format_currency($TotalNetBalance, $Decimal) ."</td>";
			} else {
				echo "<td align='right' valign='center'>&nbsp;</td>";
				echo "<td align='right' valign='center' class='$totalclass'>". format_currency($TotalPeriodBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='center'>&nbsp;</td>";
			}
			
			if ($curr == $Base1)  $i = 16; else $i = 17;
				
			for ( $y = $vYearFrom; $y <= $vYearTo; $y += 1) {

				if ($y == $vYearFrom && $y == $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = $vMonthTo; }
				else if ($y == $vYearFrom && $y != $vYearTo) { $vMFrom = $vMonthFrom; $vMTo = 12; }
				else if ($y == $vYearTo && $y != $vYearFrom) { $vMFrom = 1; $vMTo = $vMonthTo; }
				else { $vMFrom = 1; $vMTo = 12; }
						
				for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
				
					if (($FinancialTotSign == 1 && $MonthlyBalance[$i] < 0) || ($FinancialTotSign == -1 && $MonthlyBalance[$i] > 0)) {
						$monthlyclass = 'totalprofit';
					}  else {
						$monthlyclass = 'totalloss';
					}
					
					if ($MonthlyBalance[$i] != 0)
						echo "<td align='right' valign='center' class='$monthlyclass'>". format_currency($MonthlyBalance[$i], $Decimal) ."</td>";
					else
						echo "<td align='right' valign='center'>&nbsp;</td>";
						
					$i = $i + 2;
				}

			}
			
			echo "</tr>";
			
			
		}
					
			
	}
} else {
	$i = -1;
	$resultjournal=mysql_query($queryjournal,$connection) or die(mysql_error());
	while($rowsjournal=mysql_fetch_row($resultjournal)){

		if ($curr == $Base1) {
			$PrevBalance   = $rowsjournal[10];
			$PeriodBalance = $rowsjournal[12];
			$NetBalance    = $PrevBalance + $PeriodBalance;
		} else {
			$PrevBalance   = $rowsjournal[11];
			$PeriodBalance = $rowsjournal[13];
			$NetBalance    = $PrevBalance + $PeriodBalance;
		}
		
		if ($incomebycst == 1) $ProjectCostCent = $rowsjournal[7];
		else if ($incomebyprj == 1) $ProjectCostCent = $rowsjournal[6]; 
		
		if ($rowsjournal[8] != 3) {
			if ($ProjectCostCent == '' && ($MasterGroup == '' || $MasterGroup != $rowsjournal[0]) ) {
				$i = $i + 1;	
			
				$ArrayBalance['LedgerNo'][$i] = $rowsjournal[0];
				$ArrayBalance['LedgerName'][$i] = $rowsjournal[1];
				$ArrayBalance['LedgerGrpDet'][$i] = $rowsjournal[2];
				$ArrayBalance['Total'][$i] = $PeriodBalance;
					
				$MasterGroup = $rowsjournal[0];
			
			}
			else if ($ProjectCostCent != ''){
				
				$CstFound = 0;
				$count = count ($ArrayCostcenter); 
				for ($j=0; $j<$count; $j++){
					if ($ArrayCostcenter[$j] == $ProjectCostCent)
						$CstFound = 1;
				}
				
				if ($CstFound == 0) 
					$ArrayCostcenter[$count] = $ProjectCostCent;
					
				$ArrayBalance[$ProjectCostCent][$i] = $PeriodBalance;
			
			} 	
		} else {
			if ($MainGroup == '' || $MainGroup != $rowsjournal[4])  {
				$i = $i + 1;
				
				$ArrayBalance['LedgerNo'][$i] = '-1';
				$ArrayBalance['GroupDesc'][$i] = $rowsjournal[4];
				$ArrayBalance['LedgerGrpDet'][$i] = $rowsjournal[2];
				$ArrayBalance['TotLevel'][$i] = $rowsjournal[9];
				$ArrayBalance['Total'][$i] = $PeriodBalance;
				
				$MainGroup = $rowsjournal[4];
			}	
			
			if ($ProjectCostCent != ''){
				$ArrayBalance[$ProjectCostCent][$i] = $PeriodBalance;
			}
		} 
	
	}	
	
	//sorting data in array
	array_multisort($ArrayCostcenter);
	
	echo" <col width=100>
		  <col width=280>";
	
	$count = count ($ArrayCostcenter); 
	for ($j=0; $j<$count; $j++){ 
	    echo" <col width=140>";
	}
	echo" <col width=140>";
	
	echo"<tr height='30'>
			<th align='left'>Ledger No.</th>
			<th align='left'>Description</th>";
			
	$count = count ($ArrayCostcenter); 
	for ($j=0; $j<$count; $j++){ 
		echo "<th align='center' valign='center'>".$ArrayCostcenter[$j]."</th>";

	}
	echo "<th align='center'>Total $curr</th>
	";
	echo "</tr>";
	
	
	// Displaying Data
	$count = count ($ArrayBalance['LedgerNo']); 
	for ($i=0; $i<$count; $i++){
		$countmore=count($ArrayCostcenter);
		
		if ($showdetail == 1) {
			if ($ArrayBalance['LedgerGrpDet'][$i] == 1) $classname = 'group'; else $classname = 'detail'; 
		} else {
			$classname = 'detail';
		}
			
		if ($ArrayBalance['LedgerNo'][$i] != '-1') {
			echo"<tr class='$classname' height='20'>";
			echo"<td>".$ArrayBalance['LedgerNo'][$i]."</td>";
			echo"<td>".$ArrayBalance['LedgerName'][$i]."</td>";
					
			for ($j=0; $j < $countmore; $j++){
				echo"<td align='right' valign='center'>".format_currency($ArrayBalance[$ArrayCostcenter[$j]][$i], $Decimal)."</td>";
					
				if ($ArrayBalance['LedgerGrpDet'][$i] == 1) {
					$ArraySumBalByCost[$ArrayCostcenter[$j]] = $ArraySumBalByCost[$ArrayCostcenter[$j]] + $ArrayBalance[$ArrayCostcenter[$j]][$i];
				}	
			}

			echo"<td align='right' valign='center'>".format_currency($ArrayBalance['Total'][$i], $Decimal)."</td>";
			echo"</tr>";
				
			if ($ArrayBalance['LedgerGrpDet'][$i] == 1)
				$ArraySumBalByCost['Total'] = $ArraySumBalByCost['Total'] + $ArrayBalance['Total'][$i];
				
		} else {
			echo"<tr class='totals' height='30'>";
			echo"<td>&nbsp;</td>";
			echo"<td>".$ArrayBalance['GroupDesc'][$i]."</td>";
			
			$MainGroupTotals = 0;
			for ($j=0; $j < $countmore; $j++){
				echo"<td align='right' valign='center'>".format_currency($ArrayBalance[$ArrayCostcenter[$j]][$i], $Decimal)."</td>";
				
				$MainGroupTotals += $ArrayBalance[$ArrayCostcenter[$j]][$i];
			}

			echo"<td align='right' valign='center'>".format_currency($MainGroupTotals, $Decimal)."</td>";
			echo"</tr>";
			
		}
	}
	
	//Display Stock Variation
	if ($showstock == 1	) {
		echo "<tr class='totals' height='30'>"; 
		echo "<td align='right' valign='center'>&nbsp;</td>";
		echo "<td align='left' valign='center'><b>Stock</b></td>";
			
		for ($j=0; $j < $countmore; $j++){
			$ProjCostCenter = $ArrayCostcenter[$j];
			if ($ProjCostCenter == '****') $ProjCostCenter = '-1';
			
			if ($curr == $Base1) {	
				$StockValueTot = getStockValue($startdate, $enddate, $Base1, '', '', $connection);
				
				if ($incomebycst == 1)
					$StockValue = getStockValue($startdate, $enddate, $Base1, '', $ProjCostCenter, $connection);
				else
					$StockValue = getStockValue($startdate, $enddate, $Base1, $ProjCostCenter, '', $connection);
			} else 	{
				$StockValueTot = getStockValue($startdate, $enddate, $Base2, '', '', $connection);
				
				if ($incomebycst == 1)
					$StockValue = getStockValue($startdate, $enddate, $Base2, '', $ProjCostCenter, $connection);
				else
					$StockValue = getStockValue($startdate, $enddate, $Base2, $ProjCostCenter, '', $connection);
			}
		
			echo"<td align='right' valign='center'>".format_currency($StockValue, $Decimal)."</td>";
						
			$ArraySumBalByCost[$ArrayCostcenter[$j]] = $ArraySumBalByCost[$ArrayCostcenter[$j]] - $StockValue;
		}

		echo"<td align='right' valign='center'>".format_currency($StockValueTot, $Decimal)."</td>";
		echo"</tr>";
					
		$ArraySumBalByCost['Total'] = $ArraySumBalByCost['Total'] - $StockValueTot;
	}
	
	
	// Displaying Totals
	echo"<tr class='group' height='30'>";
	echo"  <td>&nbsp;</td>";
	echo"  <td align='right'>Total $curr</td>";
		
	$count=count($ArrayCostcenter);
	for ($j=0; $j < $countmore; $j++){
		echo"<td align='right' valign='center'>".format_currency($ArraySumBalByCost[$ArrayCostcenter[$j]], $Decimal)."</td>";
	
	}

	echo"<td align='right' valign='center'>".format_currency($ArraySumBalByCost['Total'], $Decimal)."</td>";
	echo"</tr>";

}

echo "</table></tr></td></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, $Decimal) { 

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

function getMonth($month){
     return date('F', mktime(0,0,0,$month,1));
}

function getStockValue($PStartDate, $PEndDate, $PCurr, $PProject, $PCostCent, $connection){
	$query = " Select (ifNull(GetStockValueItemsType('".$PEndDate."', '".$PCurr."', ".$PProject.", ".$PCostCent."),0) -  ".
			 " ifNull(GetStockValueItemsType('".$PStartDate."', '".$PCurr."', ".$PProject.", ".$PCostCent."),0)) as StockValue ";

	$result=mysql_query($query,$connection) or die(mysql_error());
	$row=mysql_fetch_row($result);

	return $row[0];
}
		
if ($printaccess==1)
print <<< HERE

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

?>