<?php

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


//$option 1=Shipment Ref   2=Costcenter
if ($option == 1) {
	$ReportName  = 'Statement of Shipment Ref';
	$ReportTitle = 'Statement of Shipment Ref';
	$OptionLabel = 'Shipment Ref';
} 
else {
	$ReportName  = 'Statement of Costcenter';
	$ReportTitle = 'Statement of Costcenter';
	$OptionLabel = 'Costcenter';
}

print <<< HERE
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<TITLE> $ReportName </TITLE>
<script>
function getJournal(journal_id, schemaname){
	window.open("Form_Journal_Actions.php?mode=&mainmode=loadfromstatmentproject&SJourId="+journal_id+"&schemaname="+schemaname,'Journal')
}
</script>
<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.totals { font-size: 12px; 
						 font-weight: bold;
						 font-family:Times-New-Roman;
					  }	
					  
				 

</style>




</HEAD>


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

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

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

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

if($fromledger!=''){
$queryledger="select ledger_name as fromledgername from ledger where ledger_number='$fromledger'";
$resultledger=mysql_query($queryledger,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultledger)){
  extract($rows);
  }
}

if($toledger!=''){
$queryledger2="select ledger_name as toledgername from ledger where ledger_number='$toledger'";
$resultledger2=mysql_query($queryledger2,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultledger2)){
  extract($rows);
  }
}

$querymodule=" Select 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($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

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

$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['dbLabel'].".loginstk on project.project_code 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]);


$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 ($fromledgername != '')    $SelectedOptions .= "-> Ledger Name From: ". $fromledgername . "  To: ". $toledgername ."<br>";
if ($fromproject != '')   $SelectedOptions .= "-> Shipment Ref From: ". $fromproject . "  To: ". $toproject . "<br>";
if ($fromcostcent != '')  $SelectedOptions .= "-> Costcent From: ". $fromcostcent . "  To: ". $tocostcent . "<br>";


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

$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';      

$showdetail = 1;

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' style='table-layout:fixed; border-collapse:collapse;' cellpadding='0' cellspacing='0'>
	  <col width=70>	
	  <col width=70>
	  <col width=50>";
	  
if ($prtvaluedate == 1)	  
	echo"<col width=70>";
if ($prtjvtype == 1)	  	
	echo"<col width=50>";
	
echo" <col width=80>
	  <col width=250>
	  <col width=110>
	  <col width=110>
	  <col width=110>";
	  
echo"<tr>
		<th align='left'>Date</th>
		<th align='center'>JV.Ref</th>
		<th align='center'>Folio</th>";

if ($prtvaluedate == 1)		
	echo"<th align='center'>Value Date</th>";
if ($prtjvtype == 1)		
	echo"<th align='center'>Type</th>";
		
echo"	<th align='left'>Ledger No.</th>
		<th align='left'>Description</th>
		<th align='center'>Debit</th>
		<th align='center'>Credit</th>
		<th align='center'>Balance $currency</th>
	</tr>";


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

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

$result = mysql_query("start transaction", $connection);
$resultvars = mysql_query("set @AmtBalBase1 :=0.0, @AmtBalBase2:=0.0, @VarMasterCode:='x' ", $connection);
	
$queryjournal=$queryjournal." select MasterCode, MasterDescription, LedgerNumber, LedgerName, Journal_date, Journaldt_ValueDate, ".
                            " OrderByDate, Journal_type, Journal_folio, Journal_refgovernment, Journaldt_desc, Currency_code, Journaldt_dbcd, ".	
							" PrevDbBase1, PrevDbBase2, PrevCrBase1, PrevCrBase2, PrevBalBase1, PrevBalBase2, ".
							" AmtDbBase1, AmtDbBase2, AmtCrBase1, AmtCrBase2, AmtBase1, AmtBase2, ".
							" @AmtBalBase1 := if (MasterCodeOption != MasterCode, if($prtprevbal = 1, PrevBalBase1 + AmtBase1, AmtBase1), @AmtBalBase1 + AmtBase1) As AmtBalBase1, ".
							" @AmtBalBase2 := if (MasterCodeOption != MasterCode, if($prtprevbal = 1, PrevBalBase2 + AmtBase2, AmtBase2), @AmtBalBase2 + AmtBase2) As AmtBalBase2, scehma, journalid ".
							" from ( ".		
$queryjournal=$queryjournal." select MasterCode, MasterDescription, LedgerNumber, LedgerName, Journal_date, Journaldt_ValueDate, ".
                            " OrderByDate, Journal_type, Journal_folio, Journal_refgovernment, Journaldt_desc, Currency_code, Journaldt_dbcd, ".	
							" PrevDbBase1, PrevDbBase2, PrevCrBase1, PrevCrBase2, PrevBalBase1, PrevBalBase2, ".
							" AmtDbBase1, AmtDbBase2, AmtCrBase1, AmtCrBase2, AmtBase1, AmtBase2, ".
							" @VarMasterCode As MasterCodeOption, @VarMasterCode := MasterCode, scehma, journalid ".
							" from ( ".	
$queryjournal=$queryjournal." select MasterCode, MasterDescription, LedgerNumber, LedgerName, Journal_date, Journaldt_ValueDate, ".
                            " OrderByDate, Journal_type, Journal_folio, Journal_refgovernment, Journaldt_desc, Currency_code, Journaldt_dbcd, ".	
							" PrevDbBase1, PrevDbBase2, PrevCrBase1, PrevCrBase2, PrevBalBase1, PrevBalBase2, ".
							" AmtDbBase1, AmtDbBase2, AmtCrBase1, AmtCrBase2, AmtBase1, AmtBase2, scehma, journalid ".
							" from ( ";
							
// Reading Data For Many Years Or Different Directories	
$ResultDir=mysql_query($QueryDir,$connection) or die(mysql_error());				 
while($RowsDir=mysql_fetch_row($ResultDir)){

	$j = $j + 1;    
	$DirSchema = $RowsDir[0];
		   
	if ($RowsDirCount >= 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
	}	

	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
		
		$k = $k + 1;
	
		$queryjournal=$queryjournal." select 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($option=1, ifNull(project.project_name, 'None'), ifNull(costcent.costcent_name, 'None')) As MasterDescription , ".
									" Ledger.Ledger_number As LedgerNumber, Ledger.Ledger_name As LedgerName, date_format(JournalDt.Journal_date,'%d/%m/%Y') As Journal_date, JournalDt.Journal_date As OrderByDate, ".
									" date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y') As Journaldt_ValueDate, Journal_type, Journal_folio, Journal_refgovernment, Journaldt_desc, JournalDt.Currency_code, Journaldt_dbcd, ".
									" ifNull(PrevDbBase1,0) As PrevDbBase1, ifNull(PrevDbBase2,0) As PrevDbBase2, ifNull(PrevCrBase1,0) As PrevCrBase1, ifNull(PrevCrBase2,0) As PrevCrBase2, ifNull(PrevBalBase1,0) As PrevBalBase1, ifNull(PrevBalBase2,0) As PrevBalBase2, ".
									" if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), 0) AmtDbBase1, ".
									" if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), 0) AmtDbBase2, ".
									" if(Journaldt_dbcd = 'C', if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), 0) AmtCrBase1, ".
									" if(Journaldt_dbcd = 'C', if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), 0) AmtCrBase2, ".
									" 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)) AmtBase1, ".
									" 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)) AmtBase2, '$DirSchema' as scehma, Journal.Journal_id as journalid ";

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

		$queryjournal=$queryjournal." Left outer Join $DirSchema.CstJour As 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,'%')  ";								
		
		$queryjournal= $queryjournal." Left join ( ".
									" select JournalDt.Ledger_number As LedgerNo, if($option=1, ifNull(CstJour.Project_code, 'None'), ifNull(CstJour.Costcent_Code, 'None')) As PrevMasterCode, ".
									" Sum(if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), 0)) PrevDbBase1, ".
									" Sum(if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), 0)) PrevDbBase2, ".
									" Sum(if(Journaldt_dbcd = 'C', if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), 0)) PrevCrBase1, ".
									" Sum(if(Journaldt_dbcd = 'C', if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), 0)) PrevCrBase2, ".
									" Sum(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))) PrevBalBase1, ".
									" Sum(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))) PrevBalBase2 ".
									" from $DirSchema.JournalDt As JournalDt ".
									" Left outer Join $DirSchema.CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ".
									" where date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) ".
									" and JournalDt.Ledger_number between ifNull(".$fromledger.",JournalDt.Ledger_number) and ifNull(". $toledger.",JournalDt.Ledger_number)  ".
									" group by LedgerNo, PrevMasterCode ".
									" ) QPrev on QPrev.PrevMasterCode = if($option=1, ifNull(CstJour.Project_code, 'None'), ifNull(CstJour.Costcent_Code, 'None')) and  QPrev.LedgerNo = JournalDt.Ledger_number ";

		$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)) ) ";
				//" and Journal.Journal_Type != 'CL' ".
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 ($RowsDirCount > 1 && $k != 1)	
			$queryjournal= $queryjournal." and Journal.Journal_Type != 'OP' ";
		
		if ($Module_BelongsToGroup == 1)
		$queryjournal= $queryjournal." 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, date_format(JournalDt.Journal_date,'%d/%m/%Y'), date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y'), JournalDt.Ledger_number, Journal_refgovernment  ";
			  
		if ($RowsDirCount > 1 && $j < $RowsDirCount)	
			$queryjournal= $queryjournal." Union ";
							
	}							
}		
							 
$queryjournal= $queryjournal." ) Q3  ".
							 " Order By MasterCode, date_format(OrderByDate,'%Y-%m-%d'), Journal_refgovernment, LedgerNumber ".
							 " ) Q4  ".
							 " Order By MasterCode, date_format(OrderByDate,'%Y-%m-%d'), Journal_refgovernment, LedgerNumber ".
							 " ) Q5  ".
							 " Order By MasterCode, date_format(OrderByDate,'%Y-%m-%d'), Journal_refgovernment, LedgerNumber ";

//echo $queryjournal;exit;


$MasterByCode = '';
$MasterByName = '';

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



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

    
    // Group By Options Names and Totals
	if (($showdetail == 1) && ($MasterByCode != $rowsjournal[0] && $MasterByCode != '')) {
		
		$StyleClass   = 'totals';
		$TotalsLabel  = 'Total Period by '. $OptionLabel .'('. $currency .')';
		$TotalsLabel1 = 'Total by '. $OptionLabel .'('. $currency .')';
		
		DisplayTotals($prtprevbal, $prtvaluedate, $prtjvtype, $ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $TotalsLabel1, $StyleClass);
		
			$GeneralTotal['Debit'] 		= $GeneralTotal['Debit'] 	  + $ArrayTotalByMaster['Debit'];
			$GeneralTotal['Credit'] 	= $GeneralTotal['Credit'] 	  + $ArrayTotalByMaster['Credit'];
			$GeneralTotal['Balance'] 	= $GeneralTotal['Balance'] 	  + $ArrayTotalByMaster['Balance'];
			
		
		unset($ArrayTotalByMaster);
		
	}

	if (($showdetail == 1) && ($MasterByCode == '' || $MasterByCode != $rowsjournal[0])) { 	

		if ($currency == $Base1) 
			CreateGroupHeader($prtprevbal, $prtvaluedate, $prtjvtype, $rowsjournal[0], $rowsjournal[1], $OptionLabel, $Base1, $rowsjournal[17], $DecimalBase1);
		else if ($currency == $Base2)	
			CreateGroupHeader($prtprevbal, $prtvaluedate, $prtjvtype, $rowsjournal[0], $rowsjournal[1], $OptionLabel, $Base2, $rowsjournal[18], $DecimalBase2);
		
		$MasterByCode = $rowsjournal[0];
		$MasterByName = $rowsjournal[1];
		
		//Set The Actual Balance Initialy Equal To Previous Balance
		if ($currency == $Base1) {
			$ArrayTotalByMaster['ActDebit']   = $rowsjournal[13];
			$ArrayTotalByMaster['ActCredit']  = $rowsjournal[15];
			$ArrayTotalByMaster['ActBalance'] = $rowsjournal[17];
			
		}	
		else if ($currency == $Base2){
			$ArrayTotalByMaster['ActDebit']   = $rowsjournal[14];
			$ArrayTotalByMaster['ActCredit']  = $rowsjournal[16];
			$ArrayTotalByMaster['ActBalance'] = $rowsjournal[18];
			
		}	
		
	}	
						
	
	if ($showdetail == 1) {
		echo "<tr>"; 
		echo "<td align='left' valign='top'>". $rowsjournal[4] ."</td>";
		echo "<td align='left' valign='top'><div onclick=\"getJournal('$rowsjournal[28]','$rowsjournal[27]');\"  style='cursor: pointer;'>". $rowsjournal[9] ."</div></td>";
		echo "<td align='left' valign='top'>". $rowsjournal[8] ."</td>";
		
		if ($prtvaluedate == 1)
			echo "<td align='left' valign='top'>". $rowsjournal[5] ."</td>";
		if ($prtjvtype == 1)	
			echo "<td align='center' valign='top'>". $rowsjournal[7] ."</td>";
			
		echo "<td align='left' valign='top'>". $rowsjournal[2] ."</td>";
		echo "<td align='left' valign='top'>". $rowsjournal[10] ."</td>";
		
		if ($currency == $Base1) {
			echo "<td align='right' valign='top' >". format_currency($rowsjournal[19], $DecimalBase1) ."</td>";
			echo "<td align='right' valign='top' >". format_currency($rowsjournal[21], $DecimalBase1) ."</td>";
			echo "<td align='right' valign='top' >". format_currency($rowsjournal[25], $DecimalBase1) ."</td>";
			
			$ArrayTotalByMaster['Debit']      = $ArrayTotalByMaster['Debit']      + $rowsjournal[19];
			$ArrayTotalByMaster['Credit']     = $ArrayTotalByMaster['Credit']     + $rowsjournal[21];
			$ArrayTotalByMaster['Balance'] 	  = $ArrayTotalByMaster['Balance']    + $rowsjournal[23];
			$ArrayTotalByMaster['ActDebit']   = $ArrayTotalByMaster['ActDebit']   + $rowsjournal[19];
			$ArrayTotalByMaster['ActCredit']  = $ArrayTotalByMaster['ActCredit']  + $rowsjournal[21];
			$ArrayTotalByMaster['ActBalance'] = $ArrayTotalByMaster['ActBalance'] + $rowsjournal[23];
		}
		else if ($currency == $Base2) {
			echo "<td align='right' valign='top' >". format_currency($rowsjournal[20], $DecimalBase2) ."</td>";
			echo "<td align='right' valign='top' >". format_currency($rowsjournal[22], $DecimalBase2) ."</td>";
			echo "<td align='right' valign='top' >". format_currency($rowsjournal[26], $DecimalBase2) ."</td>";
			
			$ArrayTotalByMaster['Debit']      = $ArrayTotalByMaster['Debit']      + $rowsjournal[20];
			$ArrayTotalByMaster['Credit']     = $ArrayTotalByMaster['Credit']     + $rowsjournal[22];
			$ArrayTotalByMaster['Balance'] 	  = $ArrayTotalByMaster['Balance']    + $rowsjournal[24];
			$ArrayTotalByMaster['ActDebit']   = $ArrayTotalByMaster['ActDebit']   + $rowsjournal[20];
			$ArrayTotalByMaster['ActCredit']  = $ArrayTotalByMaster['ActCredit']  + $rowsjournal[22];
			$ArrayTotalByMaster['ActBalance'] = $ArrayTotalByMaster['ActBalance'] + $rowsjournal[24];
		}
		
		echo "</tr>"; 
	}	
	
	
}

// Group By Options Names and Totals
if (($showdetail == 1) && ($MasterByCode != $rowsjournal[0] && $MasterByCode != '')) {
		
	$StyleClass   = 'totals';
	$TotalsLabel  = 'Total Period by '. $OptionLabel .'('. $currency .')';
	$TotalsLabel1 = 'Total by '. $OptionLabel .'('. $currency .')';
		
	DisplayTotals($prtprevbal, $prtvaluedate, $prtjvtype, $ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $TotalsLabel1, $StyleClass);
		$GeneralTotal['Debit'] 		= $GeneralTotal['Debit'] 	  + $ArrayTotalByMaster['Debit'];
		$GeneralTotal['Credit'] 	= $GeneralTotal['Credit'] 	  + $ArrayTotalByMaster['Credit'];
		$GeneralTotal['Balance'] 	= $GeneralTotal['Balance'] 	  + $ArrayTotalByMaster['Balance'];
	unset($ArrayTotalByMaster);
		
}
 
if ($PPrtValueDate == 1 && $PPrtJvType == 1)
		$SpanValue = 10;
	else if ($PPrtValueDate == 0 && $PPrtJvType == 0)
		$SpanValue = 8;
	else if ($PPrtValueDate == 1 || $PPrtJvType == 1)
		$SpanValue = 9;
			
	$SpanValue1 = $SpanValue - 3;	 
echo "<tr class='".$StyleClass."'>";
	echo "   <td align='right' valign='top' colspan=$SpanValue1>General Totals by $OptionLabel ($currency)</td>";
	echo "	 <td align='right' valign='top'>". format_currency($GeneralTotal['Debit'],   $PDecimalBase) ."</td>";
	echo "	 <td align='right' valign='top'>". format_currency($GeneralTotal['Credit'],  $PDecimalBase) ."</td>";
	echo "	 <td align='right' valign='top'>". format_currency($GeneralTotal['Balance'], $PDecimalBase) ."</td>";
echo "</tr>"; 

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

function CreateGroupHeader($PPrtPrevbal, $PPrtValueDate, $PPrtJvType, $PMasterCode, $PMasterName, $POptionLabel, $PBase, $PPrevBal, $PDecimalBase) {
	echo"<tr height='30'>";
	
	if ($PPrtValueDate == 1 && $PPrtJvType == 1)
		echo"<td colspan='10'>";
	else if ($PPrtValueDate == 0 && $PPrtJvType == 0)
		echo"<td colspan='8'>";	
	else if ($PPrtValueDate == 1 || $PPrtJvType == 1)
		echo"<td colspan='9'>";		
			
	echo"	<table  border='0' width='100%' align='center' class='master' style='table-layout:fixed; border-collapse:collapse;' cellpadding='0' cellspacing='0'>
				<col width=120>	
				<col width=400>
				<col width=120>
				<col width=40>
				<col width=130>
				<col width=50>
				<tr>
					<th align='left'>Group by $POptionLabel</th>
					<th align='left'>$PMasterCode - $PMasterName</th>";
					
				if ($PPrtPrevbal == 1) {	
					echo"<th align='left'>Previous Balance</th>
						 <th align='center'>$PBase</th>
						 <th align='right'>".format_currency($PPrevBal, $PDecimalBase)."</th>";
				} else {
					echo"<th align='center' colspan='3'>&nbsp;</th>";
				}
						 
			echo"	<th align='center'>&nbsp;</th>
				</tr>
			</table></td>
		</tr>";

}

function DisplayTotals($PPrtPrevbal, $PPrtValueDate, $PPrtJvType, $PArrayTotal, $PDecimalBase, $PTotalsLabel, $PTotalsLabel1, $PStyleClass) {
	
	if ($PPrtValueDate == 1 && $PPrtJvType == 1)
		$SpanValue = 10;
	else if ($PPrtValueDate == 0 && $PPrtJvType == 0)
		$SpanValue = 8;
	else if ($PPrtValueDate == 1 || $PPrtJvType == 1)
		$SpanValue = 9;
			
	$SpanValue1 = $SpanValue - 3;	
		
	echo "<tr>";
	echo "   <td colspan=$SpanValue><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
			
	echo "<tr class='".$PStyleClass."'>";
	echo "   <td align='right' valign='top' colspan=$SpanValue1>". $PTotalsLabel ."</td>";
	echo "	 <td align='right' valign='top'>". format_currency($PArrayTotal['Debit'],   $PDecimalBase) ."</td>";
	echo "	 <td align='right' valign='top'>". format_currency($PArrayTotal['Credit'],  $PDecimalBase) ."</td>";
	echo "	 <td align='right' valign='top'>". format_currency($PArrayTotal['Balance'], $PDecimalBase) ."</td>";
	echo "</tr>";
		
	if ($PPrtPrevbal == 1) {
		echo "<tr class='totals'>";
		echo "   <td align='right' valign='top' colspan=$SpanValue1>". $PTotalsLabel1 ."</td>";
		echo "	 <td align='right' valign='top'>". format_currency($PArrayTotal['ActDebit'],   $PDecimalBase) ."</td>";
		echo "	 <td align='right' valign='top'>". format_currency($PArrayTotal['ActCredit'],  $PDecimalBase) ."</td>";
		echo "	 <td align='right' valign='top'>". format_currency($PArrayTotal['ActBalance'], $PDecimalBase) ."</td>";
		echo "</tr>";
		
	}	

}

function current_server_time($connection){

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

  return $now;
}

function explodeword($date)
{

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

function format_currency($amount, $DecimalBase) { 

    if (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;


?>