<?php

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

//Option Balance of Project-Costcent
if ($report == 3) {
	$groupby = 2;
	//$showdetail = 1;
}


//$option 1=Project   2=Costcenter
if ($option == 1) {
	$ReportName  = 'Report of Project';
	$ReportTitle = 'Monthly Balance of Project per Account';
	$OptionLabel = 'Project';
	$SubOptionLabel = 'Costcenter';
} 
else {
	$ReportName  = 'Report of Costcenter';
	$ReportTitle = 'Monthly Balance of Costcenter per Account';
	$OptionLabel = 'Costcenter';
	$SubOptionLabel = 'Project';
}


print <<< HERE
<HTML>
<HEAD>
<TITLE> $ReportName </TITLE>

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

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

						
table.master tr.group { font-size: 12px; 
						font-weight: bold;
						font-family:Times-New-Roman;
					  }	
table.master tr.subgroup { font-size: 12px; 
						   font-weight: bold;
						   font-family:Times-New-Roman;
						   color:#0026FF;
					     }					  
			   
table.master tr.totals { font-size: 12px; 
						 font-weight: bold;
						 font-family:Times-New-Roman;
					  }	
table.master tr.subtotals { font-size: 12px; 
							font-weight: bold;
							font-family:Times-New-Roman;
							color:#0026FF;
						}
				 

</style>




</HEAD>


HERE;
include("config.inc.php");

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

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($_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);
}
$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(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, report_color1, report_color2, Company_Name As CompanyName from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultsetup)){
  extract($rows);
}

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


$querymodule="select ifNull(module_groupbyledger,0) As module_groupbyledger,ifNull(Module_BelongsToGroup,0) as Module_BelongsToGroup,ifnull(Module_ConfirmJV,0) as Module_ConfirmJV from module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultmodule)){
  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 (loginstk.project_code is not null and loginstk.project_code != '') ".
			  " order by project.project_code";
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectexist   = mysql_num_rows($projectresult);

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



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


$SelectedGroupBy = "Group by:  ";
if ($groupby == 1 ) $SelectedGroupBy = $SelectedGroupBy . "Ledger";
if ($groupby == 2 ) $SelectedGroupBy = $SelectedGroupBy . $OptionLabel;


$SelectedOptions = "Filter by: <br>";
if ($fromdate != '')      $SelectedOptions .= "-> Date From: ". $fromdate . "  To: ". $todate ."<br>";	
if ($currency != '')      $SelectedOptions .= "-> Currency: ". $currency ."<br>";	
if ($fromledger != '')    $SelectedOptions .= "-> Ledger From: ". $fromledger . "  To: ". $toledger ."<br>";
if ($fromproject != '')   $SelectedOptions .= "-> Project From: ". $fromproject . "  To: ". $toproject . "<br>";
if ($fromcostcent != '')  $SelectedOptions .= "-> Costcent From: ". $fromcostcent . "  To: ". $tocostcent . "<br>";
$SelectedOptions = $SelectedGroupBy . "<br>" . $SelectedOptions;

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

$fromledger      = GetSQLValueString($fromledger, 'text');
$toledger        = GetSQLValueString($toledger, 'text');
$fromproject     = GetSQLValueString($fromproject, 'text');
$toproject    	 = GetSQLValueString($toproject, 'text');
$fromcostcent 	 = GetSQLValueString($fromcostcent, 'text');
$tocostcent  	 = GetSQLValueString($tocostcent, 'text');
$fromdate  	   	 = GetSQLValueString($fromdate, 'date');
$todate          = GetSQLValueString($todate, 'date');   

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



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

echo $printdate[2]."/".$printdate[1]."/".$printdate[0];
echo "<br>".$dt[1]." ".$dt[2];
  
print <<<HERE
</font></td>
</tr>
<tr>
   <td colspan='4' width='100%'> <hr width='100%' color='black' size='1'> </td>
</tr>
</table>


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

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

if ($showdetail == 1) {
	if ($groupby == 1) {
		echo"<tr>
				<th align='left' width='7%'>Ledger No.</th>
				<th align='left' width='13%'>Ledger Name</th>
				<th align='left' width='80%'>&nbsp;</th>
			 </tr>";
	} else {
		echo"<tr>
				<th align='left' width='7%'>$OptionLabel</th>
				<th align='left' width='13%'>$OptionLabel Name</th>
				<th align='left' width='70%'>&nbsp;</th>
			 </tr>";
	}

}


echo "  <tr><td colspan='3'>";

//Create Table Columns
CreateTableStructure($vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo);		

	 
 
if ($groupby == 1) {
	echo"	<tr>";
	if ($showdetail == 1) {	
		echo"<th align='left'>&nbsp;</th>
			 <th align='left'>$OptionLabel</th>
		  	 <th align='left'>$OptionLabel Name</th>";
				
	} else {
		echo"<th align='left' colspan='2'>Ledger No.</th>
			 <th align='left'>Ledger Name</th>";
	}
} else {
	echo"	<tr>";
	
	if ($showdetail == 1) {
		if ($report == 3) {
			echo"	<th align='left' colspan='2'>$SubOptionLabel</th>
					<th align='left'>$SubOptionLabel Name</th>
				 </tr>";
			echo"<tr>";
		}
		echo"<th align='left'>&nbsp;</th>
			 <th align='left'>Ledger No.</th>
			 <th align='left'>Ledger Name</th>";	 	 
	} else {
		echo"<th align='left' colspan='2'>$OptionLabel</th>
			 <th align='left'>$OptionLabel Name</th>";	
			 
		if ($report == 3) {
			echo"</tr>";
			echo"<tr>";
			echo"	<th align='left'>&nbsp;</th>
					<th align='left'>$SubOptionLabel</th>
					<th align='left'>$SubOptionLabel Name</th>";
			
		}
	}
}	

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 align='center'>".getMonth($m)." ".$y."</th>";
				
	}
}		
		
echo"	<th align='center'>Balance $currency</th>";
echo" </tr>";
	

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

$queryjournal=$queryjournal." select MasterCode, MasterDescription, DetailCode, DetailDescription, Currency_code, ".	
							" Balance, BalanceBase1, BalanceBase2, SubMasterCode, SubMasterDescription ";
							
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."Balance AS ".getMonth($m).$y."Balance ".
						", ".getMonth($m).$y."BalanceBase1 AS ".getMonth($m).$y."BalanceBase1 ".
						", ".getMonth($m).$y."BalanceBase2 AS ".getMonth($m).$y."BalanceBase2 ";
					
	}
}			
				
$queryjournal=$queryjournal." from ( ";
$queryjournal=$queryjournal." select if($groupby=1, Ledger.Ledger_number, if($option=1, if($parentprjcost=1, ifNull(Project.Parent_Code, ifNull(Project.Project_Code, 'None')), ifNull(CstJour.Project_code, 'None')), if($parentprjcost=1, ifNull(Costcent.Parent_Code, ifNull(Costcent.Costcent_Code, 'None')), ifNull(CstJour.Costcent_Code, 'None')))) As MasterCode, ".
							" if($groupby=1, Ledger.Ledger_name, if($option=1, ifNull(project.project_name, 'None'), ifNull(costcent.costcent_name, 'None'))) As MasterDescription , ".
							" if($report=3, if($option=2, if($parentprjcost=1, ifNull(Project.Parent_Code, ifNull(Project.Project_Code, 'None')), ifNull(CstJour.Project_code, 'None')), if($parentprjcost=1, ifNull(Costcent.Parent_Code, ifNull(Costcent.Costcent_Code, 'None')), ifNull(CstJour.Costcent_Code, 'None'))), Null) As SubMasterCode, ".
							" if($report=3, if($option=2, ifNull(project.project_name, 'None'), ifNull(costcent.costcent_name, 'None')), Null) As SubMasterDescription , ".
							" if($showdetail=1, if($groupby=1, if($option=1, if($parentprjcost=1, ifNull(Project.Parent_Code, ifNull(Project.Project_Code, 'None')), ifNull(CstJour.Project_code, 'None')), if($parentprjcost=1, ifNull(Costcent.Parent_Code, ifNull(Costcent.Costcent_Code, 'None')), ifNull(CstJour.Costcent_Code, 'None'))), Ledger.Ledger_number), '') As DetailCode, ".
							" if($showdetail=1, if($groupby=1, if($option=1, ifNull(project.project_name, 'None'), ifNull(costcent.costcent_name, 'None')), Ledger.Ledger_name), '') As DetailDescription , ".
							" JournalDt.Currency_code, ";
					
//if ($fromproject != 'Null' || $toproject != 'Null' || $fromcostcent != 'Null' || $tocostcent != 'Null') {
  
    $queryjournal= $queryjournal.
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount)),0)) Balance, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1)),0)) BalanceBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2)),0)) BalanceBase2 ";
					
	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(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and (concat(month(JournalDt.Journal_date), year(JournalDt.Journal_date)) = '".$m.$y."'), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount)),0)) AS ".getMonth($m).$y."Balance ".
							", Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and (concat(month(JournalDt.Journal_date), year(JournalDt.Journal_date)) = '".$m.$y."'), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1)),0)) AS ".getMonth($m).$y."BalanceBase1 ".
							", Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and (concat(month(JournalDt.Journal_date), year(JournalDt.Journal_date)) = '".$m.$y."'), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2)),0)) AS ".getMonth($m).$y."BalanceBase2 ";
									
		}

	}				

/*} else {
    $queryjournal= $queryjournal.
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount , 0),0)) DebitAmount, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount1, 0),0)) DebitAmountBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount2, 0),0)) DebitAmountBase2, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', Journaldt_amount , 0),0)) CreditAmount, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', Journaldt_amount1, 0),0)) CreditAmountBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', Journaldt_amount2, 0),0)) CreditAmountBase2, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount, (-1)*Journaldt_amount),0)) Balance, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount1, (-1)*Journaldt_amount1),0)) BalanceBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount2, (-1)*Journaldt_amount2),0)) BalanceBase2 ";
				   
}	*/		   
 

$queryjournal= $queryjournal.
			   " from JournalDt ".
			   " Inner join Ledger on JournalDt.Ledger_number = Ledger.Ledger_number ".
			   " Inner join Journal on JournalDt.Journal_id = Journal.Journal_id ";

//if ($fromproject != 'Null' || $toproject != 'Null' || $fromcostcent != 'Null' || $tocostcent != 'Null') {
	$queryjournal=$queryjournal." Left outer Join CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ".
								" Left outer Join project on project.Project_code = Cstjour.Project_code ".
								" Left outer Join costcent on costcent.Costcent_Code = Cstjour.Costcent_Code ";

	if ($projectexist > 0 && $FI_RepRestrictProject == 1)
		$queryjournal=$queryjournal." Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
									"			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
									"              and (loginstk.project_code is not null and loginstk.project_code != '') ".
									"		     ) Q1 on CstJour.project_code like concat(Q1.project_code,'%') ";
									
	if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
		$queryjournal=$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 CstJour.Costcent_code like concat(Q2.costcent_code,'%')  ";								
//} else{   
  //$queryjournal= $queryjournal.	" Left outer Join project on project.Project_code = Journal.Project_code ".
	//							" Left outer Join costcent on costcent.Costcent_Code = Journal.Costcent_Code ";
							   
//}							   

 

$queryjournal= $queryjournal.  
				" where  ledger.Ledger_number between ifNull(".$fromledger.",ledger.Ledger_number) and ifNull(". $toledger.",ledger.Ledger_number)  ".
				" and date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d'))   ".
				" and (($alltypes = 1 and 1 = 1) or ($alltypes = 0 and $jvtypelen = 0 and 1 = 1) or ($alltypes = 0 and $exclude = 0 and $jvtypelen > 0 and Journal_type in ($jvtype)) or ($alltypes = 0 and $exclude = 1 and $jvtypelen > 0 and Journal_type not in ($jvtype)) ) ";


//if ($fromproject != 'Null' || $toproject != 'Null' || $fromcostcent != 'Null' || $tocostcent != 'Null') { 
if($projectper == 1)
$queryjournal= $queryjournal." and upper(ifNull(CstJour.project_code,'-1')) like ifNull(upper (".$fromproject."), upper(ifNull(CstJour.project_code,'-1'))) ";
else 
  $queryjournal= $queryjournal.	" and upper(ifNull(CstJour.project_code,'-1')) between ifNull(upper(".$fromproject."), upper(ifNull(CstJour.project_code,'-1'))) and ifNull(upper(".$toproject."), upper(ifNull(CstJour.project_code,'-1'))) ";
if($costcentper == 1)
$queryjournal= $queryjournal." and upper(ifNull(CstJour.Costcent_Code,'-1')) like ifNull(upper(".$fromcostcent."), upper(ifNull(CstJour.Costcent_Code,'-1'))) ";
else
  $queryjournal= $queryjournal." and upper(ifNull(CstJour.Costcent_Code,'-1')) between ifNull(upper(".$fromcostcent."), upper(ifNull(CstJour.Costcent_Code,'-1'))) and ifNull(upper(".$tocostcent."), upper(ifNull(CstJour.Costcent_Code,'-1'))) ";
//}

if ($Module_BelongsToGroup == 1)				
	$queryjournal= $queryjournal." and ifNull(ledger.Ledger_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ".
							   " and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ";

if($Module_ConfirmJV == 1) $queryjournal= $queryjournal." and ifnull(Journal_Confirmed,0) = 1 ";							   
 

$queryjournal= $queryjournal." Group By MasterCode, SubMasterCode, DetailCode ".
							 " Order By MasterCode, SubMasterCode, DetailCode ";
							 
$queryjournal= $queryjournal." ) Q3  ".
							 " where (($balance = 1 and 1 = 1) or ($balance = 2 and Balance > 0) or ($balance = 3 and Balance < 0) or ($balance = 4 and Balance = 0)) ".
							 " Order By MasterCode, SubMasterCode, DetailCode ";

//echo $queryjournal;exit;


$MasterByCode = '';
$MasterByName = '';
$SubMasterByCode = '';
$SubMasterByName = '';

$ArrayTotalByReport   = Array();
$ArrayTotalByMaster   = Array();
$ArrayTotalBySubMaster = Array();

$resultjournal=mysql_query($queryjournal,$connection) or die(mysql_error());
$col=0;
while($rowsjournal=mysql_fetch_row($resultjournal)){

		if($col%2==0){
			$color = "style='background-color:".$report_color1."'";
		}else{
			$color = "style='background-color:".$report_color2."'";
		}
    // Group By Options Names and Totals
	if (($report == 3) && ($SubMasterByCode != $rowsjournal[8] && $SubMasterByCode != '')) {
		    
		echo "<tr>";
		echo "   <td colspan='3'><hr width='100%' color='black' size='1'></td>";
		echo "</tr>";
			
		$StyleClass  = 'subtotals';
		$TotalsLabel = 'Total by '. $SubOptionLabel .'('. $currency .')';
	
		echo "<tr><td colspan='3'>";
	
		//Create Table Columns
		CreateTableStructure($vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo, $color);

		echo "<tr class='subtotals'>";
		echo "   <td align='right' valign='top' colspan='3'>". $TotalsLabel ."</td>";
		
		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($ArrayTotalBySubMaster['Balance'][$m.$y], $DecimalBase) ."</td>";
			}
		}
		
		echo "	 <td align='right' valign='top'>". format_currency($ArrayTotalBySubMaster['Balance']['Total'], $DecimalBase) ."</td>";
		echo "</tr>";
		echo"</table></td></tr>";
		
	}
	
	if ((($showdetail == 1) || ($report == 3 && $showdetail == 0)) && ($MasterByCode != $rowsjournal[0] && $MasterByCode != '')) {
		    
		echo "<tr>";
		echo "   <td colspan='3'><hr width='100%' color='black' size='1'></td>";
		echo "</tr>";
			
		$StyleClass  = 'totals';
		if ($groupby == 1) $TotalsLabel = 'Total by Ledger ('. $currency .')';
		else $TotalsLabel = 'Total by '. $OptionLabel .'('. $currency .')';
		
		echo "<tr><td colspan='3'>";
	
		//Create Table Columns
		CreateTableStructure($vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo, $color);

		echo "<tr class='totals'>";
		echo "   <td align='right' valign='top' colspan='3'>". $TotalsLabel ."</td>";
		
		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($ArrayTotalByMaster['Balance'][$m.$y], $DecimalBase) ."</td>";
			}
		}
		
		echo "	 <td align='right' valign='top'>". format_currency($ArrayTotalByMaster['Balance']['Total'], $DecimalBase) ."</td>";
		echo "</tr>";
		echo"</table></td></tr>";
		
	}

	if ((($showdetail == 1) || ($report == 3 && $showdetail == 0)) && ($MasterByCode == '' || $MasterByCode != $rowsjournal[0])) { 	
		echo "<tr class='group'>";
		echo "   <td align='left' valign='top' width='7%'>". $rowsjournal[0] ."</td>";
		echo "   <td align='left' valign='top' width='13%'>". $rowsjournal[1] ."</td>";
		echo "   <td align='left' valign='top' width='80%'>&nbsp;</td>";
		echo "</tr>"; 
		
		$MasterByCode = $rowsjournal[0];
		$MasterByName = $rowsjournal[1];
		
		unset($ArrayTotalByMaster);
		
	}	
	
	if (($report == 3 && $showdetail == 1) && ($SubMasterByCode == '' || $SubMasterByCode != $rowsjournal[8])) { 	
		echo "<tr class='subgroup'>";
		echo "   <td align='left' valign='top' width='7%'>". $rowsjournal[8] ."</td>";
		echo "   <td align='left' valign='top' width='13%'>". $rowsjournal[9] ."</td>";
		echo "   <td align='left' valign='top' width='80%'>&nbsp;</td>";
		echo "</tr>"; 
		
		$SubMasterByCode = $rowsjournal[8];
		$SubMasterByName = $rowsjournal[9];
		
		unset($ArrayTotalBySubMaster);
		
	}	
	
	echo "<tr><td colspan='3'>";
	
	//Create Table Columns
	CreateTableStructure($vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo);

	echo"<tr $color>";
	
	if ($showdetail == 1) {
		echo "<td align='left' valign='top'>&nbsp;</td>";
		echo "<td align='left' valign='top'>". $rowsjournal[2] ."</td>";
		echo "<td align='left' valign='top'>". $rowsjournal[3] ."</td>";
	} 
	else if ($showdetail == 0) {
		if ($report != 3) {
			echo "<td align='left' valign='top' colspan='2'>". $rowsjournal[0] ."</td>";
			echo "<td align='left' valign='top' >". $rowsjournal[1] ."</td>";
		} else {
			echo "<td align='left' valign='top' colspan='2'>". $rowsjournal[8] ."</td>";
			echo "<td align='left' valign='top' >". $rowsjournal[9] ."</td>";
		}
	} 
	
	
	$i = 10;
	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 ($currency == $Base1) {
				
				echo "<td align='right' valign='top' >". format_currency($rowsjournal[$i + 1], $DecimalBase1) ."</td>";
				
				$ArrayTotalByMaster['Balance'][$m.$y]    = $ArrayTotalByMaster['Balance'][$m.$y]    + $rowsjournal[$i + 1];
				$ArrayTotalBySubMaster['Balance'][$m.$y] = $ArrayTotalBySubMaster['Balance'][$m.$y] + $rowsjournal[$i + 1];
			}
			else if ($currency == $Base2) {
				echo "<td align='right' valign='top' >". format_currency($rowsjournal[$i + 2], $DecimalBase2) ."</td>";
				
				$ArrayTotalByMaster['Balance'][$m.$y]    = $ArrayTotalByMaster['Balance'][$m.$y]    + $rowsjournal[$i + 2];
				$ArrayTotalBySubMaster['Balance'][$m.$y] = $ArrayTotalBySubMaster['Balance'][$m.$y] + $rowsjournal[$i + 2];
			}
					
			$i = $i + 3;
		}
	}
	
	
	if ($currency == $Base1) {
		echo "<td align='right' valign='top' >". format_currency($rowsjournal[6], $DecimalBase1) ."</td>";
		
		$ArrayTotalByMaster['Balance']['Total']    = $ArrayTotalByMaster['Balance']['Total']    + $rowsjournal[6];
		$ArrayTotalBySubMaster['Balance']['Total'] = $ArrayTotalBySubMaster['Balance']['Total'] + $rowsjournal[6];
	}	
	else {
		echo "<td align='right' valign='top' >". format_currency($rowsjournal[7], $DecimalBase2) ."</td>";
		
		$ArrayTotalByMaster['Balance']['Total']    = $ArrayTotalByMaster['Balance']['Total']    + $rowsjournal[7];
		$ArrayTotalBySubMaster['Balance']['Total'] = $ArrayTotalBySubMaster['Balance']['Total'] + $rowsjournal[7];
	}		
	
	    
	echo"</tr>";	
	echo"</table></td></tr>";
	$col+=1;
}


// Group By Options Names and Totals
if (($report == 3) && ($SubMasterByCode != $rowsjournal[8] && $SubMasterByCode != '')) {
		    
	echo "<tr>";
	echo "   <td colspan='6'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
			
	$StyleClass  = 'subtotals';
	$TotalsLabel = 'Total by '. $SubOptionLabel .'('. $currency .')';
		
	echo "<tr><td colspan='3'>";
	
	//Create Table Columns
	CreateTableStructure($vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo, $color);

	echo "<tr class='subtotals'>";
	echo "   <td align='right' valign='top' colspan='3'>". $TotalsLabel ."</td>";
		
	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($ArrayTotalBySubMaster['Balance'][$m.$y], $DecimalBase) ."</td>";
		}
	}
		
	echo "	 <td align='right' valign='top'>". format_currency($ArrayTotalBySubMaster['Balance']['Total'], $DecimalBase) ."</td>";
	echo "</tr>";
	echo"</table></td></tr>";
		
}

if ((($showdetail == 1) || ($report == 3 && $showdetail == 0)) && ($MasterByCode != $rowsjournal[0] && $MasterByCode != '')) {
		    
	echo "<tr>";
	echo "   <td colspan='6'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
			
	$StyleClass  = 'totals';
	if ($groupby == 1) $TotalsLabel = 'Total by Ledger ('. $currency .')';
	else $TotalsLabel = 'Total by '. $OptionLabel .'('. $currency .')';
		
	echo "<tr><td colspan='3'>";
	
	//Create Table Columns
	CreateTableStructure($vYearFrom, $vYearTo, $vMonthFrom, $vMonthTo, $color);

	echo "<tr class='totals'>";
	echo "   <td align='right' valign='top' colspan='3'>". $TotalsLabel ."</td>";
		
	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($ArrayTotalByMaster['Balance'][$m.$y], $DecimalBase) ."</td>";
		}
	}
		
	echo "	 <td align='right' valign='top'>". format_currency($ArrayTotalByMaster['Balance']['Total'], $DecimalBase) ."</td>";
	echo "</tr>";
	echo"</table></td></tr>";
		
}
	   

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

function CreateTableStructure($PYearFrom, $PYearTo, $PMonthFrom, $PMonthTo) {
	
	echo "  <table  border='0' align='left' class='master' style='table-layout:fixed' cellpadding='0' cellspacing='0'>
				<col width=20>	
				<col width=120>
				<col width=250>";
				
	for ( $y = $PYearFrom; $y <= $PYearTo; $y += 1) {

		if ($y == $PYearFrom && $y == $PYearTo) { $vMFrom = $PMonthFrom; $vMTo = $PMonthTo; }
		else if ($y == $PYearFrom && $y != $PYearTo) { $vMFrom = $PMonthFrom; $vMTo = 12; }
		else if ($y == $PYearTo && $y != $PYearFrom) { $vMFrom = 1; $vMTo = $PMonthTo; }
		else { $vMFrom = 1; $vMTo = 12; }
				
		for ( $m = $vMFrom; $m <= $vMTo; $m += 1) {
			echo" <col width=110>";
		}
	}

	echo" <col width=110>";	

}

function current_server_time($connection){

  $string="Select date_format(NOW(),'%Y-%m-%d %h:%i %p') ";
  $result=mysql_query($string,$connection) or die(mysql_error());
  $now=mysql_fetch_row($result);

  return $now;
}

function explodeword($date)
{

$trim = explode('/',$date);
$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
return $trim;
}

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

function format_currency($amount, $DecimalBase) { 

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

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

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

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

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

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


?>