<?php

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

include("config.inc.php");
include("function.inc.php");
//Set Time Execution For the Report
//ini_set('max_execution_time', $config['ReportTimeExecution']);
set_time_limit(0);


$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) 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);
}

print <<< HERE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
<HEAD>



<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<TITLE> Statement of Account Report </TITLE>
 

<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">

<style type="text/css">
/* added_by_rodolphe on 5/4/2018 */
 tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(2) > tr:nth-child(3) > td:nth-child(1) > table:nth-child(1)
 {
	display: table;
    width: 100%;
    margin: 0 auto;
 }

</style>


<script type="text/javascript" language="javascript">


function PrintPreview(JourId)
{
	var str = '';
	
	str = 'Form_JournalPreview.php?journal_id='+JourId;
	window.open(str);

}
function PrintPreview3(TransId, TransType)
{
	var str = '';
	
	str = 'Form_TransPreview.php?TransId='+TransId+'&TransType='+TransType;
	window.open(str);

}
function PrintPreview4(TransId){
	var str = "Form_SalesJVPreview.php?SalesJVId="+TransId;
	window.open(str);
}
function PrintPreview2(MainId, JournalType, Language, ShowLogo, Module_Delivery)
{
	var str = '';
	if(JournalType == "DI" || JournalType == "DR")
	{
		if(JournalType == "DI"){
		str = 'Form_DeliveryPreview.php?SalesId='+MainId+'&PLang='+Language+'&printlogo='+ShowLogo;
		}
		else
		{
			str = 'Form_ReturnDeliveryPreview.php?ReturnSalesId='+MainId+'&PLang='+Language+'&printlogo='+ShowLogo;
		}
	}
	else
		if(JournalType == "SI" || JournalType == "SR")
		{
			if(JournalType == "SI"){
			if(Module_Delivery == 0)
			{
				str = 'Form_DeliveryPreview.php?SalesId='+MainId+'&PLang='+Language+'&printlogo='+ShowLogo;
			}
			else
			{
			str = 'Form_SalesPreview.php?SalesId='+MainId+'&PLang='+Language+'&printlogo='+ShowLogo;
			}
		}
		else
		{
			if(Module_Delivery == 0)
			{
				str = 'Form_ReturnDeliveryPreview.php?ReturnSalesId='+MainId+'&PLang='+Language+'&printlogo='+ShowLogo;
			}
			else
			{
			str = 'Form_ReturnSalesPreview.php?ReturnSalesId='+MainId+'&PLang='+Language+'&printlogo='+ShowLogo;
			}
		}
		
		}
		else
			if(JournalType == "PI" || JournalType == "PR")
			{
				if(JournalType == "PI"){
				str = 'Form_PurchasePreview.php?PurchaseId='+MainId+'&PrtSer=1&PLang='+Language;
				}
				else
				{
					str = 'Form_ReturnPurchasePreview.php?PurchaseId='+MainId+'&PrtSer=1&PLang='+Language;
				}
			}
			else
				if(JournalType == "PD")
				{
					str = 'Form_AssemblePreview.php?ProductionId='+MainId;
				}
				else
					if(JournalType == "AI")
					{
						str = 'Form_AdjustmentPreview.php?AdjustmentId='+MainId+'&PrtSer=1';
					}
					else
					if(JournalType == "SO")
					{
						str = 'Form_SalesOrderPreview.php?SorderId='+MainId+'&ShowDetail=1&export=0&sorder=SO';
					}
	window.open(str);
}

function UpdateRecord(JourId){
	win = window.open('Form_Journal_Actions.php?mainmode=EditJournalFromReport&SJourId='+JourId, 'Form_JournalSearch', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=1100,height=750,left=20,top=20');
	win.creator = self;
	win.focus();
}
function UpdateRecord2(TransId, vTransType){
	//var vTransType = document.search.TransType.value;
	
	var str="Form_Trans_Actions.php?TransType="+vTransType+"&mainmode=editfromreport&STransId="+TransId;
	//alert(str);exit;
	//document.search.submit();
	window.open(str);
	//document.search.PMode.value=1;
	
	//opener.document.trans.txtTransId.value=TransId;
	//opener.document.trans.mainaction.value='edit';
	//opener.document.trans.actionmode.value='';
	
	//opener.document.trans.action='Form_Trans.php';
	//opener.document.trans.submit();
	
	
	//self.close();
	

}
function UpdateRecord3(SId){
	//var vTransType = document.search.TransType.value;
	
	var str="Form_SalesJV_Actions.php?mainmode=editfromreport&SId="+SId;
	//alert(str);exit;
	//document.search.submit();
	window.open(str);
	//document.search.PMode.value=1;
	
	//opener.document.trans.txtTransId.value=TransId;
	//opener.document.trans.mainaction.value='edit';
	//opener.document.trans.actionmode.value='';
	
	//opener.document.trans.action='Form_Trans.php';
	//opener.document.trans.submit();
	
	
	//self.close();
	

}
</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;
                 }
		*/	 		 
th.headborder {
                border-width: 1px;
				border-style: solid;
				border-color: #666666;
               }
td.headborder {
                border-width: 1px;
				padding: 1px;
				border-style: none solid;
				border-color: #666666;
               }			   
			   
			   
				

td.headborderdt {
                border-width: 1px;
				padding: 1px;
				border-style: solid;
				border-color: #666666;
               }
			   
table.totals td { font-size: 12px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                 }					  
	td.totalborder {
                font-weight: bold;
                border-width: 1px;
				padding: 1px;
				border-style: solid;
				border-color: #666666;
               }			 		  
			   

</style>



</HEAD>


HERE;

$querylog="SELECT FA_Journal as FA_Journal, FA_Receipt, FA_ReceiptMod, FA_CreditNote, FA_CreditNoteMod, FA_DebitNote, FA_DebitNoteMod, FA_Payment, FA_PaymentMod, FA_SalesJV, FA_SalesJVMod 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);
			}
			
			$querylog=" select ifNull(FA_JournalDel,0) As FA_JournalDel, ifNull(FA_JournalMod,0) As FA_JournalMod, ".
					  " ifNull(print,0) As FA_JournalPreview, ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(ShowTransaction,0) As ShowTransaction  ".
					  " 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);
			}
			

			
$querylog="SELECT print as printaccess from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
	$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($resultlog)){
		extract($rows);
	}
	

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





$querylog=" select ifNull(FI_RepRestrictProject,0) As FI_RepRestrictProject, ifNull(FI_RepRestrictCostcenter,0) As FI_RepRestrictCostcenter, ".
		  " 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) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_BelongsToGroup,0) As Module_BelongsToGroup, ifnull(Module_ConfirmJV,0) as Module_ConfirmJV, ifnull(Module_Delivery, 0) as Module_Delivery  From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

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

$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_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);	

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

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

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

$queryledger= " select distinct ledger_number, ledger_include ".
              " from ".$_SESSION['dbLabel'].".ledgerrepstk  ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " and (ledger_number is not null and ledger_number != '') ".
			  " order by ledger_number"; 
$ledgerresult = mysql_query($queryledger,$connection) or die(mysql_error());
$ledgerexist  = mysql_num_rows($ledgerresult);	
$rows=mysql_fetch_array($ledgerresult) ;
$ledgerinclude = $rows[1];
if (empty($ledgerinclude)) $ledgerinclude = 0;


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

print <<< HERE


HERE;
echo"<tbody>";


$dispfromproject  = $fromproject;
$dispfromledger = $fromledger;
$disptoledger = $toledger;
$dispfromdate = $fromdate;
$disptodate = $todate;

  
   
if (empty($fromledger))   
   $fromledger = 'null';
else
   $fromledger = "'".$fromledger."'";   
   
if (empty($toledger))   
   $toledger = 'null';
else{
   //if (strlen($toledger) < 10 )
     // $toledger = str_pad($toledger, 10, '9', STR_PAD_RIGHT);
 
   $toledger = "'".$toledger."'";      
}  

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

if (empty($fromdate))   
   $fromdate = 'null';
else
   $fromdate = "'".$fromdate."'"; 
   
if (empty($todate))   
   $todate = 'null';
else
   $todate = "'".$todate."'";
   

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


$displaycurr = '';   
if ($currbase1 == 1 ) 
   $displaycurr = $Base1;
else if  ($currbase2 == 1 )
   $displaycurr = $Base2;
   
if($currbase1 == 1 && $currbase2 == 1)   
   $displaycurr = ''; 

$cltcst = "".$cltcst;
$cltprj = "".$cltprj;
if ($cltcst == '') 
   $cltcst = 'null';
else
   $cltcst = "'".$cltcst."'";       
     
if ($cltprj == '')   
   $cltprj = 'null';
else
   $cltprj = "'".$cltprj."'";      

if (empty($parentprj))  $parentprj = 0; 
if (empty($prtcstjour)) $prtcstjour = 0;
if (empty($prtwording)) $prtwording = 0;
if (empty($prtshowuser)) $prtshowuser = 0;

 
$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
$i=1;
$queryjournal = '';

if ($ledgeroption==1) {
	$queryjournal = " Select Ledger.Ledger_Number,Ledger.Ledger_Name,";
	} else if ($ledgeroption==2)  {
	$queryjournal = " Select Ledger.document Ledger_Number, 'Document' as Ledger_Name,";
	} else if ($ledgeroption==3) 
	$queryjournal = " Select if(ledger.document is null or ledger.document = '', ledger.Ledger_number , ledger.document) as Ledger_Number, if(Ledger.document is null or Ledger.document = '', ledger.ledger_number, 'Document')  as Ledger_Name,";
 $queryjournal =$queryjournal ."  Ledger.Ledger_type, ".
                " if(Ledger.Ledger_Type=1, Concat(ifNull(Client_Telephone1,''), '  ', ifNull(Client_Telephone2,'')), ".
                " if(Ledger.Ledger_Type=2, Concat(ifNull(Supplier_Telephone1,''), '  ', ifNull(Supplier_Telephone2,'')), ".
                " if(Ledger.Ledger_Type=3, Concat(ifNull(Salesmen.Salesman_Telephone1,''), '  ', ifNull(Salesmen.Salesman_Telephone2,'')), Null ))) As TelephoneNo, ".
				" if(Ledger.Ledger_Type=1, Client_Fax, if(Ledger.Ledger_Type=2, Supplier_Fax, if(Ledger.Ledger_Type=3, Salesmen.Salesman_Fax, Null))) As Fax, ".
				" if(Ledger.Ledger_Type=1, Client_Email, if(Ledger.Ledger_Type=2, Supplier_Email, if(Ledger.Ledger_Type=3, Salesmen.Salesman_Email, Null))) As Email, ".
				" if(Ledger.Ledger_Type=1, Client_Address, if(Ledger.Ledger_Type=2, Supplier_Address, if(Ledger.Ledger_Type=3, Salesmen.Salesman_address, Null))) As Address, ".
                " QDirBal.Currency_code, Sum(ifNull(PrevAmount,0)) As PrevAmount, Sum(ifNull(PrevAmount1,0)) As PrevAmount1, Sum(ifNull(PrevAmount2,0)) As PrevAmount2, ".
				" if(Ledger.Ledger_Type=1, Client_VatNo, if(Ledger.Ledger_Type=2, Supplier_vatno, Null)) As VatNo ".
				" ,clients.Salesmen_Code,ClientSalesmen.Ledger_Name ".
				" From Ledger Left Join ".
				" (  ";

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

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

		if ($fromproject != 'null' || $fromcst != 'null' || $prtcostcent == 1 || $prtproject == 1 || $prtcstjour == 1 || ($projectexist > 0 || $costcentexist > 0)) {
		    $queryjournal = $queryjournal.
					        " select JournalDt.Ledger_Number, JournalDt.Currency_code, ".
							" sum(if(( ($dateoption = 1 and date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d'))  ) or  ".
							"          ($dateoption = 2 and date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d'))  ) ), ".
							"        (if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is null,Journaldt_amount,Cstjour_amount), 0) - if(Journaldt_dbcd = 'C', if(CstJour.Cst_increment is null,Journaldt_amount,Cstjour_amount), 0)), 0)) PrevAmount, ".
							" sum(if(( ($dateoption = 1 and date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d'))  ) or  ".
							"          ($dateoption = 2 and date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d'))  ) ), ".
							"        (if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1), 0) - if(Journaldt_dbcd = 'C', if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1), 0)), 0)) PrevAmount1, ".
							" sum(if(( ($dateoption = 1 and date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d'))  ) or  ".
							"          ($dateoption = 2 and date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d'))  ) ), ".
							"        (if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is null,Journaldt_amount2,Cstjour_amount2), 0) - if(Journaldt_dbcd = 'C', if(CstJour.Cst_increment is null,Journaldt_amount2,Cstjour_amount2), 0)), 0)) PrevAmount2 ".
							" from $DirSchema.JournalDt As JournalDt ".
							" Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ".
							" Inner Join Ledger ON JournalDt.Ledger_Number = Ledger.Ledger_Number ";
		} else {
			$queryjournal = $queryjournal.
							" select JournalDt.Ledger_Number, JournalDt.Currency_code, ".
							" sum(if(( ($dateoption = 1 and date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d'))  ) or  ".
							"          ($dateoption = 2 and date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d'))  ) ), ".
							"        (if(Journaldt_dbcd = 'D', Journaldt_amount, 0) - if(Journaldt_dbcd = 'C', Journaldt_amount, 0)), 0)) PrevAmount, ".
							" sum(if(( ($dateoption = 1 and date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d'))  ) or  ".
							"          ($dateoption = 2 and date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d'))  ) ), ".
							"        (if(Journaldt_dbcd = 'D', Journaldt_amount1, 0) - if(Journaldt_dbcd = 'C', Journaldt_amount1, 0)), 0)) PrevAmount1, ".
							" sum(if(( ($dateoption = 1 and date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d'))  ) or  ".
							"          ($dateoption = 2 and date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d'))  ) ), ".
							"        (if(Journaldt_dbcd = 'D', Journaldt_amount2, 0) - if(Journaldt_dbcd = 'C', Journaldt_amount2, 0)), 0)) PrevAmount2 ".
							" from $DirSchema.JournalDt As JournalDt ".
							" Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ".
							" Inner Join Ledger ON JournalDt.Ledger_Number = Ledger.Ledger_Number ";
		}	  
				  
				  
		if ($fromproject != 'null' || $fromcst != 'null' || $prtcostcent == 1 || $prtproject == 1 || $prtcstjour == 1 || ($projectexist > 0 || $costcentexist > 0)) {
			$queryjournal= $queryjournal." Left outer Join $DirSchema.CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ";
			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.  
								" where ( ($ledgeroption = 1 and JournalDt.Ledger_number between ifNull(".$fromledger.",JournalDt.Ledger_number) and ifNull(". $toledger.",JournalDt.Ledger_number) ) or ".
								"         ($ledgeroption = 2 and ifNull(Ledger.Document,-1) between ifNull(".$fromledger.",ifNull(Ledger.Document,-1)) and ifNull(". $toledger.",ifNull(Ledger.Document,-1)) ) or
										  ($ledgeroption = 3 and (ifNull(Ledger.Document,-1) between ifNull(".$fromledger.",ifNull(Ledger.Document,-1)) and ifNull(". $toledger.",ifNull(Ledger.Document,-1))
										  or JournalDt.Ledger_number between ifNull(".$fromledger.",JournalDt.Ledger_number) and ifNull(". $toledger.",JournalDt.Ledger_number) ) ) ) ".
								//" and ( ($dateoption = 1 and date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d'))  ) or  ".
								//"       ($dateoption = 2 and date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d'))  ) )  ".
								//" and (($cum = 0 and JournalDt.Currency_code = '".$rowsjournal[13]."') or ($cum = 1 and 1 = 1))  ".
								" 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 (($showunposted = 1 and journaldt_posted = 0 ) or ($showunposted = 0 and 1 = 1 )) ";
								
		if ($Module_BelongsToGroup == 1)				
			$queryjournal= $queryjournal." and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ";						
								

		if ($curr == 1 && !(empty($fromcur))  )
			$queryjournal= $queryjournal." and Upper(JournalDt.Currency_code) = Upper('".$fromcur."') ";
										  
		if($Module_ConfirmJV == 1) $queryjournal= $queryjournal." and ifnull(Journal_Confirmed,0) = 1 ";
		
		if ($fromproject != 'null' || $fromcst != 'null' || $prtcostcent == 1 || $prtproject == 1 || $prtcstjour == 1 || ($projectexist > 0 || $costcentexist > 0)) {  
			if ($parentprj == 1) {
				$queryjournal= $queryjournal." and upper(ifNull(CstJour.project_code,'-1')) like ifNull(concat(upper(".$fromproject."),'%'), upper(ifNull(CstJour.project_code,'-1'))) ".
											 " and upper(ifNull(CstJour.Costcent_Code,'-1')) like ifNull(concat(upper(".$fromcst."),'%'), upper(ifNull(CstJour.Costcent_Code,'-1'))) ";
			} else {
				$queryjournal= $queryjournal." and upper(ifNull(CstJour.project_code,'-1')) like ifNull(upper(".$fromproject."), upper(ifNull(CstJour.project_code,'-1'))) ".
											 " and upper(ifNull(CstJour.Costcent_Code,'-1')) like ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))) ";
			}

		}
			
		if ($RowsDirCount > 1 && $k != 1)	
			$queryjournal= $queryjournal." And ifNull(Journal.Journal_Type,'JV') <> 'OP' ";
					
		
		$queryjournal= $queryjournal." Group By JournalDt.Ledger_Number, JournalDt.Currency_code ";
		  
		if ($RowsDirCount > 1 && $j < $RowsDirCount)
			$queryjournal= $queryjournal." Union ";
								
	}							
}
		
$queryjournal= $queryjournal." ) QDirBal on QDirBal.Ledger_Number = Ledger.Ledger_Number ".
                             " Left Join Clients on Clients.Ledger_Number = Ledger.Ledger_Number ".						
							 " Left Join Suppliers on Suppliers.Ledger_Number = Ledger.Ledger_Number ".
							 " Left Join Salesmen on Salesmen.Ledger_Number = Ledger.Ledger_Number ".
							 " Left Join salesmen ClientSalesmen on clients.Salesmen_Code = ClientSalesmen.ledger_number";
							 
							 
							/*if ($ledgerexist > 0) {
								$queryjournal = $queryjournal." Inner join ( select distinct ledger_number from ".$_SESSION['dbLabel'].".ledgerrepstk ".
															  "			     where user_account='".$_SESSION['useraccount']."' ".
															  "              and (ledger_number is not null and ledger_number != '') ".
															  "			   )  Q3 on (($ledgerinclude = 1 and Ledger.Ledger_Number like concat(Q3.ledger_number,'%') ) or ($ledgerinclude = 0 and Ledger.Ledger_Number Not like concat(Q3.ledger_number,'%') )) ";	
							} */
							
							//maroun
							 if ($projectmasterexist > 0)
								{
							 $queryjournal= $queryjournal." inner join (select distinct Masterproject from ".$_SESSION['dbLabel'].".loginstk
							 			   where loginstk.user_account='".$_SESSION['useraccount']."'
							              and (Masterproject is not null and Masterproject != '')
							 			 ) PrjMasterQry on ifnull(Clients.project_code,concat(PrjMasterQry.Masterproject,'%')) like concat(PrjMasterQry.Masterproject,'%') ";
								}
							
							if ($costcentermasterexist > 0) {	
							$queryjournal= $queryjournal." inner join ( select distinct Mastercostcenter from ".$_SESSION['dbLabel'].".loginstk ".
														 "			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
														 "             and (Mastercostcenter is not null and Mastercostcenter != '') ".
														 "			 ) CstMasterQry on ifnull(Clients.CostCenter_Code ,concat(CstMasterQry.Mastercostcenter,'%')) like concat(CstMasterQry.Mastercostcenter,'%') ";
							}
						
					
					
							 $queryjournal= $queryjournal." where ( ($ledgeroption = 1 and ledger.Ledger_number between ifNull(".$fromledger.",ledger.Ledger_number) and ifNull(". $toledger.",ledger.Ledger_number) ) or ".
														  "         ($ledgeroption = 2 and ifNull(ledger.Document,-1) between ifNull(".$fromledger.", ifNull(ledger.Document,-1)) and ifNull(". $toledger.", ifNull(ledger.Document,-1)) ) or 
																	($ledgeroption = 3 and (ifNull(ledger.Document,-1) between ifNull(".$fromledger.", ifNull(ledger.Document,-1)) and ifNull(". $toledger.", ifNull(ledger.Document,-1)) )
																	or (ledger.Ledger_number between ifNull(".$fromledger.",ledger.Ledger_number) and ifNull(". $toledger.",ledger.Ledger_number)))) ".
							 //" And PrevAmount != 0 ".
							 //maroun
							 " And upper(ifNull(Clients.Project_Code,'-1')) like if(clients.ledger_number='' or clients.ledger_number is null,upper(ifNull(Clients.Project_Code,'-1')),ifNull(upper(".$cltprj."), upper(ifNull(Clients.Project_Code,'-1')))) ".
							 " And upper(ifNull(Clients.CostCenter_Code,'-1')) like if(clients.ledger_number='' or clients.ledger_number is null,upper(ifNull(Clients.CostCenter_Code,'-1')),ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))) ";
							 		//maroun
					if ($salesmenexist > 0) {
						$queryjournal= $queryjournal. " and clients.Salesmen_Code in 
															(select distinct clientsalesmen from ".$_SESSION['dbLabel'].".loginstk where user_account = '".$_SESSION['useraccount']."'
															 and (clientsalesmen <>'' and clientsalesmen is not null)
															)";	
											}
					
if ($Module_BelongsToGroup == 1)				
	$queryjournal= $queryjournal." and ifNull(ledger.Ledger_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ";
	
if($ledgerinclude== 1 && $ledgerexist > 0) {
	$queryjournal = $queryjournal." And Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerrepstk ".
								  "              where ledgerrepstk.user_account='".$_SESSION['useraccount']."' ".
								  "              and (ledger_number is not null and ledger_number != '') ".
								  "              and ledger.ledger_number like concat(ledgerrepstk.ledger_number,'%') ".
								  "            ) ";
}
if($ledgerinclude== 0 && $ledgerexist > 0){
	$queryjournal = $queryjournal." And Not Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerrepstk ".
								  "                  where ledgerrepstk.user_account='".$_SESSION['useraccount']."' ".
								  "          	     and (ledger_number is not null and ledger_number != '') ".
								  "                  and ledger.ledger_number like concat(ledgerrepstk.ledger_number,'%') ".
								  "                ) ";	
}

if ($salesman<>'') {
	$queryjournal= $queryjournal." And Salesmen_Code = '".$salesman."'";
	}
$queryjournal= $queryjournal." And Ledger.Ledger_grpdet = 0 ";
if ($ledgeroption==1) {
    $queryjournal= $queryjournal." Group By Ledger.Ledger_Number, Ledger.Ledger_Name, Ledger.Ledger_type, if($cum = 0, QDirBal.Currency_code, Null), TelephoneNo, Fax, Email, Address ";	
} else {
    $queryjournal= $queryjournal."  and QDirBal.currency_code is not null Group By Ledger_Number,if($cum = 0, QDirBal.Currency_code, Null) ";	
}
//echo $queryjournal; exit;



$masterledger = '';
$mastercurrency = '';
$SumCreditAmount = 0;
$SumDebitAmount = 0;
$PrevBalance = 0;
$Balance = 0;


$resultjournal=mysql_query($queryjournal,$connection) or die(mysql_error());
$VarTotalCountRow=mysql_num_rows($resultjournal);
$break=0;
$VarCountRow=0;
while($rowsjournal=mysql_fetch_row($resultjournal)){

       
    //if (($masterledger == '' || $masterledger!= $rowsjournal[0]) || ($masterledger== $rowsjournal[0] && $mastercurrency != $rowsjournal[7]  && $cum==0)) {
	
  

	  $masterledger= $rowsjournal[0];
	  $mastercurrency = $rowsjournal[7];
	  
	  
	
	
	//}
	
	
		
		
	$j = 0;				
	$k = 0; // Count For First Existsing Db
	$querydetail = '';


	$querydetail = " Select Journal_id, Journal_date, Journaldt_ValueDate, Journal_type, Journal_folio, Journal_refgovernment, ".
				   " Journaldt_desc, Ledger_number, Ledger_name, ledger_type, Document, Project_code, Costcent_Code, ".
				   " Currency_code, Journaldt_dbcd, DebitAmount, CreditAmount, Journaldt_Id, project_name, costcent_name, OrderByDate, SchemaName, user_account, Manual_no ".
				   " from ".
				   " (  ";

	// Reading Data For Many Years Or Different Directories	
	$ResultDir1=mysql_query($QueryDir,$connection) or die(mysql_error());				 
	while($RowsDir=mysql_fetch_row($ResultDir1)){

		$j = $j + 1;    
		if ($RowsDirCount > 1)
		   $DirSchema = $RowsDir[0];
		else
		   $DirSchema = '';	
		   
		if ($RowsDirCount > 1) {
			$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
			$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
			$SchemaExists = mysql_num_rows($ResultSchemaExists);
			
		}
		
		if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
		
			$k = $k + 1;    
			if ($dtdate == 1)
			{
			 
			  if ($prtcstjour == 0 && ($projectexist > 0 || $costcentexist > 0)) {
			  
				 $querydetail= $querydetail.
								" select Journal.Journal_id As Journal_id,date_format(JournalDt.Journal_date,'%d/%m/%Y') As Journal_date,date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y') As Journaldt_ValueDate, ".
								" Journal_type, Journal_folio, Journal_refgovernment, concat(Journaldt_desc,ifnull(Journaldt_desc1,'')) as Journaldt_desc, ";
				if ($ledgeroption==1) {
					$querydetail= $querydetail."	JournalDt.Ledger_number, "; 
				} else if ($ledgeroption==2)  {
					$querydetail= $querydetail."	ledger.document as Ledger_number, ";
				} else if ($ledgeroption==3)  {
					$querydetail= $querydetail."	if(ledger.document is null or ledger.document = '', JournalDt.Ledger_number , ledger.document) as Ledger_number, ";
				}
				$querydetail= $querydetail." Ledger_name, ledger_type, ".
								" JournalDt.Document, cstjour.Project_code, cstjour.Costcent_Code, JournalDt.Currency_code, Journaldt_dbcd, ".
								" sum(if(Journaldt_dbcd = 'D', if($curr = 0, if($currbase1 = 1, Cstjour_amount1, if($currbase2 = 1, Cstjour_amount2, Cstjour_amount)), Cstjour_amount), 0)) As DebitAmount, ".
								" sum(if(Journaldt_dbcd = 'C', if($curr = 0, if($currbase1 = 1, Cstjour_amount1, if($currbase2 = 1, Cstjour_amount2, Cstjour_amount)), Cstjour_amount), 0)) As CreditAmount, ".
								" Journaldt.Journaldt_Id, project.project_name, costcent.costcent_name, if($dateoption = 2, JournalDt.Journaldt_ValueDate,JournalDt.Journal_date) As OrderByDate, '$DirSchema' As SchemaName, ".
								" Journal.user_account as user_account, Journaldt.Manual_no as Manual_no ";  
			  }
			  else if ($fromproject != 'null' || $fromcst != 'null' || $prtcostcentc == 1 || $prtprojectc == 1 || $prtcostcent == 1 || $prtproject == 1 || $prtcstjour == 1 || ($projectexist > 0 || $costcentexist > 0)) {
			  
				 $querydetail= $querydetail.
								" select Journal.Journal_id As Journal_id,date_format(JournalDt.Journal_date,'%d/%m/%Y') As Journal_date,date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y') As Journaldt_ValueDate, ".
								" Journal_type, Journal_folio, Journal_refgovernment, concat(Journaldt_desc,ifnull(Journaldt_desc1,'')) as Journaldt_desc, ";
								
				
				if ($ledgeroption==1) {
					$querydetail= $querydetail."	JournalDt.Ledger_number, "; 
				} else if ($ledgeroption==2)  {
					$querydetail= $querydetail."	ledger.document as Ledger_number, ";
				} else if ($ledgeroption==3)  {
					$querydetail= $querydetail."	if(ledger.document is null or ledger.document = '', JournalDt.Ledger_number , ledger.document) as Ledger_number, ";
				}	 		
				$querydetail= $querydetail." Ledger_name, ledger_type, ".
								" JournalDt.Document, cstjour.Project_code, cstjour.Costcent_Code, JournalDt.Currency_code, Journaldt_dbcd, ".
								" if(Journaldt_dbcd = 'D', if($curr = 0, if($currbase1 = 1, Cstjour_amount1, if($currbase2 = 1, Cstjour_amount2, Cstjour_amount)), Cstjour_amount), 0) As DebitAmount, ".
								" if(Journaldt_dbcd = 'C', if($curr = 0, if($currbase1 = 1, Cstjour_amount1, if($currbase2 = 1, Cstjour_amount2, Cstjour_amount)), Cstjour_amount), 0) As CreditAmount, ".
								" Journaldt.Journaldt_Id, project.project_name, costcent.costcent_name, if($dateoption = 2, JournalDt.Journaldt_ValueDate,JournalDt.Journal_date) As OrderByDate, '$DirSchema' As SchemaName, ".
								" Journal.user_account as user_account, Journaldt.Manual_no as Manual_no ";  
			  } else {
				 $querydetail= $querydetail. 
								" select Journal.Journal_id As Journal_id,date_format(JournalDt.Journal_date,'%d/%m/%Y') As Journal_date,date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y') As Journaldt_ValueDate, ".
								" Journal_type, Journal_folio, Journal_refgovernment, concat(Journaldt_desc,ifnull(Journaldt_desc1,'')) as Journaldt_desc, ";
					
				if ($ledgeroption==1) {
					$querydetail= $querydetail."	JournalDt.Ledger_number, "; 
				} else if ($ledgeroption==2) {
					$querydetail= $querydetail."	ledger.document as Ledger_number, ";
				} else if ($ledgeroption==3)  {
					$querydetail= $querydetail."	if(ledger.document is null or ledger.document = '', JournalDt.Ledger_number , ledger.document) as Ledger_number, ";
				}
				$querydetail= $querydetail." Ledger_name, ledger_type, ".
								" JournalDt.Document,Journal.Project_code,Journal.Costcent_Code,JournalDt.Currency_code, Journaldt_dbcd, ".
								" if(Journaldt_dbcd = 'D', if($curr = 0, if($currbase1 = 1, Journaldt_amount1, if($currbase2 = 1, Journaldt_amount2, Journaldt_amount)), Journaldt_amount), 0) As DebitAmount, ".
								" if(Journaldt_dbcd = 'C', if($curr = 0, if($currbase1 = 1, Journaldt_amount1, if($currbase2 = 1, Journaldt_amount2, Journaldt_amount)), Journaldt_amount), 0) As CreditAmount, ".
								" Journaldt.Journaldt_Id, project.project_name, costcent.costcent_name, if($dateoption = 2, JournalDt.Journaldt_ValueDate,JournalDt.Journal_date) As OrderByDate, '$DirSchema' As SchemaName, ".
								" Journal.user_account as user_account, journaldt.Manual_no as Manual_no ";
			  }			   
			} else {
			  
			   if ($fromproject != 'null' || $fromcst != 'null' || $prtcostcentc == 1 || $prtprojectc == 1 || $prtcostcent == 1 || $prtproject == 1 || $prtcstjour == 1 || ($projectexist > 0 || $costcentexist > 0)) {
			  
				 $querydetail= $querydetail.
								" select null As Journal_id ,date_format(JournalDt.Journal_date,'%d/%m/%Y') As Journal_date,date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y') As Journaldt_ValueDate, ".
								" null As Journal_type, null As Journal_folio, null As Journal_refgovernment, concat(Journal.journal_type,'-',date_format(JournalDt.Journal_date,'%d/%m/%Y')) As Journaldt_desc, ";
				if ($ledgeroption==1) {
					$querydetail= $querydetail."	JournalDt.Ledger_number, "; 
				} else if ($ledgeroption==2) {
					$querydetail= $querydetail."	ledger.document as Ledger_number, ";
				} else if ($ledgeroption==3) {
					$querydetail= $querydetail."	if(ledger.document is null or ledger.document = '', JournalDt.Ledger_number , ledger.document) as Ledger_number, ";
				}
				$querydetail= $querydetail." Ledger_name, ledger_type, ".
								" null As Document, null As Project_code, null As Costcent_Code, JournalDt.Currency_code, null As Journaldt_dbcd, ".
								" sum(if(Journaldt_dbcd = 'D', if($curr = 0, if($currbase1 = 1, Cstjour_amount1, if($currbase2 = 1, Cstjour_amount2, Cstjour_amount)), Cstjour_amount), 0)) As DebitAmount, ".
								" sum(if(Journaldt_dbcd = 'C', if($curr = 0, if($currbase1 = 1, Cstjour_amount1, if($currbase2 = 1, Cstjour_amount2, Cstjour_amount)), Cstjour_amount), 0)) As CreditAmount, ".
								" null As Journaldt_Id, null As project_name, null As costcent_name, if($dateoption = 2, JournalDt.Journaldt_ValueDate,JournalDt.Journal_date) As OrderByDate, '$DirSchema' As SchemaName, ".
								" Journal.user_account as user_account, Journaldt.Manual_no as Manual_no ";
			   } else {
				 $querydetail= $querydetail. 
								" select null As Journal_id ,date_format(JournalDt.Journal_date,'%d/%m/%Y') As Journal_date,date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y') As Journaldt_ValueDate, ".
								" null As Journal_type, null As Journal_folio, null As Journal_refgovernment, concat(Journal.journal_type,'-',date_format(JournalDt.Journal_date,'%d/%m/%Y')) As Journaldt_desc,  ";
				if ($ledgeroption==1) {
					$querydetail= $querydetail."	JournalDt.Ledger_number, "; 
				} else if ($ledgeroption==2){
					$querydetail= $querydetail."	ledger.document as Ledger_number, ";
				} else if ($ledgeroption==3){
					$querydetail= $querydetail."	if(ledger.document is null or ledger.document = '', JournalDt.Ledger_number , ledger.document) as Ledger_number, ";
				}
				$querydetail= $querydetail."  Ledger_name, ledger_type, ".
								" null As Document, null As Project_code, null As Costcent_Code, JournalDt.Currency_code, null As Journaldt_dbcd, ".
								" sum(if(Journaldt_dbcd = 'D', if($curr = 0, if($currbase1 = 1, Journaldt_amount1, if($currbase2 = 1, Journaldt_amount2, Journaldt_amount)), Journaldt_amount), 0)) As DebitAmount, ".
								" sum(if(Journaldt_dbcd = 'C', if($curr = 0, if($currbase1 = 1, Journaldt_amount1, if($currbase2 = 1, Journaldt_amount2, Journaldt_amount)), Journaldt_amount), 0)) As CreditAmount, ".
								" null As Journaldt_Id, null As project_name, null As costcent_name, if($dateoption = 2, JournalDt.Journaldt_ValueDate,JournalDt.Journal_date ) As OrderByDate, '$DirSchema' As SchemaName, ".
								" Journal.user_account as user_account, Journaldt.Manual_no as Manual_no ";
			   }			   
			}
//echo $querydetail; exit;
			$querydetail= $querydetail.
						   " from $DirSchema.JournalDt As JournalDt ".
						   " Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ".
						   " Inner join ledger on JournalDt.Ledger_number = ledger.Ledger_number ";

			if ($fromproject != 'null' || $fromcst != 'null' || $prtcostcentc == 1 || $prtprojectc == 1 || $prtcostcent == 1 || $prtproject == 1 || $prtcstjour == 1 || ($projectexist > 0 || $costcentexist > 0)) {
				$querydetail= $querydetail." 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) {
					$querydetail = $querydetail." 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) {
					$querydetail = $querydetail." 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{   
			  $querydetail= $querydetail." Left outer Join project on project.Project_code = Journal.Project_code ".
										 " Left outer Join costcent on costcent.Costcent_Code = Journal.Costcent_Code ";
									   
			}							   


			if ($ledgeroption==1) {
				$querydetail= $querydetail." where ledger.Ledger_number = '".$rowsjournal[0]."'  ";
			} else if ($ledgeroption==2) {
			    $querydetail= $querydetail." where ledger.document = '".$rowsjournal[0]."'  ";
			} else if ($ledgeroption==3) {
			    $querydetail= $querydetail." where (ledger.document = '".$rowsjournal[0]."' or ledger.Ledger_number = '".$rowsjournal[0]."' ) ";
			}
			$querydetail= $querydetail." and ( ($dateoption = 1 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')) ) or  ".
							"       ($dateoption = 2 and date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journaldt_ValueDate,'%Y-%m-%d')) ) )  ".
							" and (($transaction = 1 and Journaldt_dbcd = 'C') or ($transaction = 2 and Journaldt_dbcd = 'D') or ($transaction = 3 and 1 = 1)) ".
							" 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 (($showunposted = 1 and journaldt_posted = 0 ) or ($showunposted = 0 and 1 = 1 )) ".
							" and (($cum = 0 and Upper(JournalDt.Currency_code) = Upper('".$rowsjournal[7]."')) or ($cum = 1 and 1 = 1))  ".
							" And ifNull(Journal.Journal_Type,'JV') <> 'CL' "; 
							
			if ($Module_BelongsToGroup == 1)				
				$querydetail= $querydetail." and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ";
			
			if ($curr == 1 && !(empty($fromcur))  )
			  $querydetail= $querydetail." and Upper(JournalDt.Currency_code) = Upper('".$fromcur."') ";
			if($Module_ConfirmJV == 1) $querydetail= $querydetail." and  ifnull(Journal_Confirmed,0) = 1 ";	
			if ($fromproject != 'null' || $fromcst != 'null' || $prtcostcentc == 1 || $prtprojectc == 1 || $prtcostcent == 1 || $prtproject == 1 || $prtcstjour == 1 || ($projectexist > 0 || $costcentexist > 0)) {  
				if ($parentprj == 1) {
					$querydetail= $querydetail." and upper(ifNull(CstJour.project_code,'-1')) like ifNull(concat(upper(".$fromproject."),'%'), upper(ifNull(CstJour.project_code,'-1'))) ".
											   " and upper(ifNull(CstJour.Costcent_Code,'-1')) like ifNull(concat(upper(".$fromcst."),'%'), upper(ifNull(CstJour.Costcent_Code,'-1'))) ";
				} else {
					$querydetail= $querydetail." and upper(ifNull(CstJour.project_code,'-1')) like ifNull(upper(".$fromproject."), upper(ifNull(CstJour.project_code,'-1'))) ".
											   " and upper(ifNull(CstJour.Costcent_Code,'-1')) like ifNull(upper(".$fromcst."), upper(ifNull(CstJour.Costcent_Code,'-1'))) ";
				}

			}
			
			if ($RowsDirCount > 1 && $k != 1)	
				$querydetail= $querydetail." And ifNull(Journal.Journal_Type,'JV') <> 'OP' ";
			  
			// adjusted by nadine 17-09-2018  
			if ($dtdate == 0 ) {
			  $querydetail= $querydetail." group by date_format(JournalDt.Journal_date,'%d/%m/%Y'),date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y'),";
			  if ($ledgeroption==1) {
					$querydetail= $querydetail."	JournalDt.Ledger_number, "; 
				} else if ($ledgeroption==2) {
					$querydetail= $querydetail."	ledger.document , ";
				} else if ($ledgeroption==3) {
					$querydetail= $querydetail."	if(ledger.document is null or ledger.document = '', JournalDt.Ledger_number , ledger.document) , ";
				}
				$querydetail= $querydetail." Journal.journal_type, JournalDt.Currency_code, Journaldt.Journaldt_dbcd  ";
			 } else if ($prtcstjour == 0 && ($projectexist > 0 || $costcentexist > 0)){
				  $querydetail= $querydetail." group by date_format(JournalDt.Journal_date,'%d/%m/%Y'),date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y'),";
				  if ($ledgeroption==1) {
						$querydetail= $querydetail."	JournalDt.Ledger_number, "; 
					} else if ($ledgeroption==2) {
						$querydetail= $querydetail."	ledger.document , ";
					} else if ($ledgeroption==3) {
						$querydetail= $querydetail."	if(ledger.document is null or ledger.document = '', JournalDt.Ledger_number , ledger.document) , ";
					}
					$querydetail= $querydetail." Ledger_name, ledger_type,JournalDt.Currency_code, Journaldt_Id  ";
			 }
			 
			if ($RowsDirCount > 1 && $j < $RowsDirCount)	
				$querydetail= $querydetail." Union ";
							
		}							
	}

	$querydetail= $querydetail." ) QDirMaster ";
	
							   //" Where DebitAmount !=0 Or CreditAmount !=0  ".
	// if ($ledgeroption==1) {
		if($OrdManNo == 1)
			$querydetail= $querydetail." Order By  Ledger_number, Manual_no , if($cum=0, Currency_code, null), OrderByDate, Journal_refgovernment,journaldt_id ";
		else
			$querydetail= $querydetail." Order By  Ledger_number, if($cum=0, Currency_code, null), OrderByDate, Journal_refgovernment,journaldt_id  ";
	// } else {
	//     $querydetail= $querydetail." Order By  Ledger_number, if($cum=0, Currency_code, null), OrderByDate, Journal_refgovernment,journaldt_id  ";
	// }

							
	// echo $querydetail;  
	
	$resultdetail=mysql_query($querydetail,$connection) or die(mysql_error());
	$CountRowsDt = mysql_num_rows($resultdetail);
	
	$break=0;
	
	 $PrevBalance  = 0;
	 $PrevBalance1 = 0;
	 $PrevBalance2 = 0;
	 $PrevBalanceCal = 0;
	 $Balance = 0;
	
	if ($prevbal == 1) {
		  $PrevBalance  = $rowsjournal[8];
		  $PrevBalance1 = $rowsjournal[9];
		  $PrevBalance2 = $rowsjournal[10];
		  $PrevBalanceCal = $rowsjournal[8];
	  }	
	 $VarCountRow=$VarCountRow+1;
	 //echo "xxxx".$prtwnac;
	 if (!isset($prtwnac)) {
		$prtwnac=0;
	}
	
		//echo "xxxxxxxxxxxxxx$CountRowsDt $prtwnac<br>";
	if (($CountRowsDt >0) or (($prtwnac==1)) 
	or (($CountRowsDt >=0) and ((abs($PrevBalance)>1) or (abs($PrevBalance1 )>4500) or (abs($PrevBalance2)>3) or (abs($PrevBalanceCal)>1)))
	//or (($CountRowsDt >=0) and ((abs($PrevBalance)>1) ))
	) {
	//if ($CountRowsDt > 0)  {
	// echo "x.".$CountRowsDt;

	
	 if ($VarCountRow!=$VarTotalCountRow) {
			$break=1;
			
		}
	
	//echo "<tr><td align='left'>";
echo "<table border=0>";
echo "<tr><td align='left'>";
	
if ($prtheader == 1){
	ShowReportHeader('Statement of Account','portrait', $connection);
} else {
	ShowReportTitle('Statement of Account','portrait', $connection);
}	
	
echo"</td></tr>";

  

print <<<HERE
<tr><td>
<table class='report-master' width="100%" border="0" align="center" >
<tr>
  <td width="7%" valign='top'><b>Date</b></td>
  <td width="5%"><b>From <br>To </b></td>
  <td width="15%">$dispfromdate <br> $disptodate</td>
  <td width="7%" valign='top'><b>Ledger</b></td>
  <td width="5%"><b>From <br>To </b></td>
  <td width="61%">$dispfromledger <br> $disptoledger </td>
</tr>
<tr>
  <td width="7%"><b>Shipment Ref</b></td>
  <td width="93%" colspan='5'>$dispfromproject </td>
</tr>
</table>
</td></tr>
<tr><td>
HERE;
$desc=200;
if ($prtproject == 0)
$desc=$desc+50;

if ($prtcostcent == 0)
$desc=$desc+50;
$desc=155;
$spancol = 9;
echo "<table  border='1' align='left' class='report-master' width='700'  style='table-layout:fixed; border-collapse:collapse;' cellpadding='0' cellspacing='0'>
      <col width=100>
	  <col width=50>
	  <col width=50>
	  <col width=75>
	  <col width=$desc>
	  <col width=100>
	  <col width=100>
	  <col width=100>
	  ";

	  if ($prtproject == 1)
	  { echo "<col width=80>";
		$spancol = $spancol + 1;
	  }
	  if ($prtprojectc == 1)
	  { echo "<col width=80>";
		$spancol = $spancol + 1;
	  }

if ($prtcostcent == 1)
    { echo "<col width=80>";
		$spancol = $spancol + 1;
	  }  
	  if ($prtcostcentc == 1)
    { echo "<col width=80>";
		$spancol = $spancol + 1;
	  }  



/*
print <<<HERE
<tr>
    <td colspan='8'><hr width='100%' color='black' size='2'></td>
</tr>
 
HERE;*/
 
 
	  echo "<tr>";
	  echo "<td colspan='$spancol'><table border='0' align='center' class='report-master' style='table-layout:fixed; width:700px' cellpadding='0' cellspacing='0' >
	  <col width=100>
	  <col width=50>
	  <col width=50>
	  <col width=60>
	  <col width=60>
	  <col width=120>
	  <col width=100><col width=90><col width=80>";
	  echo "<tr>";
	  echo "   <td ><b> Ledger No.</b></td>";
	  echo "   <td colspan='2'>". $rowsjournal[0] ."</td>";
	  echo "   <td align='center' ><b> Name </b></td>";
	  echo "   <td colspan='3'>". $rowsjournal[1] ."</td>";
	  echo "   <td ><b>Vat No.</b> ". $rowsjournal[11] ."</td>";
	
	  echo "</tr>"; 
	  echo "<tr>";
	  echo "   <td ><b> Phone </b></td>";
	  echo "   <td colspan='2'>". $rowsjournal[3] ."</td>";
	  
	  $PrevBalance  = 0;
	  $PrevBalance1 = 0;
	  $PrevBalance2 = 0;
	  $PrevBalanceCal = 0;
	  $Balance = 0;
	  
	  if ($prevbal == 1) {
		  $PrevBalance  = $rowsjournal[8];
		  $PrevBalance1 = $rowsjournal[9];
		  $PrevBalance2 = $rowsjournal[10];
		  $PrevBalanceCal = $rowsjournal[8];
	  }	  
	  
	  if ($currbase1 == 1 && $curr == 0 )
	    $PrevBalanceCal = $rowsjournal[9];
	  else if ($currbase2 == 1 && $curr == 0 )
	    $PrevBalanceCal = $rowsjournal[10];	
		
	  if ($prevbal == 1) 	
		$Balance = $PrevBalanceCal;
	  
	  
	  if ($cum == 0 ) {
		  echo "   <td align='center' ><b> Currency </b></td>";
		  echo "   <td align='center'>". $rowsjournal[7] ."</td>";
		  echo "   <td align='center'><b> Previous Balance </b></td>";
		  echo "   <td align='left'>". format_currency($PrevBalance, $DecimalBase) ."</td>";
		  //echo "   <td align='right'>&nbsp;</td>";
	  } else
        echo "   <td colspan='4'>&nbsp;</td>";	  
	  
	  echo "</tr>"; 
	  echo "<tr>";
	  echo "   <td ><b> Fax </b></td>";
	  echo "   <td colspan='2'>". $rowsjournal[4] ."</td>";
	  
	  if ($currbase1 == 1 ) {
		echo "   <td align='right'>&nbsp;</td>";
		echo "   <td >&nbsp;</td>";
		echo "   <td  align='center'><b> Previous Balance $Base1 </b></td>";
		echo "   <td  align='left'>". format_currency($PrevBalance1, $DecimalBase) ."</td>";
		//echo "   <td  align='right'>&nbsp;</td>";
	  } else
        echo "   <td colspan='4'>&nbsp;</td>";	  
		
	  echo "</tr>"; 
	  echo "<tr>";
	  echo "   <td ><b> Email </b></td>";
	  echo "   <td  colspan='2'>". $rowsjournal[5] ."</td>";
	  
	  if ($currbase2 == 1 ) {
	  echo "   <td  align='right'>&nbsp;</td>";
	  echo "   <td >&nbsp;</td>";
	  echo "   <td  align='center'><b> Previous Balance $Base2 </b></td>";
	  echo "   <td  align='left'>". format_currency($PrevBalance2, $DecimalBase) ."</td>";
	  //echo "   <td  align='right'>&nbsp;</td>";
	  } else
        echo "   <td colspan='4'>&nbsp;</td>";	  
		
	  echo "</tr>"; 
	  echo "<tr>";
	  echo "   <td ><b> Address </b></td>";
	  echo "   <td  colspan='6'>". $rowsjournal[6] ."</td>";
	  echo "</tr>"; 
	  
	  echo "<tr>";
	  if ($prtheader==1) {
		echo "   <td ><b>Salesman </b></td>";
		echo "   <td  colspan='1'>". $rowsjournal[12] ."</td>";
		echo "   <td  colspan='2'>". $rowsjournal[13] ."</td>";
	  } else {
         echo "   <td ><b>Salesman </b></td>";
		 echo "   <td  colspan='1'>". $rowsjournal[12] ."</td>";
	     echo "   <td colspan=3> &nbsp;</td>";
	  }
		echo "</tr>"; 
	     echo "   <td colspan=3>&nbsp;</td>";
		echo "<tr><td colspan='$spancol'>&nbsp;</td></tr></table></td></tr>";

		echo "
			<tr>";
				if($cum==0) 
				  echo "<td colspan='".($spancol-2)."' class='headborder' style='border-right:none;' align='right'><b>Currency</b>    ".$rowsjournal[7]." </td><td class='headborder' colspan='2' style='border-left:none;'></td>";
				else 
				  echo "<td colspan='".($spancol-2)."'  class='headborder' align='right' ><b>Currency</b>    ".$displaycurr."</td><td class='headborder' colspan='2' style='border-left:none;'></td>"; 
		  echo "</tr>	";
		  
	
			//echo"<thead>";
	echo "<tr>";
	  echo "<td colspan='15'>
	  <table border='0'  width=100% align='center'  cellpadding='0' cellspacing='0' >";
		echo"<thead><tr>
				<th  class='headborder'>Date </th>";

		if ($prtref == 1 && $dtdate == 1)	
			echo"<th class='headborder'>Ref</th>";
		else	
		    echo"<th class='headborder'></th>";
		
        if ($prtfolio == 1 && $dtdate == 1) 		
			echo"<th class='headborder'>Folio</th>";
		else
         	echo"<th class='headborder'></th>";	
			
		if ($prtvaluedate == 1)	
			echo"<th class='headborder'>Value Date </th>";
		else if ($prtjvtype == 1)
		    echo"<th class='headborder'>Type </th>";
		else   
            echo"<th class='headborder'></th>";		
			
		// && $dtdate == 1 removed by nadine 17-09-2018	
		if ($prtdesc == 1 )		
			echo"<th class='headborder'>Description</th>";
		else
            echo"<th class='headborder'></th>";		
			
		echo"	
			<th class='headborder'>Debit $displaycurr</th>
			<th class='headborder'>Credit $displaycurr</th>
			<th class='headborder'>Balance $displaycurr</th>";
			
			if($showman ==1){
			echo"<th class='headborder'>Manual No</th>";
			}
			
		if ($prtcostcentc == 1 || $prtprojectc == 1) { 
		 	if ($prtprojectc == 1)
				echo"<th class='headborder'>Shipment Ref Code</th>";
			if ($prtcostcentc == 1)
				echo"<th class='headborder'>Costcenter Code</th>";
		}	
	    if ($prtcostcent == 1 || $prtproject == 1) { 
		 	if ($prtproject == 1)
				echo"<th class='headborder'>Shipment Ref</th>";
			if ($prtcostcent == 1)
				echo"<th class='headborder'>Costcenter</th>";
		}
		
		if ($prtshowuser == 1)	 
			echo"<th class='headborder'>User</th>";
		echo"</tr>";
	
		echo"</thead>";
		//$i=2;
	}

	
	while($rowsdetail=mysql_fetch_row($resultdetail)){

		$SumCreditAmount = $SumCreditAmount + round($rowsdetail[16],$DecimalBase);
		$SumDebitAmount  = $SumDebitAmount  + round($rowsdetail[15],$DecimalBase);
		$Balance = $Balance + (round($rowsdetail[15],$DecimalBase) - round($rowsdetail[16],$DecimalBase));
		
		
		//style='border-width: 2px; border-style: solid; border-color: black; '
		
		echo "<tr>"; 
		echo "<td align='left' valign='top' class='headborder'>". $rowsdetail[1] ."</td>";
		
		if ($prtref == 1){
			//echo $rowsdetail[3];
			if($rowsdetail[3] == "PI" || $rowsdetail[3] == "PR" || $rowsdetail[3] == "SI" || $rowsdetail[3] == "SR" || $rowsdetail[3] == "PD" || $rowsdetail[3] == "AI" || $rowsdetail[3] == "DI" || $rowsdetail[3] == "DR" || $rowsdetail[3] == "SO")
			{
				//echo $_SESSION['useraccount'];
				//echo $_SESSION['dbName'];
				$query_language  = "select Language from ".$_SESSION['dbName_log'].".login where User_account = '".$_SESSION['useraccount']."' and Login_Schema = '".$_SESSION['dbName']."'";
				$result_language = mysql_query($query_language, $connection);
				$row_language    = mysql_fetch_array($result_language);
				if($Language != "Arabic")
				{
					$Language = "EN";
				}
				else
				{
					$Language = "AR";
				}
				
				$query_showlogo  = "select show_companylogo from setup";
				$result_showlogo = mysql_query($query_showlogo, $connection); 
				$row_showlogo    = mysql_fetch_array($result_showlogo);
				extract($row_showlogo);
				$MainId = "";
				//echo $rowsdetail[0]."<br>";
				if($rowsdetail[3] == "SI" || $rowsdetail[3] == "SR")
				{
					//echo "hi";
					if($Module_Delivery == 0)
					{
						$query_sales = "select Delivery_id as MainId from deliveries where journal_id = '".$rowsdetail[0]."'";
					}
					else
					{
						$query_sales  = "select Sale_id as MainId from sales where journal_id = '".$rowsdetail[0]."'";
					}
					
					//echo $query_sales."<br>";
					$result_sales = mysql_query($query_sales, $connection);
                    $row_sales    = mysql_fetch_array($result_sales);
                    extract($row_sales);					
				}
				else
					if($rowsdetail[3] == "DI" || $rowsdetail[3] == "DR")
					{
						$query_deliveries  = "select Delivery_id as MainId from deliveries where journal_id = '".$rowsdetail[0]."'";
						$result_deliveries = mysql_query($query_deliveries, $connection);
                        $row_deliveries    = mysql_fetch_array($result_deliveries);	
                        extract($row_deliveries);						
					}
					else
						if($rowsdetail[3] == "PI" || $rowsdetail[3] == "PR")
						{
							$query_purchases  = "select Purchase_id as MainId from purchases where journal_id = '".$rowsdetail[0]."'";
							$result_purchases = mysql_query($query_purchases, $connection); 
							$row_purchases    = mysql_fetch_array($result_purchases);
							extract($row_purchases);
						}
						else
							if($rowsdetail[3] == "PD")
							{
								$query_production  = "select Production_id as MainId from production where journal_id = '".$rowsdetail[0]."'";
								$result_production = mysql_query($query_production, $connection);
								$row_production    = mysql_fetch_array($result_production);
								extract($row_production);
							}
							else
								if($rowsdetail[3] == "AI")
								{
									$query_adjustment  = "select Adjustment_Id as MainId from adjustment where journal_id = '".$rowsdetail[0]."'";
									$result_adjustment = mysql_query($query_adjustment, $connection); 
									$row_adjustment    = mysql_fetch_array($result_adjustment);
									extract($row_adjustment);
								}
								else
								if($rowsdetail[3] == "SO")
								{
									$query_sorder  = "select sorder_id as MainId from journal where journal_id = '".$rowsdetail[0]."'";
									//echo $query_sorder;
									$result_sorder = mysql_query($query_sorder, $connection); 
									$row_sorder    = mysql_fetch_array($result_sorder);
									extract($row_adjustment);
								}
				
				echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"PrintPreview2('".$MainId."', '".$rowsdetail[3]."', '".$Language."', '".$show_companylogo."', '".$Module_Delivery."')\">". $rowsdetail[5] ."</a></td>";
			}
			else
				if($rowsdetail[3] == "JV" || $rowsdetail[3] == "EV" || $rowsdetail[3] == "EX" || $rowsdetail[3] == "AD" || $rowsdetail[3] == "OP") 
			 {
			if($FA_Journal== 1 && $FA_JournalMod== 1)
				echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"UpdateRecord('".$rowsdetail[0]."')\">". $rowsdetail[5] ."</a></td>";
			else if($FA_Journal== 1 && $FA_JournalMod== 0)
				echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"PrintPreview('".$rowsdetail[0]."')\">". $rowsdetail[5] ."</a></td>";
			else echo "<td align='left' valign='top' class='headborder'>". $rowsdetail[5] ."</td>";
			}
			else
                if($rowsdetail[3] == "CV"){
					$query_trans  = "select trans_id as TransId from trans where journal_id = '".$rowsdetail[0]."'";
					$result_trans = mysql_query($query_trans, $connection); 
					$row_trans    = mysql_fetch_array($result_trans);
					extract($row_trans);
					if($FA_CreditNote== 1 && $FA_CreditNoteMod== 1)
					  echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"UpdateRecord2('".$TransId."', '".$rowsdetail[3]."')\">". $rowsdetail[5] ."</a></td>";
				    else if(($FA_CreditNote== 0 ) || ($FA_CreditNote== 1 && $FA_CreditNoteMod== 0))
						  echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"PrintPreview3('".$TransId."', '".$rowsdetail[3]."')\">". $rowsdetail[5] ."</a></td>";
					else echo "<td align='left' valign='top' class='headborder'>". $rowsdetail[5] ."</td>";
				}
             else
                if($rowsdetail[3] == "DV"){
					$query_trans  = "select trans_id as TransId from trans where journal_id = '".$rowsdetail[0]."'";
					$result_trans = mysql_query($query_trans, $connection); 
					$row_trans    = mysql_fetch_array($result_trans);
					extract($row_trans);
					if($FA_DebitNote== 1 && $FA_DebitNoteMod== 1)
					  echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"
				  ('".$TransId."', '".$rowsdetail[3]."')\">". $rowsdetail[5] ."</a></td>";
				    else  if(($FA_DebitNote== 0) ||  ($FA_DebitNote== 1 && $FA_DebitNoteMod== 0) )
					  echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"PrintPreview3('".$TransId."', '".$rowsdetail[3]."')\">". $rowsdetail[5] ."</a></td>";
					else echo "<td align='left' valign='top' class='headborder'>". $rowsdetail[5] ."</td>";
				}				
			else
                if($rowsdetail[3] == "PV"){
					$query_trans  = "select trans_id as TransId from trans where journal_id = '".$rowsdetail[0]."'";
					$result_trans = mysql_query($query_trans, $connection); 
					$row_trans    = mysql_fetch_array($result_trans);
					extract($row_trans);
					if($FA_Payment== 1 && $FA_PaymentMod== 1)
					  echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"UpdateRecord2('".$TransId."', '".$rowsdetail[3]."')\">". $rowsdetail[5] ."</a></td>";
				    else if(($FA_Payment== 0 ) || ($FA_Payment== 1 && $FA_PaymentMod== 0))
					  echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"PrintPreview3('".$TransId."', '".$rowsdetail[3]."')\">". $rowsdetail[5] ."</a></td>";
					else echo "<td align='left' valign='top' class='headborder'>". $rowsdetail[5] ."</td>";
				}
		    else
                if($rowsdetail[3] == "RV"){
					$query_trans  = "select trans_id as TransId from trans where journal_id = '".$rowsdetail[0]."'";
					$result_trans = mysql_query($query_trans, $connection); 
					$row_trans    = mysql_fetch_array($result_trans);
					extract($row_trans);
					if($FA_Receipt== 1 && $FA_ReceiptMod== 1)
					  echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"UpdateRecord2('".$TransId."', '".$rowsdetail[3]."')\">". $rowsdetail[5] ."</a></td>";
				    else if(($FA_Receipt== 0 ) || ($FA_Receipt==1 && $FA_ReceiptMod==0))
					  echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"PrintPreview3('".$TransId."', '".$rowsdetail[3]."')\">". $rowsdetail[5] ."</a></td>";
					else echo "<td align='left' valign='top' class='headborder'>". $rowsdetail[5] ."</td>";
				}
				 else
                if($rowsdetail[3] == "JS"){
					$query_trans  = "select salesjv_id as TransId from salesjv where journal_id = '".$rowsdetail[0]."'";
					$result_trans = mysql_query($query_trans, $connection); 
					$row_trans    = mysql_fetch_array($result_trans);
					extract($row_trans);
					if($FA_SalesJV== 1 && $FA_SalesJVMod== 1)
					  echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"UpdateRecord3('".$TransId."')\">". $rowsdetail[5] ."</a></td>";
				    else if(($FA_SalesJV== 0 ) || ($FA_SalesJV==1 && $FA_SalesJVMod==0))
					  echo "<td align='left' valign='top' class='headborder'><a  onMouseOver=\"style.cursor='pointer'\" onclick=\"PrintPreview4('".$TransId."')\">". $rowsdetail[5] ."</a></td>";
					else echo "<td align='left' valign='top' class='headborder'>". $rowsdetail[5] ."</td>";
				}
				else
					{
						echo "<td align='left' valign='top' class='headborder'>". $rowsdetail[5] ."</td>";
					}
			}
		else
			echo "<td align='left' valign='top' class='headborder'></td>";	
			
		if ($prtfolio == 1) 
			echo "<td align='left' valign='top' class='headborder'>". $rowsdetail[4] ."</td>";
		else
			echo "<td align='left' valign='top' class='headborder'></td>";	
		
		if ($prtvaluedate == 1)		
			echo "<td align='center' valign='top' class='headborder'>". $rowsdetail[2] ."</td>";
		else if ($prtjvtype == 1)
			echo "<td align='center' valign='top' class='headborder'>". $rowsdetail[3] ."</td>";
		else 	
			echo "<td align='center' valign='top' class='headborder'></td>";
			

		if ($prtdesc == 1)			
			echo "<td align='left' valign='top' class='headborder'>". $rowsdetail[6] ." </td>";
		else 
			echo "<td align='left'  valign='top' class='headborder'>Opening Financial Year</td>";	
		
		if ($rowsdetail[15] != 0 || ($rowsdetail[15] == 0 && $rowsdetail[14] == 'D'))
		   echo "<td align='right' valign='top' class='headborder'>". number_format($rowsdetail[15], $DecimalBase) ."</td>";
		else
		   echo "<td align='right' valign='top' class='headborder'>&nbsp;</td>";
		   
		if ($rowsdetail[16] != 0 || ($rowsdetail[16] == 0 && $rowsdetail[14] == 'C'))
		   echo "<td align='right' valign='top' class='headborder'>". number_format($rowsdetail[16], $DecimalBase) ."</td>";
		else
		   echo "<td align='right' valign='top' class='headborder'>&nbsp;</td>";
		   
		echo "<td align='right' valign='top' class='headborder'>". format_currency($Balance, $DecimalBase) ."</td>";
				
		if($showman ==1){
			echo"<td valign='top' class='headborder'>".$rowsdetail[23]."</td>";
			}
		
		//echo "</tr>";
		
		
		if ($prtcostcentc == 1 || $prtprojectc == 1) { 
				
		   if ($prtprojectc == 1)
			 echo "<td align='left' valign='top'  class='headborder'>". $rowsdetail[11] ."</td>";
		   else
			 echo "<td align='left' valign='top'  class='headborder'>&nbsp;</td>";
			 
		  if ($prtcostcentc == 1)
			 echo "<td align='left' valign='top'  class='headborder'>". $rowsdetail[12] ."</td>";   
		  else
			 echo "<td align='left' valign='top'  class='headborder'>&nbsp;</td>";
		
		 // echo "</table></td>";
		  //echo"</tr>";
		}		
		
		if ($prtcostcent == 1 || $prtproject == 1) { 
		 //  echo "<tr class='subdivisions'>";
		//   echo "<td colspan='8' align='left' valign='top' class='headborder'><table width='690' border='0' align='left'   style='border-collapse:collapse;' >";		
		//   echo "<col width=340>
		//		 <col width=340>";
				
		   if ($prtproject == 1)
			 echo "<td align='left' valign='top'  class='headborder'>". $rowsdetail[18] ."</td>";
		   else
			 echo "<td align='left' valign='top'  class='headborder'>&nbsp;</td>";
			 
		  if ($prtcostcent == 1)
			 echo "<td align='left' valign='top'  class='headborder'>". $rowsdetail[19] ."</td>";   
		  else
			 echo "<td align='left' valign='top'  class='headborder'>&nbsp;</td>";
		
		 // echo "</table></td>";
		  //echo"</tr>";
		}
		
		if ($prtshowuser == 1)	 
			echo "<td align='center' valign='top'  class='headborder'>".$rowsdetail[22]."</td>";

		
		if ($checks == 1) {
		   
		   $querychecks= " select Chk_Number, Chk_Bank, Currency_code, Chk_Amount ".
						 " from ".$rowsdetail[21].".chkjour As chkjour ".
						 " where chkjour.Journaldt_Id = ".$rowsdetail[17];
			
		   $resultchecks=mysql_query($querychecks,$connection) or die(mysql_error());
		   while($rowschecks=mysql_fetch_row($resultchecks)){	
			 echo "<tr>"; 
			 echo "<td ></td>";
			 echo "<td ></td>";
			 echo "<td ></td>";
			 echo "<td ></td>";
			 echo "<td  align='left' valign='top' >Chk #: ".$rowschecks[0]."/".$rowschecks[1]."/".$rowschecks[2]." ".$rowschecks[3]."</td>";		
			 echo "<td ></td>";
			 echo "<td ></td>";
			 echo "<td ></td>";
			 echo "</tr>"; 
		  }
		
		}
		
		$querysubdetail = '';
		if ($dtjv == 1) {
		   if ($ledgeroption==1) {
				$querysubdetail=$querysubdetail. " select JournalDt.Ledger_number,";
		   } else {
		        $querysubdetail=$querysubdetail. " select ledger.document as Ledger_number,";
		   } 
		   
		   $querysubdetail=$querysubdetail." Ledger_name, concat(Journaldt_desc,ifnull(Journaldt_desc1,'')) as Journaldt_desc, JournalDt.Currency_code, Journaldt_dbcd, ".
							" if($curr = 0, if($currbase1 = 1, Journaldt_amount1, if($currbase2 = 1, Journaldt_amount2, Journaldt_amount)), Journaldt_amount) Amount ".
							" from ".$rowsdetail[21].".Journal As Journal ".
							" left join ".$rowsdetail[21].".JournalDt As JournalDt on JournalDt.Journal_id = Journal.Journal_id ".
							" left join ledger on JournalDt.Ledger_number = ledger.Ledger_number ".
							" Where Journal.Journal_Id = ".$rowsdetail[0].
							" And ((JournalDt.Ledger_number = '".$rowsdetail[7]."' and JournalDt.Journaldt_dbcd != '".$rowsdetail[14]."') Or (JournalDt.Ledger_number != '".$rowsdetail[7]."' and 1 = 1)) ".
							" And ifNull(Journal.Journal_Type,'JV') <> 'OP' ";
						 
			  $resultsubdetail=mysql_query($querysubdetail,$connection) or die(mysql_error());
							 
			  echo "<tr>"; 
			  echo "<td colspan='8' align='left' valign='top' class='headborder'><table width='700' border='0' align='left'   style='border-collapse:collapse;' class='report-master'>";		
			  echo "<col width=70>
					<col width=175>
					<col width=40>
					<col width=20>
					<col width=140>
					<col width=260>";
			
			  while($rowssubdetail=mysql_fetch_row($resultsubdetail)){	
				  echo "<tr class='subdivisions'>";
				  echo "<td valign='top' class='headborderdt'>".$rowssubdetail[0]."</td>";
				  echo "<td valign='top' class='headborderdt'>".$rowssubdetail[1]."</td>";
				  
				  if ($curr == 1)
					echo "<td valign='top' class='headborderdt'>".$rowssubdetail[3]."</td>";
				  else
					echo "<td valign='top' class='headborderdt'></td>";		  
					
				  echo "<td valign='top' class='headborderdt'>".$rowssubdetail[4]."</td>";
				  echo "<td valign='top' align='right' class='headborderdt'>".number_format($rowssubdetail[5], $DecimalBase)."</td>";
				  
				  echo "<td  colspan='3' class='headborderdt'></td>";
				  
				 
			  
				  echo "</tr>";
				  echo "<tr class='subdivisions'>";
				  echo "<td valign='top' class='headborderdt'></td>";
				  echo "<td valign='top' colspan='7' class='headborderdt'>".$rowssubdetail[2]."</td>";
				   
				  
				  echo "</tr>";
			  }

			  echo "</table></td>";
			  echo "</tr>"; 
		
		}
		echo "</tr>";
	}
	 
	
	$colss = 9;
	
	if ($prtcostcentc == 1 ) $colss++;
	if ($prtprojectc == 1) $colss++;
	if ($prtcostcentc == 1) $colss++;
	if ($prtprojectc == 1) 	$colss++;
	
	//if (($masterledger != '' && $masterledger!= $rowsjournal[0]) || ($masterledger== $rowsjournal[0] && $mastercurrency != $rowsjournal[7] && $cum==0) ) {
	 if ($CountRowsDt > 0) {   
		echo "<tr>"; 
		echo "<td colspan='$colss'><hr width='100%' color='black' size='1'></td>";
		echo "</tr>";
		
		
		
		echo "<tr>"; 
		echo "<td align='right' valign='top' colspan='5' ><b>TOTAL PERIOD </b>&nbsp;</td>";
		echo "<td align='right' valign='top' width=75   class='totalborder'>". number_format($SumDebitAmount, $DecimalBase) ."</td>";
		echo "<td align='right' valign='top' width=85   class='totalborder'>". number_format($SumCreditAmount, $DecimalBase) ."</td>";
		echo "<td align='right' valign='top' width=115 class='totalborder'>". format_currency(($SumDebitAmount-$SumCreditAmount), $DecimalBase) ."</td>";
		echo "</tr>";
		
		echo "<tr >"; 
		echo "<td align='right' valign='top' colspan='5' ><b>TOTAL </b>&nbsp;</td>";
		echo "<td align='right' valign='top' class='totalborder'>". number_format($SumDebitAmount, $DecimalBase) ."</td>";
		echo "<td align='right' valign='top' class='totalborder'>". number_format($SumCreditAmount, $DecimalBase) ."</td>";
		echo "<td align='right' valign='top' class='totalborder'>". format_currency($Balance, $DecimalBase) ."</td>";
		echo "</tr>";
		
		
		echo "<tr>"; 
		echo "<td colspan='8'>&nbsp;</td>";
		echo "</tr>";
		
		
	  	
		if ($prtwording == 1) {
			if($cum==0) $CurrencyCode = $rowsjournal[7];
			else $CurrencyCode = $displaycurr;
			
			if ($Balance != 0) {
				$queryalpha  = " SELECT Alpha_Num ('ENGLISH', '".$CurrencyCode."', ".abs($Balance).") As AlphaAmount FROM Dual ";
				$resultalpha = mysql_query($queryalpha,$connection) or die(mysql_error());
				$rowalpha=mysql_fetch_array($resultalpha);
				$TotalAmountLetter = $rowalpha[0];

				echo "<tr>"; 
				echo "<td colspan='8' align='left'>$TotalAmountLetter</td>";
				echo "</tr>";
			}
			echo "<tr>"; 
			echo "<td colspan='6' align='right'><b>Signature</b></td>";
			echo "<td colspan='2' align='left' style='border-bottom:1px solid black;'>&nbsp;</td>";
			echo "</tr>";
		}
	
		$SumCreditAmount = 0;
		$SumDebitAmount = 0;
		$Balance = 0;
	
		if ( $prtaging == 1 ) {
			echo "<tr>"; 
			echo "<td colspan='8'>";

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

			$ArrayPeriods = Array();
			$i = 0;
			while($rows=mysql_fetch_array($resultperiods)){
				$ArrayPeriods[$i] = $rows[0];
				$i += 1;
			}
				
		
			echo "<table width='100%' border='0' class='master' align='center' cellpadding='0' cellspacing='0'><tr>";
			
			$PrevRange = 0;
			for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
				echo "<th align='center' style='width:80px;font-size:7pt;border-left:1px solid black; border-top:1px solid black;'>".$PrevRange.'-'.$ArrayPeriods[$d]."</th>";
				$PrevRange = $ArrayPeriods[$d] + 1;
			}

			echo"		<th align='center' style='width:80px;font-size:7pt; border-left:1px solid black; border-right:1px solid black; border-top:1px solid black;'> >".($PrevRange - 1)." </th>";
			echo"   </tr>";
			echo"   <tr>";
			
			$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
			mysql_select_db($_SESSION['dbName'],$conn) or die("Could not find DB");
			
			if($currbase2 == 1) $CurrencyCode = $Base2;
			else $CurrencyCode = $Base1;
			
			$query_aging = "call AgingByLedgerAccount('".$rowsjournal[0]."',".$todate.",'".$CurrencyCode."','".$Base1."','".$Base2."',1,2)";
			$result_aging = mysql_query($query_aging,$conn) or die(mysql_error($conn));
			$rows_aging=mysql_fetch_row($result_aging);
			mysql_free_result($result_aging);
			mysql_close($conn);
			
			for ( $d = 0; $d < count($ArrayPeriods); $d += 1) {
				$j = 5 + $d;
				echo "<td align='right' valign='top' style='border-left:1px solid black;font-size:7pt; border-bottom:1px solid black; '>". format_currency($rows_aging[$j], $DecimalBase) ."</td>";
			}
			echo"	<td align='right' valign='top' style='border:1px solid black; border-top:0px; font-size:7pt;'>". format_currency($rows_aging[$j+1], $DecimalBase) ."</td>";
			echo"   </tr>";
			echo"	</table>";

			echo "</td></tr>";
		}
		
	} 		  			  
	echo "</table></td></tr>";
	$cols = 9;
	
	if ($prtcostcentc == 1 ) $cols++;
	if ($prtprojectc == 1) $cols++;
	if ($prtcostcentc == 1) $cols++;
	if ($prtprojectc == 1) 	$cols++;
	
	if ($break) {
            echo "<tr>"; 
            echo "<td colspan='$cols'><hr width='100%' color='black' size='1'></td>";
            echo "</tr>";
	}
		
	$i=$i+1;
	
	 

	 
	
	echo "</table></td></tr>";
	echo"</table>";
	//echo "</tD></tr>";
	if ($break) {
		echo "<tr><td colspan=15><div style='page-break-after:always;'></div></td></tr>";	
	}
}



echo"</tbody>";

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($amount < 0) 
        return "(".number_format(abs($amount),$DecimalBase).")"; 
 
    else return number_format($amount, $DecimalBase); 
} 

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

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

?>