<?php

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

// var_dump($_GET);
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);
ini_set('max_execution_time', '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);
}


if (empty($reportprojectoption))   
    $reportprojectoption = '';
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('   a4'    .mysql_error());
while($sub_rows = mysql_fetch_array($sub_result)){
	extract($sub_rows);
}	

if($exp ==1){
	$filename = "exp_".$ReportName."_". date('Ymd') . ".xls";
	header("Content-Disposition: attachment; filename=\"$filename\"");
	header("Content-Type: application/vnd.ms-excel");
} 
$itemprint = $_GET['itemprint'];
if($prtgrpheader == '') $prtgrpheader = 0;
if($showloan == '') $showloan = 0; 
if($showper == '') $showper = 0; 

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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
	$(document).ready(function(){
		$(".toggler").click(function(e){
			e.preventDefault();
			$('.cls'+$(this).attr('data-grp-class')).toggle();
		});
	});
</script>

HERE;


$querylog="SELECT print as printaccess,ifNull(login_belongstogrp,0) As FI_BelongsToGrp from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
	$resultlog=mysql_query($querylog,$connection) or die('   a5'    .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('   a6'    .mysql_error());
while($rows=mysql_fetch_array($resultsetup)){
  extract($rows);
}

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

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


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

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

if($showledgernbr == '') $showledgernbr = 0;
 $showledgernbr = 1;

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'>";
	if($exp ==0)
	echo "<img src='LogoFile.php' width='200' height='100' />";
	
	echo "</td><td colspan=3 align='right' ><font size='5'><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>";
	

//	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;

  
   
$fromproject = "".$fromproject;

if ($fromproject == '')   
   $fromproject = 'null';
else
   $fromproject = "'".$fromproject."'";    
   
$fromcst = "".$fromcst;  
if ($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);
$vDayFrom  = substr($fromdate, 8, 2);
$vDayTo    = substr($todate, 8, 2);

$vTodate = $vYearTo."-".$vMonthTo;

$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('   a9'    .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='1' width='100%' align='center' class='report-master' style='table-layout:fixed; border-collapse:collapse;' cellpadding='0' cellspacing='0'>
		  <col width=100>
		  <col width=280>";
	if ($showprevbal == 1) echo "	  
		  <col width=140>
		  <col width=140>
		  <col width=140>";
	else echo "<col width=140>";	  
	if($showper == 1) echo"<col width=50>";	  
	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>";
				if($showper == 1) echo"<col width=50>";
			}

		}
	}
		  
	echo"<thead>
	<tr>";
	if($showledgernbr == 1)
	echo "<th align='left'>Ledger No.</th>";
	else echo "<th align='left'></th>";
	echo "<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($showper == 1) echo"<th>%</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>";
				if($showper == 1) echo"<th> % </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('_',$_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 ";

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

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

$StockValueStart = 0;
$StockValueEnd = 0;
$StockValue = 0;

$StockValueStart2 = 0;
$StockValueEnd2 = 0;
$StockValue2 = 0;
if ($showstock == 1	) {
	//echo "test".':', $fromcst;exit;
				
	if ($curr == $Base1) {	
		//with Local
		$StockValueStart = getStockValueStart($startdate, $Base1, $fromproject, $fromcst,$itemprint, 1, $FI_BelongsToGrp, $showloan, $connection);
		if($StockValueStart == '') $StockValueStart = 0;
		$StockValueEnd = getStockValueEnd($enddate, $Base1, $fromproject, $fromcst,$itemprint, 1, $FI_BelongsToGrp, $showloan, $connection);
		if($StockValueEnd == '') $StockValueEnd = 0;
		$StockValue = $StockValueEnd-$StockValueStart;
		
		//without Local
		$StockValueStart2 = getStockValueStart($startdate, $Base1, $fromproject, $fromcst,$itemprint, 0, $FI_BelongsToGrp, $showloan,$connection);
		if($StockValueStart2 == '') $StockValueStart2 = 0;
		$StockValueEnd2 = getStockValueEnd($enddate, $Base1, $fromproject, $fromcst,$itemprint, 0, $FI_BelongsToGrp, $showloan, $connection);
		if($StockValueEnd2 == '') $StockValueEnd2 = 0;
		$StockValue2 = $StockValueEnd2-$StockValueStart2;
					
		if ($showprevbal == 1) {
			//with Local
			$PrevStockValueStart =getStockValueStart($prestartdate, $Base1, $fromproject, $fromcst,$itemprint,1, $FI_BelongsToGrp,$showloan, $connection);
			if($PrevStockValueStart == '') $PrevStockValueStart = 0;
			$PrevStockValueEnd  =getStockValueEnd($preenddate, $Base1, $fromproject, $fromcst,$itemprint,1,$FI_BelongsToGrp, $showloan, $connection);
			if($PrevStockValueEnd == '') $PrevStockValueEnd = 0;
			$PrevStockValue = $PrevStockValueEnd - $PrevStockValueStart;
			
			//without Local
			$PrevStockValueStart2 =getStockValueStart($prestartdate, $Base1, $fromproject, $fromcst,$itemprint,0, $FI_BelongsToGrp,$showloan, $connection);
			if($PrevStockValueStart2 == '') $PrevStockValueStart2 = 0;
			$PrevStockValueEnd2  =getStockValueEnd($preenddate, $Base1, $fromproject, $fromcst,$itemprint,0,$FI_BelongsToGrp, $showloan, $connection);
			if($PrevStockValueEnd2 == '') $PrevStockValueEnd2 = 0;
			$PrevStockValue2 = $PrevStockValueEnd2 - $PrevStockValueStart2;
			
		}
	} else 	{
		//with Local
		$StockValueStart = getStockValueStart($startdate,$Base2,$fromproject,$fromcst,$itemprint, 1,$FI_BelongsToGrp,$showloan, $connection);
		if($StockValueStart == '') $StockValueStart = 0;
		$StockValueEnd = 	getStockValueEnd($enddate,$Base2,$fromproject,$fromcst,$itemprint,1, $FI_BelongsToGrp, $showloan,$connection);
		if($StockValueEnd == '') $StockValueEnd = 0;
		$StockValue = $StockValueEnd-$StockValueStart;
		
		//without Local
		$StockValueStart2 = getStockValueStart($startdate,$Base2,$fromproject,$fromcst,$itemprint, 0,$FI_BelongsToGrp, $showloan,$connection);
		if($StockValueStart2 == '') $StockValueStart2 = 0;
		$StockValueEnd2 = 	getStockValueEnd($enddate,$Base2,$fromproject,$fromcst,$itemprint,0, $FI_BelongsToGrp,$showloan, $connection);
		if($StockValueEnd2 == '') $StockValueEnd2 = 0;
		$StockValue2 = $StockValueEnd2-$StockValueStart2;
		if ($showprevbal == 1) {
			//with Local
			$PrevStockValueStart = getStockValueStart($prestartdate, $Base2, $fromproject, $fromcst,$itemprint,1, $FI_BelongsToGrp,$showloan, $connection);
			if($PrevStockValueStart == '') $PrevStockValueStart = 0;
			$PrevStockValueEnd = getStockValueEnd($preenddate, $Base2, $fromproject, $fromcst,$itemprint, 1,$FI_BelongsToGrp, $showloan,$connection);
			if($PrevStockValueEnd == '') $PrevStockValueEnd = 0;
			$PrevStockValue = $PrevStockValueEnd-$PrevStockValueStart;
			
			//without Local
			$PrevStockValueStart2 = getStockValueStart($prestartdate, $Base2, $fromproject, $fromcst,$itemprint,0,$FI_BelongsToGrp,$showloan,  $connection);
			if($PrevStockValueStart2 == '') $PrevStockValueStart2 = 0;
			$PrevStockValueEnd2 = getStockValueEnd($preenddate, $Base2, $fromproject, $fromcst,$itemprint, 0,$FI_BelongsToGrp, $showloan,$connection);
			if($PrevStockValueEnd2 == '') $PrevStockValueEnd2 = 0;
			$PrevStockValue2 = $PrevStockValueEnd2-$PrevStockValueStart2;
			
		}
		
	
}

}
$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, balanceType, ".
				" Financial_bgcolor,Financial_fontcolor,Financial_fontsize,Financial_isContinuous, FinancialTot_RelatedPer ";

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."PreBase1) 
							, (".getMonth($m).$y."Base2  + ".getMonth($m).$y."PreBase2) ";
		
		}

	}
}

$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, ".
				" if( Q1.$Ledger_Number = '99990001' or Q1.$Ledger_Number = '99980001',SUM(if(date_format(Q1.Journal_date,'%Y-%m') = date_format(". $fromdate.",'%Y-%m'),Q1.AmountBase1,0)),
					if(Q1.$Ledger_Number = '99990002' or Q1.$Ledger_Number = '99980002', SUM(if(date_format(Q1.Journal_date,'%Y-%m') = date_format(". $todate.",'%Y-%m'),Q1.AmountBase1,0)),
					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, ".
				" if( Q1.$Ledger_Number = '99990001' or Q1.$Ledger_Number = '99980001',SUM(if(date_format(Q1.Journal_date,'%Y-%m') = date_format(". $fromdate.",'%Y-%m'),Q1.AmountBase2,0)),
					if(Q1.$Ledger_Number = '99990002' or Q1.$Ledger_Number = '99980002', SUM(if(date_format(Q1.Journal_date,'%Y-%m') = date_format(". $todate.",'%Y-%m'),Q1.AmountBase2,0)),
				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, ".
				" Q1.FinancialTot_LevelCode, Q1.FinancialTot_ShowResult, Q1.balanceType as balanceType, Q1.Financial_bgcolor as Financial_bgcolor,Q1.Financial_fontcolor as Financial_fontcolor,
				Q1.Financial_fontsize as Financial_fontsize,Q1.Financial_isContinuous as Financial_isContinuous, Q1.FinancialTot_RelatedPer ";
				
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 ";
			if($m == 1)							  
			$queryjournal .= " ,0 as ".getMonth($m).$y."PreBase1,0 as ".getMonth($m).$y."PreBase2 ";
			else 
			$queryjournal .= " ,SUM(if(Financial_isContinuous = 1 and date_format(Q1.Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(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-1)."') and (MaxYear = '".$y."'), Q1.AmountBase1, 0), 0)) as  ".getMonth($m).$y."PreBase1 
								, SUM(if(Financial_isContinuous = 1 and 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-1)."') and (MaxYear = '".$y."'), Q1.AmountBase2, 0), 0)) AS ".getMonth($m).$y."PreBase2 ";
						
		}

	}
}

$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 = $RowsDir[0];	
			   
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die('   a14'    .mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
				
	}
	// if($j >= 1) $queryjournal = $queryjournal." UNION ";
	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, concat(Ledger.$Ledger_Name, if(ifnull(FinancialTemplate.costcent_code,'')='',if(ifnull(FinancialTemplate.project_code,'')='','',concat('-',tempproject.project_name)),concat('-',tempcostcent.costcent_name))) as $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.CstJour_Amount1), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount1, (-1)*CstJour.CstJour_Amount1))) AS AmountBase1, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
							" if(CstJour.Cst_increment is null,JournalDt_Amount2, CstJour.CstJour_Amount2), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount2, (-1)*CstJour.CstJour_Amount2))) AS AmountBase2, ".
							" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
							" FinancialTotLabel.FinancialTot_ShowResult, balanceType, ifnull(Financial_bgcolor,'#FFFFFF') as Financial_bgcolor,
							ifnull(Financial_fontcolor,'#000000') as Financial_fontcolor,ifnull(Financial_fontsize,15) as Financial_fontsize,ifnull(Financial_isContinuous,0) as Financial_isContinuous, financialtotlabel.FinancialTot_RelatedPer ".
							" From Ledger ".
							" Inner Join FinancialTemplate on (Ledger.Ledger_Number = FinancialTemplate.Ledger_Number) ".
							" left join costcent as tempcostcent on tempcostcent.Costcent_code = FinancialTemplate.Costcent_code ".
							" left join project as tempproject on tempproject.Project_Code = FinancialTemplate.Project_Code ".
							" 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.currency_code = CstJour.JournalDT_ID ";
							"";
							
			if ($projectexist >	0)
				$queryjournal= $queryjournal." Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
											 "		  	    where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
											 "              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 ".$_SESSION['dbLabel'].".loginstk ".
										   "			  where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
										   "              and (costcent_code is not null and costcent_code != '') ".
										   "			) Q2 on CstJour.costcent_code like concat(Q2.costcent_code,'%') ";	
			//////////////////////////////////////////////////////////////////											   
			$queryjournal= $queryjournal." left join (
									select journaldt.journaldt_id,
								   journaldt.journal_date as journal_date,
								   journaldt.ledger_number,
								   journaldt.journaldt_dbcd,
								   JournalDt_Amount1,
								   JournalDt_Amount2,
								   JournalDt.Currency_Code,
								   journal.journal_type,
								   1 as acctrx_Posted ,
								   journaldt.Journal_BelongsToGroup as journal_BelongsToGroup,
								   Cst_increment,
								   cstjour.Costcent_code,
								   cstjour.Project_Code,
								   Cstjour_prcnt,
								   Cstjour_amount1,
								   Cstjour_amount2
								   from ".$DirSchema.".journal ".
					   " inner join ".$DirSchema.".journaldt on journal.journal_id=journaldt.journal_id 
					   left join  ".$DirSchema.".cstjour on cstjour.journaldt_id=journaldt.journaldt_id ";
				   if ($projectexist >	0)
						$queryjournal .= " Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
											 "		  	    where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
											 "              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 .= " inner join ( SELECT DISTINCT costcent_code FROM ".$_SESSION['dbLabel'].".loginstk
													WHERE loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."')  AND (costcent_code IS NOT NULL
													AND costcent_code != '')
												) q2 on q2.costcent_code=cstjour.costcent_code";
					   }
		$queryjournal .= "	where journaldt.journal_date<='".$enddate."' ";
		if ($RowsDirCount > 1 && $k != 1)	
			$queryjournal= $queryjournal." And (Journal.Journal_Type <> 'OP' ) ";
			$queryjournal .= "	and  if('$showstock' = '1', Journal.Journal_Type <> 'CL', 1=1)";		
		//herenad
		/* $queryjournal .=" union select transdt.transdt_id as journaldt_id,  transdt.trans_date as journal_date,
						   transdt.ledger_number as ledger_number, transdt.transdt_dbcd as journaldt_dbcd, 
						   transdt.transdt_amount1 as journaldt_amount1, transdt.transdt_amount2 as journaldt_amount2,
						   transdt.currency_code,  trans_type as journal_type, 0 as acctrx_Posted,
						   Trans_BelongsToGroup AS journal_BelongsToGroup, CstJourDt_id as Cst_increment,
						   Costcenter_Code AS Costcent_code, cstjourdt.Project_code,
						   cstjourdt.CstjourDt_Per AS Cstjour_prcnt, CstJourDt_Amount1 AS Cstjour_amount1,
						   CstJourDt_Amount2 AS Cstjour_amount2 
						  from ".$DirSchema.".trans ".
					   " inner join ".$DirSchema.".transdt on trans.trans_id=transdt.trans_id and trans.acctrx_Posted=0 
						 left join ".$DirSchema.".cstjourdt on cstjourdt.TransDt_id=transdt.TransDt_id ";
	   if ($projectexist > 0) {
		   $queryjournal .= " 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 != '')) q2 on q2.project_code=cstjourdt.project_code ";
	   }
	   if ($costcentexist > 0) {
		   $queryjournal .= " inner join (SELECT DISTINCT costcent_code
					   FROM ".$_SESSION['dbLabel'].".loginstk
					   WHERE loginstk.user_account='".$_SESSION['useraccount']."' 
					   AND (costcent_code IS NOT NULL
					   AND costcent_code != '')) q2 on q2.costcent_code=cstjourdt.costcenter_code ";
	   }
			$queryjournal .= "	where transdt.trans_date<='".$enddate."'";   */
		

		if($showstock==1) {	
		// Monthly Distribution		
		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) {
					
					if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
					else $lastDate = "LAST_DAY('$y-$m-01')";
					
					//Whith Local		
					$queryjournal .= " union select 1 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ";
					$queryjournal .= "'99990001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',0),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
					
					$queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1, ".
									 " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',0),0)  AS journaldt_amount2,  '$curr' AS currency_code,".
									 " 'ST' AS journal_type,	1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup,	null as Cst_increment,
									 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
									 " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,".
									 " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
									 " from dual ".
									 " union   select 2 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ";
					$queryjournal .= " '99990002' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
						
					$queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
									 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
									 " from dual";
					//Whithout Local				 
					$queryjournal .= " union   select 1 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ";
					$queryjournal .= "'99980001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',0),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
					
					$queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1, ".
									 " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)  AS journaldt_amount2,  '$curr' AS currency_code,".
									 " 'ST' AS journal_type,	1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup,	null as Cst_increment,
									 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
									 " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,".
									 " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
									 " from dual ".
									 " union   select 2 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ";
					$queryjournal .= " '99980002' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
						
					$queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
									 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
									 " from dual ";	
									 //RM
					$queryjournal .= " union select 3 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
									 " '99940001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
									" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
									 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
									 " from dual ".//FG
									 " union   select 4 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
									 " '99950001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
									 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
									 " from dual ";			
				}
			}
		
		} 
		else {
			if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
			else $lastDate = "LAST_DAY(".$fromdate.")";
			//Whith Local	
			$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
			$queryjournal .= "     '99990001' as ledger_number,"."     IF(". $StockValueStart."*-1>=0 ,'C','D') as journaldt_dbcd, ";
			
			$queryjournal .= $StockValueStart." AS journaldt_amount1,".$StockValueStart." AS journaldt_amount2,  '$curr' AS currency_code,".
							"      'ST' AS journal_type,	1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup,	null as Cst_increment,
							".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
							".$StockValueStart."  AS Cstjour_amount1,".$StockValueStart."  AS Cstjour_amount2 ".
							" from dual ".
							" union   select 2 as journaldt_id,".$todate." as journal_date, ";
			$queryjournal .= " '99990002' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ";
				

				$queryjournal .= $StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
								"  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
							".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
							".$StockValueEnd."  AS Cstjour_amount1,	".$StockValueEnd."  AS Cstjour_amount2 ".
							" from dual";
			//Whithout Local					
			$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
			$queryjournal .= "     '99980001' as ledger_number,"."     IF(". $StockValueStart2."*-1>=0 ,'C','D') as journaldt_dbcd, ";
			
			$queryjournal .= $StockValueStart2." AS journaldt_amount1,".$StockValueStart2." AS journaldt_amount2,  '$curr' AS currency_code,".
							"      'ST' AS journal_type,	1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup,	null as Cst_increment,
							".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
							".$StockValueStart2."  AS Cstjour_amount1,".$StockValueStart2."  AS Cstjour_amount2 ".
							" from dual ".
							" union   select 2 as journaldt_id,".$todate." as journal_date, ";
			$queryjournal .= " '99980002' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ";
				

				$queryjournal .= $StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
								"  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
							".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
							".$StockValueEnd2."  AS Cstjour_amount1,	".$StockValueEnd2."  AS Cstjour_amount2 ".
							" from dual";	
			//RM
			$queryjournal .= " union   select 3 as journaldt_id,".$todate." as journal_date, ".
							 " '99940001' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ".
							 " ".$StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
							 "  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
							 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
							 ".$StockValueEnd2."  AS Cstjour_amount1,	".$StockValueEnd2."  AS Cstjour_amount2 ".
							 " from dual ".		//FG				
							 " union   select 4 as journaldt_id,".$todate." as journal_date, ".
							 " '99950001' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ".
							 " ".$StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
								"  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
							".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
							".$StockValueEnd."  AS Cstjour_amount1,	".$StockValueEnd."  AS Cstjour_amount2 ".
							" from dual";				 
		}
					
		}			 
			
			$queryjournal .= " ) 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 ";
							
		} else {
			$queryjournal = $queryjournal.
							" Select Ledger.$Ledger_Number, concat(Ledger.$Ledger_Name, if(ifnull(FinancialTemplate.costcent_code,'')='',if(ifnull(FinancialTemplate.project_code,'')='','',concat('-',tempproject.project_name)),concat('-',tempcostcent.costcent_name))) as $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(FinancialTemplate.Project_code is not null or FinancialTemplate.costcent_code is not null,if(JournalDt.JournalDt_DbCd='D', Cstjour_amount1, (-1)*Cstjour_amount1),if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount1, (-1)*JournalDt_Amount1))) AS AmountBase1, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(FinancialTemplate.Project_code is not null or FinancialTemplate.costcent_code is not null,if(JournalDt.JournalDt_DbCd='D', Cstjour_amount2, (-1)*Cstjour_amount2),if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount2, (-1)*JournalDt_Amount2))) AS AmountBase2, ".
							" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
							" FinancialTotLabel.FinancialTot_ShowResult, balanceType, ifnull(Financial_bgcolor,'#FFFFFF') as Financial_bgcolor,
							ifnull(Financial_fontcolor,'#000000') as Financial_fontcolor,ifnull(Financial_fontsize,15) as Financial_fontsize,ifnull(Financial_isContinuous,0) as Financial_isContinuous, financialtotlabel.FinancialTot_RelatedPer ".
							" From Ledger ".
							" Inner Join FinancialTemplate on (Ledger.Ledger_Number = FinancialTemplate.Ledger_Number) ".
							" left join costcent as tempcostcent on tempcostcent.Costcent_code = FinancialTemplate.Costcent_code ".
							" left join project as tempproject on tempproject.Project_Code = FinancialTemplate.Project_Code ".
							" 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 Join $DirSchema.CstJour As CstJour on CstJour.JournalDt_ID = journaldt.currency_code ";
							"";

							//////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
			$queryjournal .=" left join (select journaldt.journaldt_id,journaldt.journal_date as journal_date,journaldt.ledger_number,journaldt.journaldt_dbcd,JournalDt_Amount1,JournalDt_Amount2, journaldt.currency_code, 
							journal.journal_type,1 as acctrx_Posted, journaldt.Journal_BelongsToGroup as journal_BelongsToGroup 
							from ".$DirSchema.".journal,".$DirSchema.".journaldt where journal.journal_id=journaldt.journal_id and journaldt.journal_date<='".$enddate."'";
			if ($RowsDirCount > 1 && $k != 1)	
			$queryjournal= $queryjournal." And (Journal.Journal_Type <> 'OP') ";
			$queryjournal .= " and if('$showstock' = '1', Journal.Journal_Type <> 'CL', 1=1) ";				
			//herenad
			/* $queryjournal .= " union select transdt.transdt_id as journaldt_id,transdt.trans_date as journal_date,transdt.ledger_number as ledger_number, ".
						   " transdt.transdt_dbcd as journaldt_dbcd, transdt.transdt_amount1 as journaldt_amount1,transdt.transdt_amount2 as journaldt_amount2, transdt.currency_code, trans_type as journal_type,0 as acctrx_Posted, transdt.currency_code  from ".
						   $DirSchema.".trans,".$DirSchema.".transdt where trans.trans_id=transdt.trans_id ".
						   " and trans.acctrx_Posted=0 and transdt.trans_date<='".$enddate."'"; */
						   
			   ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////			
		if($showstock==1) {
				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) {
							if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
							else $lastDate = "LAST_DAY('$y-$m-01')";
							//With Local							
								$queryjournal .= " union   select 1 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
							$queryjournal .= "  '99990001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
							
								$queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												 " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												 "'$Curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
												 " from dual 
												 union  select 2 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ";
							$queryjournal .= " '99990002' as ledger_number,IF(ifNull(GetStockValueCostMethod( concat($lastDate,' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
							
								$queryjournal .= " ifNull(GetStockValueCostMethod( concat($lastDate,' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1, ".
												 " ifNull(GetStockValueCostMethod( concat($lastDate,' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												 " '$Curr' AS currency_code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
												 " from dual";
							//Without Local
								$queryjournal .= " union   select 1 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
								$queryjournal .= "  '99980001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',0),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
							
								$queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												 " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												 "'$Curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
												 " from dual 
												 union  select 2 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ";
								$queryjournal .= " '99980002' as ledger_number,IF(ifNull(GetStockValueCostMethod( concat($lastDate,' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
							
								$queryjournal .= " ifNull(GetStockValueCostMethod( concat($lastDate,' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1, ".
												 " ifNull(GetStockValueCostMethod( concat($lastDate,' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												 " '$Curr' AS currency_code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
												 " from dual ";
												 
							//RM
								$queryjournal .= " union select 3 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
												 " '99940001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup 
													from dual ".//FG
												 " union   select 4 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
												 " '99950001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup 
												  from dual ";					 
						}
					}
				
				} 
				else {
					if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
					else $lastDate = "LAST_DAY(".$fromdate.")";
					
						//With Local		
						$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
						$queryjournal .= "  '99990001' as ledger_number,  IF(". $StockValueStart."*-1>=0 ,'C','D') as journaldt_dbcd, ";
					

						$queryjournal .= $StockValueStart." AS journaldt_amount1,".$StockValueStart." AS journaldt_amount2,".
										"'$Curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
										" from dual 
										union  select 2 as journaldt_id,".$todate." as journal_date, ";
						$queryjournal .= " '99990002' as ledger_number,  IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ";
					
						$queryjournal .=  $StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
										 " '$Curr' AS currency_code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
										 " from dual";
					//Without Local		
					$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
					$queryjournal .= "  '99980001' as ledger_number,   IF(". $StockValueStart2."*-1>=0 ,'C','D') as journaldt_dbcd, ";
					

						$queryjournal .= $StockValueStart2." AS journaldt_amount1,".$StockValueStart2." AS journaldt_amount2,".
										"'$Curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
										" from dual 
										union  select 2 as journaldt_id,".$todate." as journal_date, ";
						$queryjournal .= " '99980002' as ledger_number,   IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ";
										  
						$queryjournal .=  $StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
										 " '$Curr' AS currency_code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
										 " from dual";	
						
						//RM
					$queryjournal .= " union   select 3 as journaldt_id,".$todate." as journal_date, ".
									 " '99940001' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ".
									 " ".$StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
									 "  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup 
									  from dual ".		//FG				
									 " union   select 4 as journaldt_id,".$todate." as journal_date, ".
									 " '99950001' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ".
									 " ".$StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
										"  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup 
									 from dual";	
				}
		
		}		
				$queryjournal .= " ) as JournalDt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,'%')) ".
								" Left Join $DirSchema.CstJour As CstJour on CstJour.JournalDt_ID = JournalDt.JournalDT_ID 
									and (FinancialTemplate.Project_code is not null or FinancialTemplate.costcent_code is not null)";
								
		}	  
				  
				  

		$queryjournal= $queryjournal.  
								" where FinancialTotLabel.FinancialTot_TreeCode = $reportoption  ".
								" and if(FinancialTemplate.Project_code is not null, FinancialTemplate.Project_code = CstJour.Project_code, 1=1)
								  and if(FinancialTemplate.costcent_code is not null, FinancialTemplate.costcent_code = CstJour.Costcent_Code, 1=1)
								  and if(FinancialTemplate.dbcd is not null,JournalDt.JournalDt_DbCd = FinancialTemplate.dbcd, 1=1)	 ".
							    " and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ".
                                " and ifNull(ledger.ledger_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)							  ".
							  
							//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'))),'%') ";
			
						//echo $queryjournal;
									//exit;

		}
		else if  ( ($fromproject != 'null' || $fromcst != 'null' || $showcostcenter == 1 || $showproject == 1 ) and ($parentprjcost == 0) ){  
//xxxxxxxx
			$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 concat(ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))),'%') ";

		}
			
		
		
		    
			$queryjournal= $queryjournal." and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ";						
					
		$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, concat(Ledger.$Ledger_Name, if(ifnull(FinancialTemplate.costcent_code,'')='',if(ifnull(FinancialTemplate.project_code,'')='','',concat('-',tempproject.project_name)),concat('-',tempcostcent.costcent_name))) as $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.CstJour_Amount1), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount1, (-1)*CstJour.CstJour_Amount1))) AS AmountBase1, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
							" if(CstJour.Cst_increment is null,JournalDt_Amount2, CstJour.CstJour_Amount2), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount2, (-1)*CstJour.CstJour_Amount2))) AS AmountBase2, ".
							" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
							" FinancialTotLabel.FinancialTot_ShowResult, balanceType, ifnull(Financial_bgcolor,'#FFFFFF') as Financial_bgcolor,
							ifnull(Financial_fontcolor,'#000000') as Financial_fontcolor,ifnull(Financial_fontsize,15) as Financial_fontsize,ifnull(Financial_isContinuous,0) as Financial_isContinuous, financialtotlabel.FinancialTot_RelatedPer ".
							" From Ledger ".
							" Inner Join FinancialTemplate on (Ledger.Ledger_Number = FinancialTemplate.Ledger_Number) ".
							" left join costcent as tempcostcent on tempcostcent.Costcent_code = FinancialTemplate.Costcent_code ".
							" left join project as tempproject on tempproject.Project_Code = FinancialTemplate.Project_Code ".
							" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ";

							//--------------------------------
			$queryjournal = $queryjournal." left join (select journaldt.journaldt_id,
							journaldt.journal_date as journal_date,
							journaldt.ledger_number,
							journaldt.journaldt_dbcd,
							JournalDt_Amount1,
							JournalDt_Amount2,
							journaldt.Currency_Code,
							journal.journal_type,
							1 as acctrx_Posted,
							journaldt.Journal_BelongsToGroup as journal_BelongsToGroup,
							Cst_increment,
							cstjour.Costcent_code,
							cstjour.Project_Code,
							Cstjour_prcnt,
							Cstjour_amount1,
							Cstjour_amount2 
							from ".$DirSchema.".journal ".
							" inner join ".$DirSchema.".journaldt on journal.journal_id=journaldt.journal_id 
							left join  ".$DirSchema.".cstjour on cstjour.journaldt_id=journaldt.journaldt_id ";
				if ($projectexist >	0) {
				$queryjournal .= " inner join (SELECT DISTINCT project_code
									FROM ".$_SESSION['dbLabel'].".loginstk
									WHERE loginstk.user_account='".$_SESSION['useraccount']."' and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') 
									AND (project_code IS NOT NULL
									AND project_code != '')) q2 on q2.project_code=cstjour.project_code";							
				}
			
			if ($costcentexist >	0) {
				$queryjournal = $queryjournal."
							inner join (SELECT DISTINCT costcent_code
							FROM ".$_SESSION['dbLabel'].".loginstk
							WHERE loginstk.user_account='".$_SESSION['useraccount']."' and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') 
							AND (costcent_code IS NOT NULL
							AND costcent_code != '')) q2 on q2.costcent_code=cstjour.costcenter_code";							
				}
					$queryjournal .= " where journaldt.journal_date<='".$enddate."' ";
					if ($RowsDirCount > 1 && $k != 1)	
						$queryjournal= $queryjournal." And ( Journal.Journal_Type <> 'OP' )";
						$queryjournal .= " and if('$showstock' = '1', Journal.Journal_Type <> 'CL', 1=1) ";
					//herenad
					/* 
					$queryjournal .=" union select transdt.transdt_id as journaldt_id,transdt.trans_date as journal_date,
									transdt.ledger_number as ledger_number,transdt.transdt_dbcd as journaldt_dbcd,
									transdt.transdt_amount1 as journaldt_amount1, transdt.transdt_amount2 as journaldt_amount2,
									transdt.Currency_Code, trans_type as journal_type, 0 as acctrx_Posted, Trans_BelongsToGroup AS Journal_BelongsToGroup,
									CstJourDt_id as Cst_increment, Costcenter_Code AS Costcent_code, cstjourdt.Project_code,
									cstjourdt.CstjourDt_Per AS Cstjour_prcnt, CstJourDt_Amount1 AS Cstjour_amount1,	CstJourDt_Amount2 AS Cstjour_amount2
									from ".$DirSchema.".trans "
									" inner join ".$DirSchema.".transdt on trans.trans_id=transdt.trans_id  and trans.acctrx_Posted=0 
									left join ".$DirSchema.".cstjourdt on cstjourdt.TransDt_id=transdt.TransDt_id ";
				if ($projectexist >	0) {
				$queryjournal .= " 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 != '')) q2 on q2.project_code=cstjourdt.project_code";							
				}

				if ($costcentexist >	0) {
				$queryjournal .= " inner join (SELECT DISTINCT costcent_code
									FROM ".$_SESSION['dbLabel'].".loginstk
									WHERE loginstk.user_account='".$_SESSION['useraccount']."'
									AND (costcent_code IS NOT NULL
									AND costcent_code != '')) q2 on q2.costcent_code=cstjourdt.costcenter_code";							
				}				
					
				$queryjournal .= " where transdt.trans_date<='".$enddate."'"; */
						
				////////////////////////////////////////////////////////////////////////////////////////////////////////////////////			
				if($showstock==1) {
					
					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) {
								if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
								else $lastDate = "LAST_DAY('$y-$m-01')";
								//With Local
								$queryjournal .=" union   select 1 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
								$queryjournal .= " '99990001' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
								

								$queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,". 
												" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
												".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt, ".
												"  ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1, ".
												"  ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
												" from dual";

								$queryjournal .= " union   select 2 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
								$queryjournal .= " '99990002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
								
								$queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
												".$fromcst." AS Costcent_code, ".$fromproject." as Project_code,100  AS Cstjour_prcnt,".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1, ".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
												" from dual";
												
								//Without Local
								$queryjournal .=" union   select 1 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
								$queryjournal .= " '99980001' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',0),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
								
								$queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,". 
												" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
												".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt, ".
												"  ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1, ".
												"  ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
												" from dual";

								$queryjournal .= " union   select 2 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
								$queryjournal .= " '99980002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
								$queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
												".$fromcst." AS Costcent_code, ".$fromproject." as Project_code,100  AS Cstjour_prcnt,".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1, ".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
												" from dual";
								//RM
								$queryjournal .= " union select 3 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
												 " '99940001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
												 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
												 " from dual ".//FG
												 " union   select 4 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
												 " '99950001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
												 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
												 " from dual ";				
							}
						}
					}
					
					else {
						if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
						else $lastDate = "LAST_DAY(".$fromdate.")";
						//With Local
						$queryjournal .=" union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
						$queryjournal .= " '99990001' as ledger_number, IF(". $StockValueStart."*-1>=0 ,'C','D') as journaldt_dbcd, ";
						

						$queryjournal .= $StockValueStart." AS journaldt_amount1,".$StockValueStart." AS journaldt_amount2,".
										" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt,
										".$StockValueStart."  AS Cstjour_amount1,
										".$StockValueStart."  AS Cstjour_amount2 ".
										" from dual";

						$queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
						$queryjournal .= " '99990002' as ledger_number, IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ";
						

						$queryjournal .= $StockValueEnd." AS journaldt_amount1,".
											$StockValueEnd." AS journaldt_amount2,".
										"      '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										".$fromcst." AS Costcent_code, ".$fromproject." as Project_code,100  AS Cstjour_prcnt,
										".$StockValueEnd."  AS Cstjour_amount1,
										".$StockValueEnd."  AS Cstjour_amount2 ".
										" from dual";
						//Without Local	
						$queryjournal .=" union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
						$queryjournal .= " '99980001' as ledger_number, IF(". $StockValueStart2."*-1>=0 ,'C','D') as journaldt_dbcd, ";
						

						$queryjournal .= $StockValueStart2." AS journaldt_amount1,".$StockValueStart2." AS journaldt_amount2,".
										" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt,
										".$StockValueStart2."  AS Cstjour_amount1,
										".$StockValueStart2."  AS Cstjour_amount2 ".
										" from dual";

						$queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
						$queryjournal .= " '99980002' as ledger_number, IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ";
						

						$queryjournal .= $StockValueEnd2." AS journaldt_amount1,".
											$StockValueEnd2." AS journaldt_amount2,".
										"      '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										".$fromcst." AS Costcent_code, ".$fromproject." as Project_code,100  AS Cstjour_prcnt,
										".$StockValueEnd2."  AS Cstjour_amount1,
										".$StockValueEnd2."  AS Cstjour_amount2 ".
										" from dual";	
						//RM
						$queryjournal .= " union   select 3 as journaldt_id,".$todate." as journal_date, ".
										 " '99940001' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ".
										 " ".$StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
										 "  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
										 ".$StockValueEnd2."  AS Cstjour_amount1,	".$StockValueEnd2."  AS Cstjour_amount2 ".
										 " from dual ".		//FG				
										 " union   select 4 as journaldt_id,".$todate." as journal_date, ".
										 " '99950001' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ".
										 " ".$StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
											"  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
										".$StockValueEnd."  AS Cstjour_amount1,	".$StockValueEnd."  AS Cstjour_amount2 ".
										" from dual";						
					}
				}



			$queryjournal=$queryjournal." ) as journaldt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,'%')) ".
										// " 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 ".$_SESSION['dbLabel'].".loginstk ".
											 "		  	    where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
											 "              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 ".$_SESSION['dbLabel'].".loginstk ".
										   "			  where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
										   "              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 if(FinancialTemplate.Project_code is not null, FinancialTemplate.Project_code = CstJour.Project_code, 1=1)
								  and if(FinancialTemplate.costcent_code is not null, FinancialTemplate.costcent_code = CstJour.Costcent_Code, 1=1)
								  and if(FinancialTemplate.dbcd is not null,JournalDt.JournalDt_DbCd = FinancialTemplate.dbcd, 1=1)		".
								" and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ".
                                " and ifNull(ledger.ledger_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)	";
								//" 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) ){  					  
			//XXXXXXXXXXXXXXXXXXXXXXXX
			$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 concat(ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))),'%') ";

			}
				
			
			$queryjournal= $queryjournal." and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ";						
			
			$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, concat(Ledger.$Ledger_Name, if(ifnull(FinancialTemplate.costcent_code,'')='',if(ifnull(FinancialTemplate.project_code,'')='','',concat('-',tempproject.project_name)),concat('-',tempcostcent.costcent_name))) as $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.CstJour_Amount1), ".
								" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount1, (-1)*CstJour.CstJour_Amount1))) AS AmountBase1, ".
								" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
								" if(CstJour.Cst_increment is null,JournalDt_Amount2, CstJour.CstJour_Amount2), ".
								" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount2, (-1)*CstJour.CstJour_Amount2))) AS AmountBase2, ".
								" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
								" FinancialTotLabel.FinancialTot_ShowResult, balanceType, ifnull(Financial_bgcolor,'#FFFFFF') as Financial_bgcolor,
							ifnull(Financial_fontcolor,'#000000') as Financial_fontcolor,ifnull(Financial_fontsize,15) as Financial_fontsize,ifnull(Financial_isContinuous,0) as Financial_isContinuous, financialtotlabel.FinancialTot_RelatedPer ".
								" From Ledger ".
								" Inner Join FinancialTemplate on (Ledger.Ledger_Number Like Concat(FinancialTemplate.Ledger_Number,'%')) ".
								" left join costcent as tempcostcent on tempcostcent.Costcent_code = FinancialTemplate.Costcent_code ".
								" left join project as tempproject on tempproject.Project_Code = FinancialTemplate.Project_Code ".
								" 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.currency_code = CstJour.JournalDT_ID ";

								////////////////////////////////////////////////////////////////////
				$queryjournal = $queryjournal." left join (select journaldt.journaldt_id,journaldt.journal_date as journal_date,
							journaldt.ledger_number,journaldt.journaldt_dbcd,
							JournalDt_Amount1,
							JournalDt_Amount2,
							journaldt.Currency_Code,
							journal.journal_type,
							 1 as acctrx_Posted,
							 journaldt.Journal_BelongsToGroup as journal_BelongsToGroup,
							 Cst_increment,
							cstjour.Costcent_code,
							cstjour.Project_Code,
							Cstjour_prcnt,
							Cstjour_amount1,
							Cstjour_amount2
							from ".$DirSchema.".journal ".		
							" inner join ".$DirSchema.".journaldt on journal.journal_id=journaldt.journal_id 
								left join  ".$DirSchema.".cstjour on cstjour.journaldt_id=journaldt.journaldt_id ";
							if ($projectexist >	0) {
								$queryjournal .= " inner join (SELECT DISTINCT costcent_code FROM ".$_SESSION['dbLabel'].".loginstk	WHERE loginstk.user_account='".$_SESSION['useraccount']."' and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') 
													AND (costcent_code IS NOT NULL	AND costcent_code != '')) q2 on q2.costcent_code=cstjour.costcent_code";
							}
							if ($costcentexist >	0) {
								$queryjournal .= " inner join (SELECT DISTINCT costcent_code FROM ".$_SESSION['dbLabel'].".loginstk WHERE loginstk.user_account='".$_SESSION['useraccount']."' and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') 
															AND (costcent_code IS NOT NULL	AND costcent_code != '')) q2 on q2.costcent_code=cstjour.costcenter_code";							
							}	
					
							$queryjournal = $queryjournal."	where journaldt.journal_date<='".$enddate."'";
							if ($RowsDirCount > 1 && $k != 1)	
								$queryjournal .= " And (Journal.Journal_Type <> 'OP' )";
								$queryjournal .= " and if('$showstock' = '1', Journal.Journal_Type <> 'CL', 1=1) ";
							//herenad
							/* $queryjournal .=" union select transdt.transdt_id as journaldt_id,	transdt.trans_date as journal_date,	transdt.ledger_number as ledger_number, ".
										" transdt.transdt_dbcd as journaldt_dbcd,	transdt.transdt_amount1 as journaldt_amount1,transdt.transdt_amount2 as journaldt_amount2,
										transdt.Currency_Code,	trans_type as journal_type,	0 as acctrx_Posted,	Trans_BelongsToGroup AS Journal_BelongsToGroup,
										CstJourDt_id as Cst_increment,		Costcenter_Code AS Costcent_code,	cstjourdt.Project_code,	cstjourdt.CstjourDt_Per AS Cstjour_prcnt,
										CstJourDt_Amount1 AS Cstjour_amount1, CstJourDt_Amount2 AS Cstjour_amount2	from ".
										$DirSchema.".trans ".
										"inner join ".$DirSchema.".transdt on trans.trans_id=transdt.trans_id  and trans.acctrx_Posted=0 
										left join ".$DirSchema.".cstjourdt on cstjourdt.TransDt_id=transdt.TransDt_id ";
					if ($projectexist >	0) {
						$queryjournal .= " 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 != '')) q2 on q2.project_code=cstjourdt.project_code";							
					}
					if ($costcentexist >	0) {
						$queryjournal .= "	inner join (SELECT DISTINCT costcent_code FROM ".$_SESSION['dbLabel'].".loginstk WHERE loginstk.user_account='".$_SESSION['useraccount']."'
											AND (costcent_code IS NOT NULL	AND costcent_code != '')) q2 on q2.costcent_code=cstjourdt.costcenter_code";							
					}				
							
				$queryjournal = $queryjournal." where transdt.trans_date<='".$enddate."'"; */
							 
					
							
				////////////////////////////////////////////////////////////////////////////////////////////////////////////////////			
			if($showstock==1) {

				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) {
							if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
							else $lastDate = "LAST_DAY('$y-$m-01')";
							//With Local
							$queryjournal .= " union   select 1 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
							$queryjournal .= " '99990001' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
							

							 $queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
											  " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
											  " '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
											  ".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt, ".
											  " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1, ".
											  " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
											  " from dual";
							  
							  $queryjournal .= " union   select 2 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
							$queryjournal .= " '99990002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
							
							 $queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
											" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
											" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted,  '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
											".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt, ".
											" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1, ".
											" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
											" from dual";
							//Without Local
							$queryjournal .= " union   select 1 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
							$queryjournal .= " '99980001' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',0),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
							

							 $queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
											  " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
											  " '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
											  ".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt, ".
											  " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1, ".
											  " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
											  " from dual";
							  
							  $queryjournal .= " union   select 2 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
							$queryjournal .= " '99980002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
							

							 $queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
											" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
											" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted,  '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
											".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt, ".
											" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1, ".
											" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
											" from dual";
							//RM
							$queryjournal .= " union select 3 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
											 " '99940001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
											" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
											 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
											 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
											 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
											 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
											 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
											 " from dual ".//FG
											 " union   select 4 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
											 " '99950001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
											 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
											 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
											 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
											 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
											 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
											 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
											 " from dual ";				
						}
					}
				}
				else {
					if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
					else $lastDate = "LAST_DAY(".$fromdate.")";
					//With Local
					$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59')  as journal_date,";
					$queryjournal .= " '99990001' as ledger_number, IF(". $StockValueStart."*-1>=0 ,'C','D') as journaldt_dbcd, ";
					
					 $queryjournal .=  $StockValueStart." AS journaldt_amount1,".$StockValueStart." AS journaldt_amount2,".
									" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt,
									".$StockValueStart."  AS Cstjour_amount1, ".$StockValueStart."  AS Cstjour_amount2 ".
									" from dual";
					  
					  $queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
					$queryjournal .= " '99990002' as ledger_number, IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ";
					

					 $queryjournal .= $StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
									" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted,  '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt,
									".$StockValueEnd."  AS Cstjour_amount1,
									".$StockValueEnd."  AS Cstjour_amount2".
									" from dual";
					//Without Local
					$queryjournal .= " union   select 1 as journaldt_id, concat($fromdate,' 23:59:59') as journal_date,";
					$queryjournal .= " '99980001' as ledger_number, IF(". $StockValueStart2."*-1>=0 ,'C','D') as journaldt_dbcd, ";
					

					 $queryjournal .=  $StockValueStart2." AS journaldt_amount1,".$StockValueStart2." AS journaldt_amount2,".
									" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt,
									".$StockValueStart2."  AS Cstjour_amount1, ".$StockValueStart2."  AS Cstjour_amount2 ".
									" from dual";
					  
					  $queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
					$queryjournal .= " '99980002' as ledger_number, IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ";
					

					 $queryjournal .= $StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
									" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted,  '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt,
									".$StockValueEnd2."  AS Cstjour_amount1,
									".$StockValueEnd2."  AS Cstjour_amount2".
									" from dual";	
					//RM
					$queryjournal .= " union   select 3 as journaldt_id,".$todate." as journal_date, ".
									 " '99940001' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ".
									 " ".$StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
									 "  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
									 ".$StockValueEnd2."  AS Cstjour_amount1,	".$StockValueEnd2."  AS Cstjour_amount2 ".
									 " from dual ".		//FG				
									 " union   select 4 as journaldt_id,".$todate." as journal_date, ".
									 " '99950001' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ".
									 " ".$StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
										"  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
									".$StockValueEnd."  AS Cstjour_amount1,	".$StockValueEnd."  AS Cstjour_amount2 ".
									" from dual";					
				}
			}				

				$queryjournal=$queryjournal.' ) as journaldt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,"%")) ';

				$queryjournal=$queryjournal." 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 ".$_SESSION['dbLabel'].".loginstk ".
												 "		  	    where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
												 "              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 ".$_SESSION['dbLabel'].".loginstk ".
											   "			  where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
											   "              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, concat(Ledger.$Ledger_Name, if(ifnull(FinancialTemplate.costcent_code,'')='',if(ifnull(FinancialTemplate.project_code,'')='','',concat('-',tempproject.project_name)),concat('-',tempcostcent.costcent_name))) as $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(FinancialTemplate.Project_code is not null or FinancialTemplate.costcent_code is not null,if(JournalDt.JournalDt_DbCd='D', Cstjour_amount1, (-1)*Cstjour_amount1),if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount1, (-1)*JournalDt_Amount1))) AS AmountBase1, ".
								" Sum(ifNull(FinancialTot_Sign,1) * if(FinancialTemplate.Project_code is not null or FinancialTemplate.costcent_code is not null,if(JournalDt.JournalDt_DbCd='D', Cstjour_amount2, (-1)*Cstjour_amount2),if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount2, (-1)*JournalDt_Amount2))) AS AmountBase2, ".
								" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
								" FinancialTotLabel.FinancialTot_ShowResult, balanceType, ifnull(Financial_bgcolor,'#FFFFFF') as Financial_bgcolor,
							ifnull(Financial_fontcolor,'#000000') as Financial_fontcolor,ifnull(Financial_fontsize,15) as Financial_fontsize,ifnull(Financial_isContinuous,0) as Financial_isContinuous, financialtotlabel.FinancialTot_RelatedPer ".
								" From Ledger ".
								" Inner Join FinancialTemplate on (Ledger.Ledger_Number Like Concat(FinancialTemplate.Ledger_Number,'%')) ".
								" left join costcent as tempcostcent on tempcostcent.Costcent_code = FinancialTemplate.Costcent_code ".
								" left join project as tempproject on tempproject.Project_Code = FinancialTemplate.Project_Code ".
								" 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 Join $DirSchema.CstJour As CstJour on CstJour.JournalDT_ID = journaldt.currency_code ";
								//////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
								" left join (select journaldt.journaldt_id,journaldt.journal_date as journal_date,journaldt.ledger_number,journaldt.journaldt_dbcd,JournalDt_Amount1,JournalDt_Amount2,JournalDt.Currency_Code,
							 journal.journal_type,1 as acctrx_Posted, journaldt.Journal_BelongsToGroup from ".$DirSchema.".journal,".$DirSchema.".journaldt where journal.journal_id=journaldt.journal_id 
							  and journaldt.journal_date<='".$enddate."'";
					if ($RowsDirCount > 1 && $k != 1)	
						$queryjournal= $queryjournal." And (Journal.Journal_Type <> 'OP' ) ";
						$queryjournal .= " and if('$showstock' = '1', Journal.Journal_Type <> 'CL', 1=1) ";	
					//herenad
					/* 	$queryjournal .=	" union select transdt.transdt_id as journaldt_id,transdt.trans_date as journal_date,transdt.ledger_number as ledger_number, ".
							" transdt.transdt_dbcd as journaldt_dbcd, transdt.transdt_amount1 as journaldt_amount1,transdt.transdt_amount2 as journaldt_amount2,transdt.Currency_Code,trans_type as journal_type,0 as acctrx_Posted,
							Trans_BelongsToGroup AS Journal_BelongsToGroup from ".
							$DirSchema.".trans,".$DirSchema.".transdt where trans.trans_id=transdt.trans_id ".
							" and trans.acctrx_Posted=0 and transdt.trans_date<='".$enddate."'"; */
							
							////////////////////////////////////////////////////////////////////////////////////////////////////////////////////			
					if($showstock==1) {
						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) {
									if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
									else $lastDate = "LAST_DAY('$y-$m-01')";
									//With Local
									$queryjournal .= " union   select 1 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
								$queryjournal .= "  '99990001' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
									

									$queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
													" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
													" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup ".
													" from dual";
									
									$queryjournal .= " union   select 2 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
									$queryjournal .= " '99990002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
									
									$queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
													" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
													" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
													" from dual";
									//Without Local
									$queryjournal .= " union   select 1 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
									$queryjournal .= "  '99980001' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',0),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
									

									$queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
													" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
													" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup ".
													" from dual";
									
									$queryjournal .= " union   select 2 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
									$queryjournal .= " '99980002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
									
									$queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
													" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
													" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
													" from dual";
									//RM
									$queryjournal .= " union select 3 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
													 " '99940001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
													" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
													 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
													 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup 
													 from dual ".//FG
													 " union   select 4 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
													 " '99950001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
													 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
													 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
													 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup
													 from dual ";				
								}
							}
						}
						else {
							if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
							else $lastDate = "LAST_DAY(".$fromdate.")";	
							//With Local
							$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
						$queryjournal .= "  '99990001' as ledger_number, IF(". $StockValueStart."*-1>=0 ,'C','D') as journaldt_dbcd, ";
							

							$queryjournal .= $StockValueStart." AS journaldt_amount1,".$StockValueStart." AS journaldt_amount2,".
											" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup ".
											" from dual";
							
							$queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
							$queryjournal .= " '99990002' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ";
							
							$queryjournal .= $StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
											" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
											" from dual";
							//Without Local
							$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
							$queryjournal .= "  '99980001' as ledger_number, IF(". $StockValueStart2."*-1>=0 ,'C','D') as journaldt_dbcd, ";
							

							$queryjournal .= $StockValueStart2." AS journaldt_amount1,".$StockValueStart2." AS journaldt_amount2,".
											" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup ".
											" from dual";
							
							$queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
							$queryjournal .= " '99980002' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ";
							
							$queryjournal .= $StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
											" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
											" from dual";	
							//RM
							$queryjournal .= " union   select 3 as journaldt_id,".$todate." as journal_date, ".
											 " '99940001' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ".
											 " ".$StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
											 "  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup
											 from dual ".		//FG				
											 " union   select 4 as journaldt_id,".$todate." as journal_date, ".
											 " '99950001' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ".
											 " ".$StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
												"  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup
												from dual";						
						}
					}


						$queryjournal=$queryjournal." ) as journaldt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,'%')) ";
						$queryjournal=$queryjournal." Left Join $DirSchema.CstJour As CstJour on CstJour.JournalDT_ID = journaldt.JournalDT_ID 
													and (FinancialTemplate.Project_code is not null or FinancialTemplate.costcent_code is not null) ";
			}	  
					  
					  

			$queryjournal= $queryjournal.  
									" where FinancialTotLabel.FinancialTot_TreeCode = $reportoption  ".
									" and Ledger.Ledger_grpdet = 0 ".
									" and FinancialTemplate.Ledger_ShowDt = 1 ".
									" and if(FinancialTemplate.Project_code is not null, FinancialTemplate.Project_code = CstJour.Project_code, 1=1)
									  and if(FinancialTemplate.costcent_code is not null, FinancialTemplate.costcent_code = CstJour.Costcent_Code, 1=1) 
									  and if(FinancialTemplate.dbcd is not null,JournalDt.JournalDt_DbCd = FinancialTemplate.dbcd, 1=1)	".
									"	  	  and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ".
								  	" and ifNull(ledger.ledger_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0) ";
								  						
										  

			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) ){  					  		  
//xxxxxxxxxxxxxxxxxxx
			$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 concat(ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))),'%') ";

			}
				
			
			
			$queryjournal= $queryjournal." and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ";						
						
			$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, concat(Ledger.$Ledger_Name, if(ifnull(FinancialTemplate.costcent_code,'')='',if(ifnull(FinancialTemplate.project_code,'')='','',concat('-',tempproject.project_name)),concat('-',tempcostcent.costcent_name))) as $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.CstJour_Amount1), ".
								" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount1, (-1)*CstJour.CstJour_Amount1))) AS AmountBase1, ".
								" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
								" if(CstJour.Cst_increment is null,JournalDt_Amount2, CstJour.CstJour_Amount2), ".
								" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount2, (-1)*CstJour.CstJour_Amount2))) AS AmountBase2, ".
								" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_LevelCode, ".
								" FinancialTotLabel.FinancialTot_ShowResult, balanceType, ifnull(Financial_bgcolor,'#FFFFFF') as Financial_bgcolor,
							ifnull(Financial_fontcolor,'#000000') as Financial_fontcolor,ifnull(Financial_fontsize,15) as Financial_fontsize,ifnull(Financial_isContinuous,0) as Financial_isContinuous, financialtotlabel.FinancialTot_RelatedPer ".
								" From Ledger ".
								" Inner Join FinancialTemplate on (Ledger.Ledger_Number Like Concat(FinancialTemplate.Ledger_Number,'%')) ".
								" left join costcent as tempcostcent on tempcostcent.Costcent_code = FinancialTemplate.Costcent_code ".
								" left join project as tempproject on tempproject.Project_Code = FinancialTemplate.Project_Code ".
								" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ";
								////////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

				$queryjournal = $queryjournal." left join (
								select journaldt.journaldt_id,journaldt.journal_date as journal_date,
								journaldt.ledger_number,journaldt.journaldt_dbcd,
								JournalDt_Amount1, JournalDt_Amount2,JournalDt.Currency_Code,
								journal.journal_type,1 as acctrx_Posted,journaldt.Journal_BelongsToGroup as journal_BelongsToGroup,
								Cst_increment,cstjour.Costcent_code,cstjour.Project_Code,
								Cstjour_prcnt,Cstjour_amount1,Cstjour_amount2
							from ".$DirSchema.".journal ".		
							" inner join ".$DirSchema.".journaldt on journal.journal_id=journaldt.journal_id 
								left join  ".$DirSchema.".cstjour on cstjour.journaldt_id=journaldt.journaldt_id";
							
							if ($projectexist >	0) {
								$queryjournal .= " inner join (SELECT DISTINCT project_code FROM ".$_SESSION['dbLabel'].".loginstk WHERE loginstk.user_account='".$_SESSION['useraccount']."' and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') 
													AND (project_code IS NOT NULL AND project_code != '')) q2 on q2.project_code=cstjour.project_code";							
							}	
							if ($costcentexist >	0) {	
								$queryjournal .= "	inner join (SELECT DISTINCT costcent_code FROM ".$_SESSION['dbLabel'].".loginstk WHERE loginstk.user_account='".$_SESSION['useraccount']."' and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') 
													AND (costcent_code IS NOT NULL	AND costcent_code != '')) q2 on q2.costcent_code=cstjour.costcent_code ";
							}	
							$queryjournal .= " where journaldt.journal_date<='".$enddate."'";
					if ($RowsDirCount > 1 && $k != 1)	
						$queryjournal= $queryjournal." And (Journal.Journal_Type <> 'OP' )";
						$queryjournal .= " and if('$showstock' = '1', Journal.Journal_Type <> 'CL', 1=1)  ";
						//herenad
						/* $queryjournal .=	" union select transdt.transdt_id as journaldt_id, transdt.trans_date as journal_date, transdt.ledger_number as ledger_number, ".
											" transdt.transdt_dbcd as journaldt_dbcd, transdt.transdt_amount1 as journaldt_amount1, transdt.transdt_amount2 as journaldt_amount2,
											transdt.Currency_Code, trans_type as journal_type, 0 as acctrx_Posted, Trans_BelongsToGroup AS Journal_BelongsToGroup,
											CstJourDt_id as Cst_increment, Costcenter_Code AS Costcent_code, cstjourdt.Project_code,
											cstjourdt.CstjourDt_Per AS Cstjour_prcnt, CstJourDt_Amount1 AS Cstjour_amount1, CstJourDt_Amount2 AS Cstjour_amount2
											from ".$DirSchema.".trans ".
											" inner join ".$DirSchema.".transdt on trans.trans_id=transdt.trans_id  and trans.acctrx_Posted=0 
											left join ".$DirSchema.".cstjourdt on cstjourdt.TransDt_id=transdt.TransDt_id ";
					if ($projectexist >	0) {
						$queryjournal .= " 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 != '')) q2 on q2.project_code=cstjourdt.project_code";							
					}
					if ($costcentexist >	0) {
						$queryjournal .= " inner join (SELECT DISTINCT costcent_code FROM ".$_SESSION['dbLabel'].".loginstk	WHERE loginstk.user_account='".$_SESSION['useraccount']."'
										AND (costcent_code IS NOT NULL AND costcent_code != '')) q2 on q2.costcent_code=cstjourdt.costcenter_code";							
					}				
							
				$queryjournal .= " where transdt.trans_date<='".$enddate."'"; */
							
				////////////////////////////////////////////////////////////////////////////////////////////////////////////////////			
		if($showstock==1) {

			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) {
						if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
						else $lastDate = "LAST_DAY('$y-$m-01')";
						//With Local
						$queryjournal .= " union   select 1 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
						$queryjournal .= " '99990001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
						

						 $queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									    " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
										" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt, ".
										" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,".
										" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2  ".
										" from dual";
						  
						  $queryjournal .= " union   select 2 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
						$queryjournal .= " '99990002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
						

						 $queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									    " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
										"'$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										".$fromcst." AS Costcent_code,".$fromproject." as Project_code,100  AS Cstjour_prcnt, ".
										" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,".
										" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2".
										" from dual";
						//Without Local
						$queryjournal .= " union   select 1 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
						$queryjournal .= " '99980001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',0),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
						

						 $queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									    " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
										" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt, ".
										" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,".
										" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2  ".
										" from dual";
						  
						  $queryjournal .= " union   select 2 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
							$queryjournal .= " '99980002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
						

						 $queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									    " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
										"'$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										".$fromcst." AS Costcent_code,".$fromproject." as Project_code,100  AS Cstjour_prcnt, ".
										" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,".
										" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2".
										" from dual";	
						//RM
						$queryjournal .= " union select 3 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
										 " '99940001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
										" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
										 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
										 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
										 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
										 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
										 " from dual ".//FG
										 " union   select 4 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
										 " '99950001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
										 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
										 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
										 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
										 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
										 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
										 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
										 " from dual ";			
					}
				}
			} 				
			
			else {
				if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
				else $lastDate = "LAST_DAY(".$fromdate.")";
					//With Local
					$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
				 $queryjournal .= " '99990001' as ledger_number,IF(". $StockValueStart."*-1>=0 ,'C','D') as journaldt_dbcd, ";
					

					 $queryjournal .= $StockValueStart." AS journaldt_amount1,".$StockValueStart." AS journaldt_amount2,".
									" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt,
									".$StockValueStart."  AS Cstjour_amount1,".$StockValueStart."  AS Cstjour_amount2  ".
									" from dual";
					  
					  $queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
					$queryjournal .= " '99990002' as ledger_number, IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ";
					

					 $queryjournal .= $StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
									"'$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code,".$fromproject." as Project_code,100  AS Cstjour_prcnt,
									".$StockValueEnd."  AS Cstjour_amount1,".$StockValueEnd."  AS Cstjour_amount2".
									" from dual";
					//Without Local
					$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
				 $queryjournal .= " '99980001' as ledger_number,IF(". $StockValueStart2."*-1>=0 ,'C','D') as journaldt_dbcd, ";
					

					 $queryjournal .= $StockValueStart2." AS journaldt_amount1,".$StockValueStart2." AS journaldt_amount2,".
									" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code, ".$fromproject." as Project_code, 100  AS Cstjour_prcnt,
									".$StockValueStart2."  AS Cstjour_amount1,".$StockValueStart2."  AS Cstjour_amount2  ".
									" from dual";
					  
					  $queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
					$queryjournal .= " '99980002' as ledger_number, IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ";
					

					 $queryjournal .= $StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
									"'$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code,".$fromproject." as Project_code,100  AS Cstjour_prcnt,
									".$StockValueEnd2."  AS Cstjour_amount1,".$StockValueEnd2."  AS Cstjour_amount2".
									" from dual";	
					//RM
					$queryjournal .= " union   select 3 as journaldt_id,".$todate." as journal_date, ".
									 " '99940001' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ".
									 " ".$StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
									 "  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
									 ".$StockValueEnd2."  AS Cstjour_amount1,	".$StockValueEnd2."  AS Cstjour_amount2 ".
									 " from dual ".		//FG				
									 " union   select 4 as journaldt_id,".$todate." as journal_date, ".
									 " '99950001' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ".
									 " ".$StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
										"  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
									".$StockValueEnd."  AS Cstjour_amount1,	".$StockValueEnd."  AS Cstjour_amount2 ".
									" from dual";							
				}
			}
				
				$queryjournal .= ' ) as journaldt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,"%")) ';

				////////////////////////////////////////////////////////////////////////
				$queryjournal=$queryjournal." 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 ".$_SESSION['dbLabel'].".loginstk ".
												 "		  	    where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
												 "              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 ".$_SESSION['dbLabel'].".loginstk ".
											   "			  where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
											   "              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 ".
										" and if(FinancialTemplate.Project_code is not null, FinancialTemplate.Project_code = CstJour.Project_code, 1=1)
										  and if(FinancialTemplate.costcent_code is not null, FinancialTemplate.costcent_code = CstJour.Costcent_Code, 1=1) 
										  and if(FinancialTemplate.dbcd is not null,JournalDt.JournalDt_DbCd = FinancialTemplate.dbcd, 1=1) ".
	  									"		and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ".
                                  		" and ifNull(ledger.ledger_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)											  ";
										
											  
						  
				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) ){
//xxxxxxxxx
					$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 concat(ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))),'%') ";
				}
				
				
				$queryjournal= $queryjournal." and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ";						

				$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(PrvBalanceBase1) as PrvBalanceBase1, SUM(PrvBalanceBase2) as PrvBalanceBase2, SUM(BalanceBase1) as BalanceBase1, SUM(BalanceBase2) as BalanceBase2, a.FinancialTot_LevelCode, a.FinancialTot_ShowResult, '' as balanceType,
								ifnull(a.FinancialTot_bgcolor,'#FFFFFF') as Financial_bgcolor, ifnull(a.FinancialTot_fontcolor,'#000000') as Financial_fontcolor, 
								ifnull(a.FinancialTot_fontsize,15) as Financial_fontsize, 0 as Financial_isContinuous, a.FinancialTot_RelatedPer
							 ";

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(".getMonth($m).$y."Base1) as ".getMonth($m).$y."Base1 ".
										  ", SUM(".getMonth($m).$y."Base2) as ".getMonth($m).$y."Base2 ";
			$queryjournal .= " ,sum(".getMonth($m).$y."PreBase1) as ".getMonth($m).$y."PreBase1 , sum(".getMonth($m).$y."PreBase2) as ".getMonth($m).$y."PreBase2 ";	
		}

	}
}

$queryjournal = $queryjournal.							 
		 " From FinancialTotLabel As a ".
		 " Left Join FinancialTotLabel as b on a.FinancialTot_RelatedCode=b.FinancialTot_Code ".
		 " Left Join ( 
			select Ledger_Number, Ledger_Name, Ledger_GrpDet, FinancialTot_Label, Financial_Order, FinancialTot_Code, MaxMon, MaxYear, ProjectCode, CostcentCode, ".
		 " SUM(if(date_format(Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(Journal_date,'%Y-%m-%d')), AmountBase1, 0)) AS PrvBalanceBase1, ".
		 " SUM(if(date_format(Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(Journal_date,'%Y-%m-%d')), AmountBase2, 0)) AS PrvBalanceBase2, ".
		 " if( Ledger_Number = '99990001' or Ledger_Number = '99980001', SUM(if(date_format(Journal_date,'%Y-%m') = date_format(". $fromdate.",'%Y-%m'),AmountBase1,0)),
			if(Ledger_Number = '99990002' or Ledger_Number = '99980002', SUM(if(date_format(Journal_date,'%Y-%m') = date_format(". $todate.",'%Y-%m'),AmountBase1,0)),
			SUM(if(date_format(Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Journal_date,'%Y-%m-%d')) and date_format(Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Journal_date,'%Y-%m-%d')), 
			AmountBase1, 0)))) AS BalanceBase1, ".
		 " if( Ledger_Number = '99990001' or Ledger_Number = '99980001',SUM(if(date_format(Journal_date,'%Y-%m') = date_format(". $fromdate.",'%Y-%m'),AmountBase2,0)),
			if(Ledger_Number = '99990002' or Ledger_Number = '99980002', SUM(if(date_format(Journal_date,'%Y-%m') = date_format(". $todate.",'%Y-%m'),AmountBase2,0)),
			SUM(if(date_format(Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Journal_date,'%Y-%m-%d')) and date_format(Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Journal_date,'%Y-%m-%d')), 
			AmountBase2, 0)))) AS BalanceBase2, ";
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(Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Journal_date,'%Y-%m-%d')) and date_format(Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Journal_date,'%Y-%m-%d')), if((MaxMon = '".$m."') and (MaxYear = '".$y."'), AmountBase1, 0), 0)) AS ".getMonth($m).$y."Base1 ".
										  ", SUM(if(date_format(Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Journal_date,'%Y-%m-%d')) and date_format(Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Journal_date,'%Y-%m-%d')), if((MaxMon = '".$m."') and (MaxYear = '".$y."'), AmountBase2, 0), 0)) AS ".getMonth($m).$y."Base2, ";
			if($m == 1)							  
			$queryjournal .= " 0 as ".getMonth($m).$y."PreBase1,  0 as ".getMonth($m).$y."PreBase2, ";
			else 
			$queryjournal .= " SUM(if(Financial_isContinuous = 1 and date_format(Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Journal_date,'%Y-%m-%d')) and date_format(Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Journal_date,'%Y-%m-%d')), if((MaxMon <= '".($m-1)."') and (MaxYear = '".$y."'), AmountBase1, 0), 0)) as  ".getMonth($m).$y."PreBase1, 
							SUM(if(Financial_isContinuous = 1 and date_format(Journal_date,'%Y-%m-%d') >= ifNull(". $fromdate.",date_format(Journal_date,'%Y-%m-%d')) and date_format(Journal_date,'%Y-%m-%d') <= ifNull(". $todate.",date_format(Journal_date,'%Y-%m-%d')), if((MaxMon <= '".($m-1)."') and (MaxYear = '".$y."'), AmountBase2, 0), 0)) AS ".getMonth($m).$y."PreBase2,";
				
		}

	}
}							 
$queryjournal = $queryjournal." MasterRecord, FinancialTot_Level, FinancialTot_RelatedCode, FinancialTot_LevelCode, balanceType,
								Financial_bgcolor,Financial_fontcolor, Financial_fontsize,  Financial_isContinuous, FinancialTot_RelatedPer
								 from (
							 ";
$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 = $RowsDir[0];	
	
	 
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die('   a15'    .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, concat(Ledger.$Ledger_Name, if(ifnull(FinancialTemplate.costcent_code,'')='',if(ifnull(FinancialTemplate.project_code,'')='','',concat('-',tempproject.project_name)),concat('-',tempcostcent.Costcent_name))) as $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.CstJour_Amount1), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount1, (-1)*CstJour.CstJour_Amount1))) AS AmountBase1, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(JournalDt.JournalDt_DbCd='D', ".
							" if(CstJour.Cst_increment is null,JournalDt_Amount2, CstJour.CstJour_Amount2), ".
							" if(CstJour.Cst_increment is null,(-1)*JournalDt_Amount2, (-1)*CstJour.CstJour_Amount2))) AS AmountBase2, ".
							" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_RelatedCode , FinancialTotLabel.FinancialTot_LevelCode, balanceType, ".
							" ifnull(Financial_bgcolor,'#FFFFFF') as Financial_bgcolor,
							ifnull(Financial_fontcolor,'#000000') as Financial_fontcolor,ifnull(Financial_fontsize,15) as Financial_fontsize,ifnull(Financial_isContinuous,0) as Financial_isContinuous, financialtotlabel.FinancialTot_RelatedPer ".
							" From Ledger ".
							" Inner Join FinancialTemplate on (Ledger.Ledger_Number = FinancialTemplate.Ledger_Number) ".
							" Inner Join FinancialTotLabel on FinancialTemplate.FinancialTot_Code = FinancialTotLabel.FinancialTot_Code ".
							" left join costcent as tempcostcent on tempcostcent.Costcent_code = FinancialTemplate.Costcent_code ".
							" left join project as tempproject on tempproject.Project_Code = FinancialTemplate.Project_Code ";
					//		" Left Join Project on CstJour.Project_Code = Project.Project_Code ".
					//	" Left Join Costcent on CstJour.Costcent_Code = Costcent.Costcent_Code ";
					////////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

			$queryjournal = $queryjournal.				" left join (
								select journaldt.journaldt_id,journaldt.journal_date as journal_date,
								journaldt.ledger_number,journaldt.journaldt_dbcd,
								JournalDt_Amount1,
								JournalDt_Amount2,
								JournalDt.Currency_Code,
								journal.journal_type,
								1 as acctrx_Posted,
								journaldt.Journal_BelongsToGroup as journal_BelongsToGroup,
								Cst_increment,
								cstjour.Costcent_code,
								cstjour.Project_Code,
								Cstjour_prcnt,
								Cstjour_amount1,
								Cstjour_amount2
							from ".$DirSchema.".journal ".		
							" inner join ".$DirSchema.".journaldt on journal.journal_id=journaldt.journal_id 
								left join  ".$DirSchema.".cstjour on cstjour.journaldt_id=journaldt.journaldt_id";
							if ($projectexist >	0) {
								$queryjournal .= " inner join (SELECT DISTINCT project_code FROM ".$_SESSION['dbLabel'].".loginstk 	WHERE loginstk.user_account='".$_SESSION['useraccount']."' and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') 
															AND (project_code IS NOT NULL	AND project_code != '')) q2 on q2.project_code=cstjour.project_code";							
							}
							if ($costcentexist >	0) {
								$queryjournal .= "
									inner join (SELECT DISTINCT costcent_code 	FROM ".$_SESSION['dbLabel'].".loginstk	WHERE loginstk.user_account='".$_SESSION['useraccount']."' and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') 
									AND (costcent_code IS NOT NULL	AND costcent_code != '')) q2 on q2.costcent_code=cstjour.costcenter_code";							
							}
							$queryjournal = $queryjournal."
								where journaldt.journal_date<='".$enddate."'";
							
						if ($RowsDirCount > 1 && $k != 1)	
							$queryjournal .= " And (Journal.Journal_Type <> 'OP' ) ";
							$queryjournal .= " and if('$showstock' = '1', Journal.Journal_Type <> 'CL', 1=1) ";	
							//herenad	
							/* $queryjournal .= " union select transdt.transdt_id as journaldt_id,	transdt.trans_date as journal_date,	transdt.ledger_number as ledger_number, ".
										" transdt.transdt_dbcd as journaldt_dbcd,
										transdt.transdt_amount1 as journaldt_amount1,
										transdt.transdt_amount2 as journaldt_amount2,
										transdt.Currency_Code,
										trans_type as journal_type,
										0 as acctrx_Posted,
										Trans_BelongsToGroup AS Journal_BelongsToGroup,
										CstJourDt_id as Cst_increment,
										Costcenter_Code AS Costcent_code,
										cstjourdt.Project_code,
										cstjourdt.CstjourDt_Per AS Cstjour_prcnt,
										CstJourDt_Amount1 AS Cstjour_amount1,
										CstJourDt_Amount2 AS Cstjour_amount2
										from ".
										$DirSchema.".trans ".
										"inner join ".$DirSchema.".transdt on trans.trans_id=transdt.trans_id  and trans.acctrx_Posted=0 
										left join ".$DirSchema.".cstjourdt on cstjourdt.TransDt_id=transdt.TransDt_id ";
					if ($projectexist >	0) {
						$queryjournal .= " 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 != '')) q2 on q2.project_code=cstjourdt.project_code";							
					}
					if ($costcentexist >	0) {
						$queryjournal .= "
							inner join (SELECT DISTINCT costcent_code 	FROM ".$_SESSION['dbLabel'].".loginstk	WHERE loginstk.user_account='".$_SESSION['useraccount']."'
							AND (costcent_code IS NOT NULL	AND costcent_code != '')) q2 on q2.costcent_code=cstjourdt.costcenter_code";							
					}				
							
				$queryjournal = $queryjournal." where transdt.trans_date<='".$enddate."'"; */
							
				////////////////////////////////////////////////////////////////////////////////////////////////////////////////////			
		if($showstock==1) {
		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) {
					if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
					else $lastDate = "LAST_DAY('$y-$m-01')";
					//With Local
					$queryjournal .= " union   select 1 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
				$queryjournal .= " '99990001' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."',  '".$PProject."', '".$PCostCent."', ".$itemprint.",1,'$FI_BelongsToGrp',$showloan),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
					
					$queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1, ".
									" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)AS journaldt_amount2,".
									" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code,".$fromproject." as Project_code, 100  AS Cstjour_prcnt, ".
									" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1, ".
									" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2  ".
									" from dual ";
						
					$queryjournal .= " union   select 2 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
					$queryjournal .= "     '99990002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
					

					$queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
									" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
									" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,".
									" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2".
									" from dual";
					//Without Local
					$queryjournal .= " union   select 1 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
					$queryjournal .= " '99980001' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', ".$itemprint.",0,'$FI_BelongsToGrp',$showloan),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
					
					$queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1, ".
									" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)AS journaldt_amount2,".
									" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code,".$fromproject." as Project_code, 100  AS Cstjour_prcnt, ".
									" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1, ".
									" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2  ".
									" from dual ";
						
					$queryjournal .= " union   select 2 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date,";
					$queryjournal .= "     '99980002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
					

					$queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
									" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
									" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,".
									" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2".
									" from dual";	
					//RM
					$queryjournal .= " union select 3 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
									 " '99940001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
									" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
									 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
									 " from dual ".//FG
									 " union   select 4 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
									 " '99950001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
									 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
									 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt, ".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount1,	".
									 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS Cstjour_amount2 ".
									 " from dual ";			
				}
			}
		}
				
			else {	
			if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
			else $lastDate = "LAST_DAY(".$fromdate.")";
				//With Local
				$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
				$queryjournal .= " '99990001' as ledger_number, IF(". $StockValueStart."*-1>=0 ,'C','D') as journaldt_dbcd, ";
				
				$queryjournal .= $StockValueStart." AS journaldt_amount1,".$StockValueStart." AS journaldt_amount2,".
								" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
								".$fromcst." AS Costcent_code,".$fromproject." as Project_code, 100  AS Cstjour_prcnt,
								".$StockValueStart."  AS Cstjour_amount1, ".$StockValueStart."  AS Cstjour_amount2  ".
								" from dual ";
					
				$queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
				$queryjournal .= "     '99990002' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ";
				

				$queryjournal .= $StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
								" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
								".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
								".$StockValueEnd."  AS Cstjour_amount1,".$StockValueEnd."  AS Cstjour_amount2".
								" from dual";
				//Without Local
				$queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
				$queryjournal .= " '99980001' as ledger_number, IF(". $StockValueStart2."*-1>=0 ,'C','D') as journaldt_dbcd, ";
				
				$queryjournal .= $StockValueStart2." AS journaldt_amount1,".$StockValueStart2." AS journaldt_amount2,".
								" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
								".$fromcst." AS Costcent_code,".$fromproject." as Project_code, 100  AS Cstjour_prcnt,
								".$StockValueStart2."  AS Cstjour_amount1, ".$StockValueStart2."  AS Cstjour_amount2  ".
								" from dual ";
					
				$queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
				$queryjournal .= "     '99980002' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ";
				

				$queryjournal .= $StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
								" '$curr' AS Currency_Code, 'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
								".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
								".$StockValueEnd2."  AS Cstjour_amount1,".$StockValueEnd2."  AS Cstjour_amount2".
								" from dual";
				//RM
				$queryjournal .= " union   select 3 as journaldt_id,".$todate." as journal_date, ".
								 " '99940001' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ".
								 " ".$StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
								 "  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
								 ".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
								 ".$StockValueEnd2."  AS Cstjour_amount1,	".$StockValueEnd2."  AS Cstjour_amount2 ".
								 " from dual ".		//FG				
								 " union   select 4 as journaldt_id,".$todate." as journal_date, ".
								 " '99950001' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ".
								 " ".$StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
									"  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup, null as Cst_increment,
								".$fromcst." AS Costcent_code,".$fromproject." as Project_code,	100  AS Cstjour_prcnt,
								".$StockValueEnd."  AS Cstjour_amount1,	".$StockValueEnd."  AS Cstjour_amount2 ".
								" from dual";				
			}
		}
				$queryjournal=$queryjournal.' ) as journaldt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,"%")) ';
				$queryjournal=$queryjournal." 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 ".$_SESSION['dbLabel'].".loginstk ".
											 "		  	    where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
											 "              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 ".$_SESSION['dbLabel'].".loginstk ".
										   "			  where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
										   "              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, concat(Ledger.$Ledger_Name, if(ifnull(FinancialTemplate.costcent_code,'')='',if(ifnull(FinancialTemplate.project_code,'')='','',concat('-',tempproject.project_name)),concat('-',tempcostcent.Costcent_name))) as $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(FinancialTemplate.Project_code is not null or FinancialTemplate.costcent_code is not null,if(JournalDt.JournalDt_DbCd='D', Cstjour_amount1, (-1)*Cstjour_amount1),if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount1, (-1)*JournalDt_Amount1))) AS AmountBase1, ".
							" Sum(ifNull(FinancialTot_Sign,1) * if(FinancialTemplate.Project_code is not null or FinancialTemplate.costcent_code is not null,if(JournalDt.JournalDt_DbCd='D', Cstjour_amount2, (-1)*Cstjour_amount2),if(JournalDt.JournalDt_DbCd='D', JournalDt_Amount2, (-1)*JournalDt_Amount2))) AS AmountBase2, ".
							" 1 As MasterRecord, FinancialTotLabel.FinancialTot_Level, FinancialTotLabel.FinancialTot_RelatedCode, FinancialTotLabel.FinancialTot_LevelCode, balanceType, ".
							" ifnull(Financial_bgcolor,'#FFFFFF') as Financial_bgcolor,
							ifnull(Financial_fontcolor,'#000000') as Financial_fontcolor,ifnull(Financial_fontsize,15) as Financial_fontsize,ifnull(Financial_isContinuous,0) as Financial_isContinuous, financialtotlabel.FinancialTot_RelatedPer ".
							" From Ledger ".
							" Inner Join FinancialTemplate on (Ledger.Ledger_Number = FinancialTemplate.Ledger_Number) ".
							" left join costcent as tempcostcent on tempcostcent.Costcent_code = FinancialTemplate.Costcent_code ".
							" left join project as tempproject on tempproject.Project_Code = FinancialTemplate.Project_Code ".
							" 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 Join $DirSchema.CstJour As CstJour on CstJour.JournalDT_ID = journaldt.currency_code ";
							//////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
							" left join (select journaldt.journaldt_id,journaldt.journal_date as journal_date,journaldt.ledger_number,journaldt.journaldt_dbcd,JournalDt_Amount1,JournalDt_Amount2,JournalDt.Currency_Code,
							journal.journal_type,1 as acctrx_Posted, journaldt.Journal_BelongsToGroup from ".$DirSchema.".journal,".$DirSchema.".journaldt where journal.journal_id=journaldt.journal_id 
							 and journaldt.journal_date<='".$enddate."'";
					$queryjournal .= " and if('$showstock' = '1', Journal.Journal_Type <> 'CL', 1=1) ";			 
				//herenad			 
				/* $queryjournal .=	" union select transdt.transdt_id as journaldt_id,transdt.trans_date as journal_date,transdt.ledger_number as ledger_number, ".
						   " transdt.transdt_dbcd as journaldt_dbcd, transdt.transdt_amount1 as journaldt_amount1,transdt.transdt_amount2 as journaldt_amount2,transdt.Currency_Code,trans_type as journal_type,0 as acctrx_Posted, 
							Trans_BelongsToGroup AS Journal_BelongsToGroup from ".
						   $DirSchema.".trans,".$DirSchema.".transdt where trans.trans_id=transdt.trans_id ".
						   " and trans.acctrx_Posted=0 and transdt.trans_date<='".$enddate."'"; */
						   
						   ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////			
				if($showstock==1) {
					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) {	
							if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
							else $lastDate = "LAST_DAY('$y-$m-01')";
							//With Local
								$queryjournal .= " union   select 1 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
							   $queryjournal .= " '99990001' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
							   

							   $queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												" '$curr' AS Currency_Code, 'ST' AS journal_type,  1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
												" from dual";
							   
							   $queryjournal .= " union   select 2 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
							   $queryjournal .= " '99990002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
							   

							   $queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												" '$curr' AS Currency_Code,  'ST' AS journal_type,   1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
												" from dual";
								//Without Local
								$queryjournal .= " union   select 1 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
								$queryjournal .= " '99980001' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)*-1>=0 ,'C','D') as journaldt_dbcd, ";
							   

							   $queryjournal .= " ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												" ifNull(GetStockValueCostMethod(concat(DATE_SUB('$y-$m-01', INTERVAL 1 DAY),' 23:59:59') , '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												" '$curr' AS Currency_Code, 'ST' AS journal_type,  1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
												" from dual";
							   
							   $queryjournal .= " union   select 2 as journaldt_id,concat($lastDate,' 23:59:59') as journal_date,";
							    $queryjournal .= " '99980002' as ledger_number, IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ";
							   

							   $queryjournal .= " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												" '$curr' AS Currency_Code,  'ST' AS journal_type,   1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
												" from dual";	
								//RM
								$queryjournal .= " union select 3 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
												 " '99940001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
												" ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',0,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup
												 from dual ".//FG
												 " union   select 4 as journaldt_id, concat($lastDate,' 23:59:59') as journal_date, ".
												 " '99950001' as ledger_number,IF(ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0)>=0 ,'C','D') as journaldt_dbcd, ".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount1,".
												 " ifNull(GetStockValueCostMethod(concat($lastDate,' 23:59:59'), '".$curr."', '".$PProject."', '".$PCostCent."', '".$itemprint."',1,'$FI_BelongsToGrp',$showloan),0) AS journaldt_amount2,".
												 " '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup
												 from dual ";				
							}
						}
					}						

					 else {	 
					if($vTodate == $y."-".$m) $lastDate = "'".$vTodate."-".$vDayTo."'"; 
					else $lastDate = "LAST_DAY(".$fromdate.")";					 
							//With Local
						   $queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
						 $queryjournal .= " '99990001' as ledger_number, IF(". $StockValueStart."*-1>=0 ,'C','D') as journaldt_dbcd, ";
						   

						   $queryjournal .= $StockValueStart." AS journaldt_amount1,".$StockValueStart." AS journaldt_amount2,".
											" '$curr' AS Currency_Code, 'ST' AS journal_type,  1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
										    " from dual";
						   
						   $queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
						   $queryjournal .= " '99990002' as ledger_number, IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ";
						  

						   $queryjournal .= $StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
											" '$curr' AS Currency_Code,  'ST' AS journal_type,   1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
										    " from dual";
							//Without Local
						   $queryjournal .= " union   select 1 as journaldt_id,concat($fromdate,' 23:59:59') as journal_date,";
						   $queryjournal .= " '99980001' as ledger_number, IF(". $StockValueStart2."*-1>=0 ,'C','D') as journaldt_dbcd, ";
						   

						   $queryjournal .= $StockValueStart2." AS journaldt_amount1,".$StockValueStart2." AS journaldt_amount2,".
											" '$curr' AS Currency_Code, 'ST' AS journal_type,  1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
										    " from dual";
						   
						   $queryjournal .= " union   select 2 as journaldt_id,".$todate." as journal_date,";
						    $queryjournal .= " '99980002' as ledger_number, IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ";
						  

						   $queryjournal .= $StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
											" '$curr' AS Currency_Code,  'ST' AS journal_type,   1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup".
										    " from dual";
							//RM
							$queryjournal .= " union   select 3 as journaldt_id,".$todate." as journal_date, ".
											 " '99940001' as ledger_number,"."     IF(". $StockValueEnd2.">=0 ,'C','D') as journaldt_dbcd, ".
											 " ".$StockValueEnd2." AS journaldt_amount1,".$StockValueEnd2." AS journaldt_amount2,".
											 "  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup
											 from dual ".		//FG				
											 " union   select 4 as journaldt_id,".$todate." as journal_date, ".
											 " '99950001' as ledger_number,"."     IF(". $StockValueEnd.">=0 ,'C','D') as journaldt_dbcd, ".
											 " ".$StockValueEnd." AS journaldt_amount1,".$StockValueEnd." AS journaldt_amount2,".
												"  '$curr' AS currency_code,'ST' AS journal_type, 1 AS acctrx_Posted, '$FI_BelongsToGrp' AS journal_BelongsToGroup
												from dual";					
					 }
				}


					   $queryjournal=$queryjournal." ) as journaldt On (JournalDt.Ledger_Number Like concat(Ledger.ledger_number,'%')) ";
					   $queryjournal=$queryjournal." Left Join $DirSchema.CstJour As CstJour on CstJour.JournalDT_ID = journaldt.JournalDT_ID 
										and (FinancialTemplate.Project_code is not null or FinancialTemplate.costcent_code is not null) ";
										
					   ////////////////////////////
		}	  
				  
				  

		$queryjournal= $queryjournal.  
								" where FinancialTotLabel.FinancialTot_TreeCode = $reportoption  ".
								" and if(FinancialTemplate.Project_code is not null, FinancialTemplate.Project_code = CstJour.Project_code, 1=1)
								  and if(FinancialTemplate.costcent_code is not null, FinancialTemplate.costcent_code = CstJour.Costcent_Code, 1=1) 
								  and if(FinancialTemplate.dbcd is not null,JournalDt.JournalDt_DbCd = FinancialTemplate.dbcd, 1=1) ".
								"	  	  and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ".
                                " and ifNull(ledger.ledger_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0) ";
								//" 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) ){
//xxxxx
			$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 concat(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 QQ 
					 group by FinancialTot_Label, FinancialTot_Code, ProjectCode, CostcentCode, ledger_name
					 having (if(balanceType=1,(BalanceBase1)>0, if(balanceType=2,(BalanceBase1)<0,1=1)))
					) 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,'%')) ";


$queryjournal= $queryjournal." 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)) and (if(balanceType=1,BalanceBase1>0, if(balanceType=2,BalanceBase1<0,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();
$PreAmountByMonth  = Array();

$ShowResult = 0;


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

if($showper == 1) {
	$PerArr = array();
	$resultjournal=mysql_query($queryjournal,$connection) or die('    a16'    .mysql_error());
	while($rowsjournal=mysql_fetch_row($resultjournal)){
		if($rowsjournal[0] == ''){
			if ($curr == $Base1) $PerArr[$rowsjournal[3]] = $rowsjournal[12];
			else $PerArr[$rowsjournal[3]] = $rowsjournal[13];
			if ($monthdist == 1 ) {
				if ($curr == $Base1)  $i = 22; else $i = 23;
				
				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) {
						$PerArr[$rowsjournal[3].getMonth($m).$y] = $rowsjournal[$i];								
						
						$i = $i + 2;
					}

				}
			}
		}
	}
}

if ($incomebycst == 0 && $incomebyprj == 0) {
	$resultjournal=mysql_query($queryjournal,$connection) or die('   a17'    .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'  bgcolor='$rowsjournal[17]'>"; 
			echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>&nbsp;</td>";
			echo "<td align='left' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'><b>".$rowsjournal[4]."</b></td>";
				
			if ($showprevbal == 1) {
				echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". format_currency($PrevBalance  , $Decimal) ."</td>";
				echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". format_currency($PeriodBalance, $Decimal) ."</td>";
				echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". format_currency($NetBalance   , $Decimal) ."</td>";
			} else {
				//echo "<td align='right' valign='center'>&nbsp;</td>";
				echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". format_currency($PeriodBalance, $Decimal) ."</td>";
				//echo "<td align='right' valign='center'>&nbsp;</td>";
			}
			if($showper == 1){
				$per = $PeriodBalance*100/abs($PerArr[$rowsjournal[21]]);
				echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:12px !important;'>  ". number_format($per, $Decimal) ." %</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 = 22; else $i = 23;
				
				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='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". format_currency($rowsjournal[$i], $Decimal) ."</td>";
						if($showper == 1){
							$per = $rowsjournal[$i]*100/abs($PerArr[$rowsjournal[21].getMonth($m).$y]);
							echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:12px !important;'>". number_format($per, $Decimal) ."%</td>";
						}
						// If Show Result Is True
						if ($rowsjournal[15] == 1) 
							$MonthlyBalance[$i] = $rowsjournal[$i]; 
						
								
						$i = $i + 2;
					}

				}
			}
				
			echo "</tr>";
			
				
			echo "<tr>"; 
			if ($showprevbal == 1) echo "<td colspan='5'>&nbsp;</td>";
			echo "<td colspan='3'>&nbsp;</td>";
			echo "</tr>"; 
			
			
		} 
		else {
			if($prtgrpheader == 1){
				if($showledgertype!=-1) {
					$tmpgrpclass = $rowsjournal[0];
					if ($rowsjournal[2] == 1){
						$classname = 'group';
						$grpclass = $rowsjournal[0];
						echo "<tr class='$classname' height='20' bgcolor='$rowsjournal[17]'>"; 
						//echo 'prj='.$rowsjournal[6].' cet= '.$rowsjournal[7];
						
						
						if ($rowsjournal[6] == '' && $rowsjournal[7] == '') {
							if($exp ==1)
								echo "<td align='left' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". $rowsjournal[0] ."</td>";
							else{
								if($showledgernbr == 1)
								echo "<td align='left' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>
								<a href='#' class='toggler' data-grp-class='$rowsjournal[0]' style='text-decoration:none; color: inherit;'> ". $rowsjournal[0] ."</a></td>";
								else
									echo "<td align='left' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". $rowsjournal[0] ."</td>";
							}
							echo "<td align='left' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". $rowsjournal[1] ."</td>";
						} else {
							echo "<td align='left' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". $rowsjournal[6] ."</td>";
							echo "<td align='left' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". $rowsjournal[7] ."</td>";
						}	

						if ($showprevbal == 1) {
							echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". format_currency($PrevBalance  , $Decimal) ."</td>";
							echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". format_currency($PeriodBalance, $Decimal) ."</td>";
							echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". format_currency($NetBalance   , $Decimal) ."</td>";	
						} else {
							//echo "<td align='right' valign='top' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>&nbsp;</td>";
							echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". format_currency($PeriodBalance, $Decimal) ."</td>";
							//echo "<td align='right' valign='top' >&nbsp;</td>";	
						}
						if($showper == 1){
							$per = $PeriodBalance*100/abs($PerArr[$rowsjournal[21]]);
							echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:12px !important;'>". number_format($per, $Decimal) ."%</td>";
						}
						
						if ($monthdist == 1 ) {
							if ($curr == $Base1)  $i = 22; else $i = 23;
							
							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='center' style='color:$rowsjournal[18] !important;font-size:$rowsjournal[19]px !important;'>". format_currency($rowsjournal[$i]   , $Decimal) ."</td>";
									if($showper == 1){
										$per = $rowsjournal[$i]*100/abs($PerArr[$rowsjournal[21].getMonth($m).$y]);
										echo "<td align='right' valign='center' style='color:$rowsjournal[18] !important;font-size:12px !important;'>". number_format($per , $Decimal) ."%</td>";
									}
									$i = $i + 2;
								}

							}
						}
						
						echo "</tr>";
					}else{
						
						if((substr($tmpgrpclass,0,2) == $grpclass || substr($tmpgrpclass,0,4) == $grpclass || substr($tmpgrpclass,0,5) == $grpclass) && $showdetail == 0){ $dtlclassdisplay = "style='display:none'"; $classname = 'detail'; }
						else $dtlclassdisplay = '';
						echo "<tr class='cls$grpclass' class='$classname' height='20'  $dtlclassdisplay>"; 
						//echo 'prj='.$rowsjournal[6].' cet= '.$rowsjournal[7];
						if ($rowsjournal[6] == '' && $rowsjournal[7] == '') {
							
							if($curr == 'USD'){$currbase = 0;$currbase1 = 0;$currbase2 = 1;}
							else{$currbase = 1;$currbase1 = 1;$currbase2 = 0;}
							echo "<td align='left' valign='top'>";
							if($exp ==1)
								echo $rowsjournal[0] ."</td>";
							else 	
							echo "<a href=\"rep_statementofaccount.php?fromdate=$dispfromdate&todate=$disptodate&fromledger=".$rowsjournal[0]."&toledger=".$rowsjournal[0]."&fromproject=$dispfromproject&fromcst=$dispfromcst&fromcur=$fromcur&dateoption=1&transaction=3&ledgeroption=1&curr=$currbase&currbase1=$currbase1&currbase2=$currbase2&cum=0&alltypes=0&exclude=0&jvtype=&showunposted=0&prtfolio=1&prtref=1&prtdesc=1&prtvaluedate=1&prtjvtype=0&prtcostcent=0&prtproject=0&prevbal=1&dtjv=0&dtdate=1&checks=1&cltcst=&cltprj=&parentprj=0&prtaging=0&prtheader=1&prtcstjour=0&prtwording=0&salesman=&prtwnac=0&varprtbreak=1\" 
								target='_blank' style='text-decoration:none; color: inherit;'>". $rowsjournal[0] ."</a></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($showper == 1)
							echo "<td align='right' valign='top'> </td>";
						
						if ($monthdist == 1 ) {
							if ($curr == $Base1)  $i = 22; else $i = 23;
							
							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($showper == 1)
										echo "<td align='right' valign='top'></td>";
									
									$i = $i + 2;
								}

							}
						}
						
						echo "</tr>";
					}
				}
			}
		}
		
		//Display Stock Variation
		if ($showstock == 1  && 0  	) {
			//echo "test".':', $fromcst;exit;
			/*if ($curr == $Base1) {	
				//$StockValue =    getStockValue(     $startdate, $enddate, $Base1, $fromproject, $fromcst, $connection);
				$StockValueStart = getStockValueStart($startdate,           $Base1, $fromproject, $fromcst,$itemprint, $connection);
				$StockValueEnd = getStockValueEnd($enddate,                 $Base1, $fromproject, $fromcst,$itemprint, $connection);
				$StockValue = $StockValueEnd-$StockValueStart;
							
				if ($showprevbal == 1) {
					//$PrevStockValue =     getStockValue(    $prestartdate, $preenddate, $Base1, $fromproject, $fromcst, $connection);
					$PrevStockValueStart =getStockValueStart($prestartdate,              $Base1, $fromproject, $fromcst,$itemprint, $connection);
					$PrevStockValueEnd  =getStockValueEnd(  $preenddate,                $Base1, $fromproject, $fromcst,$itemprint, $connection);
					$PrevStockValue = $PrevStockValueEnd - $PrevStockValueStart;
					
				}
			} else 	{
				//$StockValue = getStockValue(         $startdate, $enddate, $Base2,$fromproject, $fromcst, $connection);
				$StockValueStart = getStockValueStart($startdate,           $Base2, $fromproject,$fromcst,$itemprint, $connection);
				$StockValueEnd = getStockValueEnd(                $enddate, $Base2, $fromproject,$fromcst,$itemprint, $connection);
				$StockValue = $StockValueEnd-$StockValueStart;
				if ($showprevbal == 1) {
					//$PrevStockValue = getStockValue(        $prestartdate, $preenddate, $Base2, $fromproject, $fromcst, $connection);
					$PrevStockValueStart = getStockValueStart($prestartdate,              $Base2, $fromproject, $fromcst,$itemprint, $connection);
					$PrevStockValueEnd = getStockValueEnd(   $preenddate,                $Base2, $fromproject, $fromcst,$itemprint, $connection);
					$PrevStockValue = $PrevStockValueEnd-$PrevStockValueStart;
					
				}
			}*/
		
			echo "<tr class='totals' height='30'>"; 
			echo "<td align='right' valign='center'>&nbsp;</td>";
			echo "<td align='left' valign='center'><b>Stock - Opening</b></td>";	
			if ($showprevbal == 1) {
				echo "<td align='right' valign='top'>". format_currency($PrevStockValueStart, $Decimal) ."</td>";
				echo "<td align='right' valign='top'>". format_currency($StockValueStart, $Decimal) ."</td>";
				echo "<td align='right' valign='top'>". format_currency($StockValueStart + $PrevStockValueStart, $Decimal) ."</td>";	
			} else {
				//echo "<td align='right' valign='top'>&nbsp;</td>";
				echo "<td align='right' valign='top'>". format_currency($StockValueStart, $Decimal) ."</td>";
				//echo "<td align='right' valign='top'>&nbsp;</td>";	
			}			
			echo "</tr>";
			
			echo "<tr class='totals' height='30'>"; 
			echo "<td align='right' valign='center'>&nbsp;</td>";
			echo "<td align='left' valign='center'><b>Stock - Closing</b></td>";	
			if ($showprevbal == 1) {
				echo "<td align='right' valign='top'>". format_currency($PrevStockValueEnd, $Decimal) ."</td>";
				echo "<td align='right' valign='top'>". format_currency($StockValueEnd, $Decimal) ."</td>";
				echo "<td align='right' valign='top'>". format_currency($StockValueEnd + $PrevStockValueEnd, $Decimal) ."</td>";	
			} else {
				//echo "<td align='right' valign='top'>&nbsp;</td>";
				echo "<td align='right' valign='top'>". format_currency($StockValueEnd, $Decimal) ."</td>";
				//echo "<td align='right' valign='top'>&nbsp;</td>";	
			}	
			if($showper == 1)
				echo "<td align='right' valign='top'>". format_currency($StockValueEnd, $Decimal) ."</td>";
			echo "</tr>";
			echo "<tr class='totals' height='30'>"; 
			echo "<td align='right' valign='center'>&nbsp;</td>";
			echo "<td align='left' valign='center'><b>Stock Variation</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($showper == 1)
				echo "<td align='right' valign='top'>". format_currency($StockValueEnd, $Decimal) ."</td>";
			
			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>";
			}
			if($showper == 1)
				echo "<td align='right' valign='center'>". format_currency($TotalPeriodBalance, $Decimal) ."</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 = 22; else $i = 23;
				
			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>";
						if($showper == 1) echo "<td align='center' valign='center' class='$monthlyclass'>".$monthlylabel."</td>";
						
					}
					else {
						echo "<td align='right' valign='center'>&nbsp;</td>";
						if($showper == 1) 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($showper == 1) 
				echo "<td align='right' valign='center' class='$totalclass' font-size:12px>". format_currency($TotalPeriodBalance, $Decimal) ."</td>";
			if ($curr == $Base1)  $i = 22; else $i = 23;
				
			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>";
						if($showper == 1)  echo "<td align='right' valign='center' class='$monthlyclass' font-size:12px>". format_currency($MonthlyBalance[$i], $Decimal) ."</td>";
						
					}
					else {
						echo "<td align='right' valign='center'>&nbsp;</td>";
						if($showper == 1) echo "<td align='right' valign='center'>&nbsp;</td>";
					}
						
					$i = $i + 2;
				}

			}
			
			echo "</tr>";
			
			
		}
					
			
	}
}
else {
	$i = -1;
	$resultjournal=mysql_query($queryjournal,$connection) or die('   a'    .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') {
			if ($ArrayBalance['LedgerGrpDet'][$i] == 1){
				$grpclass = $ArrayBalance['LedgerNo'][$i];
				echo"<tr class='$classname' height='20'>";
				if($exp ==1)
				echo"<td align='left' valign='top'>". $ArrayBalance['LedgerNo'][$i] ."</td>";
				else echo"<td align='left' valign='top'><a href='#' class='toggler' data-grp-class='".$ArrayBalance['LedgerNo'][$i]."' style='text-decoration:none; color: inherit;'>". $ArrayBalance['LedgerNo'][$i] ."</a></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($showdtprjcost == 1 && $ArrayBalance['LedgerGrpDet'][$i] == 0 ) {
						$ArraySumBalByCost[$ArrayCostcenter[$j]] = $ArraySumBalByCost[$ArrayCostcenter[$j]] + $ArrayBalance[$ArrayCostcenter[$j]][$i]; 
						$ArrayBalance2[$ArrayCostcenter[$j]] = $ArrayBalance2[$ArrayCostcenter[$j]] + $ArrayBalance[$ArrayCostcenter[$j]][$i]; 	
					}
					else 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($showdtprjcost == 1 && $ArrayBalance['LedgerGrpDet'][$i] == 0 ) {
					$ArraySumBalByCost['Total'] = $ArraySumBalByCost['Total'] + $ArrayBalance['Total'][$i];
					
				}			
				else if ($ArrayBalance['LedgerGrpDet'][$i] == 1)
					$ArraySumBalByCost['Total'] = $ArraySumBalByCost['Total'] + $ArrayBalance['Total'][$i];
			}else{
				echo "<tr class='cls$grpclass' class='$classname' height='20'  style='display:none'>"; 
				echo "<td align='left' valign='top'>";
				if($exp ==1)
				echo $ArrayBalance['LedgerNo'][$i] ."</td>";
				else 
				echo "<a href=\"rep_statementofaccount.php?fromdate=$dispfromdate&todate=$disptodate&fromledger=".$ArrayBalance['LedgerNo'][$i]."&toledger=".$ArrayBalance['LedgerNo'][$i]."&fromproject=$dispfromproject&fromcst=$dispfromcst&fromcur=$fromcur&dateoption=1&transaction=3&ledgeroption=1&curr=$currbase&currbase1=$currbase1&currbase2=$currbase2&cum=0&alltypes=0&exclude=0&jvtype=&showunposted=0&prtfolio=1&prtref=1&prtdesc=1&prtvaluedate=1&prtjvtype=0&prtcostcent=0&prtproject=0&prevbal=1&dtjv=0&dtdate=1&checks=1&cltcst=&cltprj=&parentprj=0&prtaging=0&prtheader=1&prtcstjour=0&prtwording=0&salesman=&prtwnac=0&varprtbreak=1\"
							target='_blank' style='text-decoration:none; color: inherit;'>". $ArrayBalance['LedgerNo'][$i] ."</a></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($showdtprjcost == 1 && $ArrayBalance['LedgerGrpDet'][$i] == 0 ) {
						$ArraySumBalByCost[$ArrayCostcenter[$j]] = $ArraySumBalByCost[$ArrayCostcenter[$j]] + $ArrayBalance[$ArrayCostcenter[$j]][$i]; 
						$ArrayBalance2[$ArrayCostcenter[$j]] = $ArrayBalance2[$ArrayCostcenter[$j]] + $ArrayBalance[$ArrayCostcenter[$j]][$i]; 	
					}
					else 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($showdtprjcost == 1 && $ArrayBalance['LedgerGrpDet'][$i] == 0 ) {
					$ArraySumBalByCost['Total'] = $ArraySumBalByCost['Total'] + $ArrayBalance['Total'][$i];
					
				}			
				else 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++){
				if($showdtprjcost == 1 ) {
					echo"<td align='right' valign='center'>".format_currency($ArrayBalance2[$ArrayCostcenter[$j]], $Decimal)."</td>";
					$MainGroupTotals += $ArrayBalance2[$ArrayCostcenter[$j]];
					$ArrayBalance2[$ArrayCostcenter[$j]] = 0;
				} else {
					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
	$StockValueStart = 0;
	$StockValueEnd = 0;
	$StockValue = 0;
	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);
				$StockValueTotStart =getStockValueStart($startdate, $Base1, $fromproject, $fromcst,$itemprint,$WithLocal,$FI_BelongsToGrp,  $connection);
			    $StockValueTotEnd   =getStockValueEnd(  $enddate,   $Base1, $fromproject, $fromcst,$itemprint,$WithLocal,$FI_BelongsToGrp,  $connection);
				$StockValueTot=$StockValueTotEnd-$StockValueTotStart;
				if ($incomebycst == 1) {
					//$StockValue = getStockValue(       $startdate, $enddate, $Base1, '', $ProjCostCenter, $connection);
					$StockValueStart =getStockValueStart($startdate,           $Base1, '', $ProjCostCenter,$itemprint,$WithLocal,$FI_BelongsToGrp,  $connection);
					$StockValueEnd   =getStockValueEnd(  $enddate,             $Base1, '', $ProjCostCenter,$itemprint,$WithLocal, $FI_BelongsToGrp, $connection);
					$StockValue=$StockValueEnd-$StockValueStart;
				} else {
					//$StockValue = getStockValue(       $startdate, $enddate, $Base1, $ProjCostCenter, '', $connection);
					$StockValueStart =getStockValueStart($startdate,           $Base1, $ProjCostCenter, '',$itemprint,$WithLocal,$FI_BelongsToGrp,  $connection);
					$StockValueEnd   =getStockValueEnd(  $enddate,             $Base1, $ProjCostCenter,'',$itemprint, $WithLocal,$FI_BelongsToGrp, $connection);
					$StockValue=$StockValueEnd-$StockValueStart;
				}
			} else 	{
				//$StockValueTot =   getStockValue(     $startdate, $enddate, $Base2, '', '', $connection);
				$StockValueTotStart =getStockValueStart($startdate, $Base2,           '', '',$itemprint,$WithLocal,$FI_BelongsToGrp,  $connection);
			    $StockValueTotEnd = getStockValueEnd(   $enddate,   $Base2,           '', '',$itemprint,$WithLocal, $FI_BelongsToGrp, $connection);
				$StockValueTot=$StockValueTotEnd-$StockValueTotStart;
				if ($incomebycst == 1) {
					//$StockValue = getStockValue($startdate,$enddate,$Base2, '',$ProjCostCenter, $connection);
					$StockValueStart = getStockValueStart($startdate, $Base2, '',$ProjCostCenter,$itemprint,$WithLocal, $FI_BelongsToGrp, $connection);
					$StockValueEnd = getStockValueEnd(    $enddate,   $Base2, '',$ProjCostCenter,$itemprint,$WithLocal,$FI_BelongsToGrp,  $connection);
					$StockValue=$StockValueEnd-$StockValueStart;
				} else {
					//$StockValue = getStockValue($startdate,$enddate,$Base2,$ProjCostCenter, '', $connection);
					$StockValueStart = getStockValueStart($startdate, $Base2, $ProjCostCenter,'',$itemprint,$WithLocal,$FI_BelongsToGrp,  $connection);
					$StockValueEnd =   getStockValueEnd(  $enddate,   $Base2, $ProjCostCenter,'',$itemprint,$WithLocal, $FI_BelongsToGrp, $connection);
					$StockValue=$StockValueEnd-$StockValueStart;
				}
			}
		
			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('   a'    .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,$itemprint,$WithLocal,$FI_BelongsToGrp, $connection){
	
	$query = " Select (ifNull(GetStockValueCostMethod('".$PEndDate."', '".$PCurr."', ".$PProject.", ".$PCostCent.", ".$itemprint.",".$WithLocal.",'".$FI_BelongsToGrp."'),0) -  ".
			 " ifNull(GetStockValueCostMethod('".$PStartDate."', '".$PCurr."', ".$PProject.", ".$PCostCent.", ".$itemprint.",".$WithLocal.",'".$FI_BelongsToGrp."'),0)) as StockValue ";

	$result=mysql_query($query,$connection) or die('   a1    '.mysql_error());
	$row=mysql_fetch_row($result);
	
	
	return $row[0];
}

function getStockValueStart($PStartDate, $PCurr, $PProject, $PCostCent,$itemprint, $WithLocal,$FI_BelongsToGrp,$showloan, $connection){
	//echo 'kokokokoko';
	//echo $itemprint;
	//exit;
	
	//echo $itemprint;
	$query = " Select (ifNull(GetStockValueCostMethod('".$PStartDate."', '".$PCurr."', ".$PProject.", ".$PCostCent.", ".$itemprint.", ".$WithLocal.",'".$FI_BelongsToGrp."','".$showloan."'),0)) as StockValue ";
	//echo $query."<br>" ;//exit;
	$result=mysql_query($query,$connection) or die('   a2    '.mysql_error());
	$row=mysql_fetch_row($result);

	return $row[0];
}

function getStockValueEnd( $PEndDate, $PCurr, $PProject, $PCostCent,$itemprint, $WithLocal,$FI_BelongsToGrp, $showloan, $connection){
	$query = " Select (ifNull(GetStockValueCostMethod('".$PEndDate."', '".$PCurr."', ".$PProject.", ".$PCostCent.", ".$itemprint.", ".$WithLocal.",'".$FI_BelongsToGrp."','".$showloan."'),0)) as StockValue ";
 //echo $query."<br>" ;
	$result=mysql_query($query,$connection) or die('   a3    '.mysql_error());
	$row=mysql_fetch_row($result);
//echo $row[0];
	return $row[0];
}

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

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

?>