<?php

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


print <<< HERE
<HTML>
<HEAD>
<TITLE> Aging Report </TITLE>

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

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


</style>




</HEAD>

<BODY>
HERE;
include("config.inc.php");

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

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


if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
$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']."' ".
			  " order by project.project_code";
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectexist   = mysql_num_rows($projectresult);



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



$dispfromproject  = $fromproject;
$dispfromcst = $fromcst;
$dispfromledger = $fromledger;
$disptoledger = $toledger;
$dispfromdate = $fromdate;
$disptodate = $todate;
$dispagingdate = $agingdate;

  
if ($curr == 'currency1'){
   $curr='null';  
   $displaycurr = '';
}   
else {
   $displaycurr = $curr;
   $curr="'".$curr."'";
}

if (empty($fromledger))   
   $fromledger = 'null';
else
   $fromledger = "'".$fromledger."'";   
   
if (empty($toledger))   
   $toledger = 'null';
else
   $toledger = "'".$toledger."'";      

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

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

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

if (empty($rangefrom))   
   $rangefrom = 'null';   
if (empty($rangeto))   
   $rangeto = 'null';      
   
if (empty($daysfrom))   
   $daysfrom = 'null';   
if (empty($rangeto))   
   $daysto = 'null';         


if ($accountno == 1) {
  $title = 'Suppliers';
  $tablename = 'Suppliers';
}  
else if ($accountno == 2) {
  $title = 'Clients';
  $tablename = 'Clients';
}  
else if ($accountno == 3)  {
  $title = 'Salesmen';
  $tablename = 'Clients';
}     

if ($lastbal == 1) {
  if($balorderby == 1)
     $OrderByCond = 'Q7.Balance Asc';
  else	 
     $OrderByCond = 'Q7.Balance Desc';

} else
{
   $OrderByCond = '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>Aging</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="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%" colspan='3'>$dispfromledger <br> $disptoledger </td>
</tr>
<tr>
  <td width="7%"><b>Project</b></td>
  <td width="20%" colspan='2'>$dispfromproject </td>
  <td width="12%" colspan='2'><b>Cost Center</b></td>
  <td width="20%" >$dispfromcst </td>
  <td width="10%" ><b>Up to date</b></td>
  <td width="31%" >$dispagingdate </td>
</tr>
<tr>
  <td colspan='18'><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=80>
	  <col width=200>
	  <col width=40>
	  <col width=100>
	  <col width=100>
	  <col width=100>
	  <col width=80>
<tr>
    <th>Account No.</th>
    <th>Account Name</th>
	<th>Cur.</th>
	<th align='right'>Total Amt</th>
	<th align='right'>Total Amt Paid</th>
	<th align='right'>Balance</th>	
	<th align='right'>Delay Days</th>
</tr>";


print <<<HERE
<tr>
    <td colspan='18'><hr width='100%' color='black' size='2'></td>
</tr>
 
HERE;
 
$MainCompanyName=explode('_',$_SESSION['dbName']);  
$QueryDir = " Select Concat(CompanyName, '_', DirYear) As DirSchema ".
			" From ".$_SESSION['dbLabel'].".Directories ".
			//" Where Date_Format(StartFinancialDate,'%Y') between ifNull(Date_Format(". $fromdate.",'%Y'),Date_Format(StartFinancialDate,'%Y')) and ifNull(date_format(". $todate.",'%Y'),date_format(StartFinancialDate,'%Y')) ".
			" Where ( Date_Format(StartFinancialDate,'%Y') >= ifNull(Date_Format(". $fromdate.",'%Y'),Date_Format(StartFinancialDate,'%Y')) ".
			"         or ".
			"         (Date_Format(StartFinancialDate,'%Y') < ifNull(Date_Format(". $fromdate.",'%Y'),Date_Format(StartFinancialDate,'%Y')) and Date_Format(EndFinancialDate,'%Y') = ifNull(date_format(". $todate.",'%Y'),date_format(EndFinancialDate,'%Y')) ) ".
			"       )".
			" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
			" Order By DirYear ";
$ResultDir=mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir1=mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir2=mysql_query($QueryDir,$connection) or die(mysql_error());
$RowsDirCount = mysql_num_rows($ResultDir);



    

if ($fromproject != 'null' || $fromcst != 'null') {
  $QueryCstJour ='CstJour.Cst_increment is null';
}  else
{
  $QueryCstJour ='True';
}

$result = mysql_query("start transaction", $connection);
$resultvars = mysql_query("set @PrevAmount :=0.0, @PrevBal:=0.0 ,@RecordNum:=0,@VarLedgerNumber:='x',@VarCurr:='x' ", $connection);

$queryjournal = '';

if ($accountno == 3) {
	$queryjournal=  " Select SalesmanCode As Ledger_number, SalesmanName As Ledger_name, BusinessType, ".
					" SalesmanCode, SalesmanName, Currency_code, Sum(PrevDebitAmount), Sum(PrevCreditAmount), ".
					" Sum(PrevBalance), Days, Sum(Balance) , ".
					" Sum(AgingAmount) As AgingAmount, Sum(DaysAmt) As TotDaysAmt, (Sum(DaysAmt)/Round(Sum(AgingAmount) - Sum(Balance))) As DelayDays, (Sum(AgingAmount) - Sum(Balance)) As TotAmtPaid , ".
					" RecordNum, Sum(AgingBalance), Sum(ActualBalance),OrdDate, Sum(CheckBalance), Sum(AccountBal)  ".
					" from (  ";
}

$queryjournal= $queryjournal.				
				" Select Ledger_number, Ledger_name, BusinessType, SalesmanCode, SalesmanName, Currency_code, ".
				" PrevDebitAmount, PrevCreditAmount, PrevBalance, Days, Balance , ".
				" Sum(AgingAmount) As AgingAmount, Sum(DaysAmt) As TotDaysAmt, (Sum(DaysAmt)/Round(Sum(AgingAmount) - Balance)) As DelayDays, (Sum(AgingAmount) - Balance) As TotAmtPaid, ".
				" RecordNum, AgingBalance, ActualBalance,OrdDate, CheckBalance, (Balance - CheckBalance) As AccountBal  ".
				" from (  ".
                " Select Q6.Ledger_number, Q6.Ledger_name, Q6.BusinessType, Q6.SalesmanCode, Q6.SalesmanName, Q6.Currency_code, ".
                " Q6.PrevDebitAmount, Q6.PrevCreditAmount, Q6.PrevBalance, Q6.Days,Q6.Balance, Q6.AgingAmount, Q6.DaysAmt, Q6.RecordNum, Q6.AgingBalance, ".
				" Q6.CheckBalance, (Q6.AgingBalance - Q6.AgingAmount) ActualBalance, Q6.OrdDate ".
				" from (  ".
				" Select Q5.JournalDt_ID, Q5.Ledger_number, Q5.Ledger_name, Q5.BusinessType, Q5.SalesmanCode, Q5.SalesmanName, ".
                " Q5.Currency_code, Q5.PrevDebitAmount, Q5.PrevCreditAmount, Q5.PrevBalance, ".
				" Q5.JournalDt_DBCD, Q5.JDate,Q5.OrdDate,Q5.Days,Q5.Balance,Q5.AgingAmount, Q5.DaysAmt, Q5.CheckBalance, ".
				" if((Q5.varledger!=Q5.Ledger_number Or Q5.varCurr!=Q5.Currency_code),@RecordNum:=1,@RecordNum:=(ifNull(@RecordNum,0)+1)) As RecordNum, ".
				" if((Q5.varledger!=Q5.Ledger_number Or Q5.varCurr!=Q5.Currency_code),@PrevBal:=0.0,0), ".
				" if($accountno = 1, if(Q5.Journaldt_dbcd = 'C', if(@RecordNum=1, @PrevBal:=Q5.Balance, @PrevBal:=(@PrevBal - @PrevAmount)), if(@RecordNum=1, @PrevBal:=Q5.Balance, @PrevBal:=@PrevBal)), if(Q5.Journaldt_dbcd = 'D', if(@RecordNum=1, @PrevBal:=Q5.Balance, @PrevBal:=(@PrevBal - @PrevAmount)),0)) As AgingBalance, ".
				" if($accountno = 1, if(Q5.Journaldt_dbcd = 'C', @PrevAmount:=Q5.AgingAmount, @PrevAmount:= @PrevAmount), if(Q5.Journaldt_dbcd = 'D', @PrevAmount:=Q5.AgingAmount, @PrevAmount:= @PrevAmount) ) ".
				" from (  ".
        		" Select Q4.JournalDt_ID, Q4.Ledger_number, Q4.Ledger_name, Q4.BusinessType, Q4.SalesmanCode, Q4.SalesmanName, ".
                " Q4.Currency_code, Q4.PrevDebitAmount, Q4.PrevCreditAmount, Q4.PrevBalance, ".
				" Q4.JournalDt_DBCD, Q4.JDate,Q4.OrdDate,Q4.Days,Q4.Amount AgingAmount, Q4.DaysAmt, Q4.RecordCount, Q4.Balance, Q4.CheckBalance, ".
				" @VarLedgerNumber varledger,@VarCurr varCurr,  ".
				" @VarLedgerNumber:=Q4.Ledger_number, @VarCurr:=Q4.Currency_code ".
				" from ".
				" ( ".
				" Select Q2.JournalDt_ID, Q1.Ledger_number, Q1.Ledger_name, Q1.BusinessType, Q1.SalesmanCode, Q1.SalesmanName, ".
                " Q1.Currency_code, Q1.PrevDebitAmount, Q1.PrevCreditAmount, (Q1.PrevDebitAmount - Q1.PrevCreditAmount) As PrevBalance, ".
				" Q2.JournalDt_DBCD, Q2.JDate,Q2.OrdDate,Q2.Days,Q2.Amount, (Q2.Days*Q2.Amount) As DaysAmt,Q1.RecordCount, (Q1.Balance + (Q1.PrevDebitAmount - Q1.PrevCreditAmount)) Balance,  ";

if ($riskbal == 1 && $accountno == 2)				
	$queryjournal =	$queryjournal." QCheckBal.CheckBalance As CheckBalance ";
else	
	$queryjournal =	$queryjournal." 0 As CheckBalance ";			
	
$queryjournal =	$queryjournal.	
				" from ".
				"(  ";
				

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


if ($RowsDirCount > 1) {
   $QueryDirSchema = " Select Ledger_number, Ledger_name, BusinessType, SalesmanCode, SalesmanName, Currency_code, ".
					 " Sum(PrevDebitAmount) As PrevDebitAmount, Sum(PrevCreditAmount) As PrevCreditAmount, Sum(RecordCount) As RecordCount, Sum(Balance) As Balance ".
					 " from ".
					 "(  ";
}					 

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

    $j = $j + 1;    
	if ($RowsDirCount > 1)
	   $DirSchema = $RowsDir[0];
	else
       $DirSchema = '';	
	   
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
	    $k = $k + 1;    
	
					if ($riskbal == 1 && $accountno == 2) 
					   $QueryDirSchema= $QueryDirSchema."  Select clients.Ledger_number, clients.Ledger_name, ";
					else
					   $QueryDirSchema= $QueryDirSchema."  Select JournalDt.Ledger_number, ledger.Ledger_name,  ";
			
					if ($accountno == 1) {
					  $QueryDirSchema= $QueryDirSchema."Null BusinessType, Null SalesmanCode, Null SalesmanName, ";
					}  
					else if ($accountno == 2) {
					  $QueryDirSchema= $QueryDirSchema."ifNull(Clients.Client_BusinessType,'None') BusinessType , Salesmen.Ledger_Number SalesmanCode,Salesmen.Ledger_Name SalesmanName, ";
					}  
					else if ($accountno == 3)  {
					  $QueryDirSchema= $QueryDirSchema."Null BusinessType, Salesmen.Ledger_Number SalesmanCode, Salesmen.Ledger_Name SalesmanName, ";
					}     
			   
				    $QueryDirSchema= $QueryDirSchema." if(upper($curr) = '".$Base1."', '".$Base1."', if(upper($curr) = '".$Base2."', '".$Base2."', JournalDt.Currency_code)) Currency_code , ";
					
					if ($fromproject != 'null' || $fromcst != 'null') {
				       $QueryDirSchema= $QueryDirSchema." sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) , if(Journaldt_dbcd = 'D', if(upper($curr) = '".$Base1."', Cstjour_amount1, if(upper($curr) = '".$Base2."', Cstjour_amount2, Cstjour_amount)), 0),0)) PrevDebitAmount, ".
													" sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) , if(Journaldt_dbcd = 'C', if(upper($curr) = '".$Base1."', Cstjour_amount1, if(upper($curr) = '".$Base2."', Cstjour_amount2, Cstjour_amount)), 0),0)) PrevCreditAmount, ".
													" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if($accountno = 1, if(Journaldt_dbcd = 'C',1,0), if(Journaldt_dbcd = 'D',1,0)) ,0)) As RecordCount, ".
													" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D', Cstjour_amount1, (-1)*Cstjour_amount1), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D', Cstjour_amount2, (-1)*Cstjour_amount2), if(Journaldt_dbcd = 'D', Cstjour_amount, (-1)*Cstjour_amount))),0) ) Balance ";
                    } else {
					   $QueryDirSchema= $QueryDirSchema." sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) , if(Journaldt_dbcd = 'D', if(upper($curr) = '".$Base1."', Journaldt_amount1, if(upper($curr) = '".$Base2."', Journaldt_amount2, Journaldt_amount)), 0),0)) PrevDebitAmount, ".
													" sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) , if(Journaldt_dbcd = 'C', if(upper($curr) = '".$Base1."', Journaldt_amount1, if(upper($curr) = '".$Base2."', Journaldt_amount2, Journaldt_amount)), 0),0)) PrevCreditAmount, ".
													" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if($accountno = 1, if(Journaldt_dbcd = 'C',1,0), if(Journaldt_dbcd = 'D',1,0)) ,0)) As RecordCount, ".
													" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D', Journaldt_amount1, (-1)*Journaldt_amount1), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D', Journaldt_amount2, (-1)*Journaldt_amount2), if(Journaldt_dbcd = 'D', Journaldt_amount, (-1)*Journaldt_amount))),0) ) Balance ";
					}
					
					$QueryDirSchema= $QueryDirSchema.
				    " from $DirSchema.JournalDt As JournalDt ".
				    " Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ";
				    //" Inner join $tablename on JournalDt.Ledger_number = $tablename.Ledger_number ";
					
					
					if ($riskbal == 1 && $accountno == 2) {
					   $QueryDirSchema= $QueryDirSchema."   Inner join ".
													"   ( select  clients.ledger_number, ledger.Ledger_name, clients.ledger_number accountnumber, Clients.Client_BusinessType, Clients.Salesmen_Code  ".
													"     from clients ".
													"     Inner join ledger on clients.Ledger_number = ledger.Ledger_number ".
													"     where Clients.Ledger_Number between ifNull(".$fromledger.",Clients.Ledger_Number) and ifNull(". $toledger.",Clients.Ledger_Number) ".
													"     And upper(ifNull(Clients.CostCenter_Code,'-1')) like ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))   ".
													"     union ".
                                                    "     select clients.ledger_number, ledger.Ledger_name, concat(acctypesetup.ledger_number,substr(clients.ledger_number,5,length(clients.ledger_number))) accountnumber, Clients.Client_BusinessType, Clients.Salesmen_Code ".
                                                    "     from clients ".
													"     Inner join ledger on clients.Ledger_number = ledger.Ledger_number ".
													"     left join acctype on substr(clients.ledger_number,1,4) = acctype.acctype_ledger ".
													"     left join acctypesetup on upper(acctypesetup.type_code) = upper(acctype.acctype_code) ".
													"     where Clients.Ledger_Number between ifNull(".$fromledger.",Clients.Ledger_Number) and ifNull(". $toledger.",Clients.Ledger_Number) ".
													"     And upper(ifNull(Clients.CostCenter_Code,'-1')) like ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))   ".
													"     And acctypesetup.ledger_number Is Not Null ".
													"    ) Clients on JournalDt.Ledger_Number = Clients.accountnumber  ";
													
					} else {
					   $QueryDirSchema= $QueryDirSchema." Inner join ledger on JournalDt.Ledger_number = ledger.Ledger_number ".
				              					        " Inner join $tablename on JournalDt.Ledger_number = $tablename.Ledger_number ";
					}
			   

					if ($accountno == 2 || $accountno == 3 )			   
					  $QueryDirSchema= $QueryDirSchema."  Left Join Salesmen As Salesmen On Clients.Salesmen_Code = Salesmen.Ledger_Number ";

                    if ($fromproject != 'null' || $fromcst != 'null') {
						$QueryDirSchema= $QueryDirSchema." Left outer Join $DirSchema.CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ";

						if ($projectexist > 0)
						  $QueryDirSchema= $QueryDirSchema." left join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
														 "			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
														 "             and (project_code is not null and project_code != '') ".
														 "			 ) PrjQry on CstJour.project_code like concat(PrjQry.project_code,'%') ";
                    }
													 
                    if ($riskbal == 1 && $accountno == 2)
					    $QueryDirSchema= $QueryDirSchema." where JournalDt.JournalDt_Amount1 <> 0 ";
					else {	
					    if ($accountno == 3) {
							$QueryDirSchema= $QueryDirSchema." where Salesmen.Ledger_number between ifNull(".$fromledger.",Salesmen.Ledger_number) and ifNull(". $toledger.",Salesmen.Ledger_number)  ".
														 " And JournalDt.JournalDt_Amount1 <> 0 ";
						} else {							 
						    $QueryDirSchema= $QueryDirSchema." where JournalDt.Ledger_number between ifNull(".$fromledger.",JournalDt.Ledger_number) and ifNull(". $toledger.",JournalDt.Ledger_number)  ".
														 " And JournalDt.JournalDt_Amount1 <> 0 ";
						}								 
					}
					
					
					if ($RowsDirCount > 1 && $k != 1)	
						$QueryDirSchema= $QueryDirSchema." And Journal.Journal_Type <> 'OP' ";
					
                    if ($fromproject != 'null' || $fromcst != 'null') {					
						$QueryDirSchema= $QueryDirSchema." 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 ($riskbal == 0 && $accountno == 2) {
                        $QueryDirSchema= $QueryDirSchema." And upper(ifNull(Clients.CostCenter_Code,'-1')) like ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))   ";
					}	
					
					if ($riskbal == 1 && $accountno == 2) {
                        $QueryDirSchema= $QueryDirSchema.				
										" group by clients.Ledger_number, clients.Ledger_name, Currency_code, BusinessType, SalesmanCode, SalesmanName ".
										" having RecordCount > 0 ";
					} else {				
						$QueryDirSchema= $QueryDirSchema.				
										" group by Ledger_number, Ledger_name, Currency_code, BusinessType, SalesmanCode, SalesmanName ".
										" having RecordCount > 0 ";
					}

                   	if ($RowsDirCount > 1 && $j < $RowsDirCount)	
                        $QueryDirSchema= $QueryDirSchema." Union ";
	}			
} // End Loop For Directories

if ($RowsDirCount == 1)	{
    if ($riskbal == 1 && $accountno == 2) {
        $QueryDirSchema= $QueryDirSchema." order by clients.Ledger_number, Currency_code ";
	} else {				
		$QueryDirSchema= $QueryDirSchema." order by Ledger_number, Currency_code ";
	}
} else {
    $QueryDirSchema= $QueryDirSchema.
					 " ) QDirMaster ".
					 " Group By Ledger_number, Ledger_name, Currency_code, BusinessType, SalesmanCode, SalesmanName ".
	                 " Order By Ledger_number, Currency_code ";
}	

	
//echo $QueryDirSchema; exit;					

$queryjournal= $queryjournal." ".$QueryDirSchema.
				 " ) As Q1 Inner Join  ". 
				 " (  ";
				 
$j = 0;				
$k = 0;
$QueryDirSchemaDt = '';

if ($RowsDirCount > 1) {
   $QueryDirSchemaDt = " Select JournalDt_ID, Ledger_number,  Currency_code, Journaldt_desc, Journal_folio, ".
					   " JournalDt_DBCD, JDate, OrdDate, Days, Amount ".
					   " from ".
					   "(  ";
}					 

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

    $j = $j + 1;    
	if ($RowsDirCount > 1)
	   $DirSchema = $RowsDir[0];
	else
       $DirSchema = '';	
    
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
		$k = $k + 1;    		
		$QueryDirSchemaDt= $QueryDirSchemaDt.   
				 "  Select JournalDt.JournalDt_ID, ";
				 
		//if ($accountno == 3)		 
			//$QueryDirSchemaDt= $QueryDirSchemaDt." Salesmen.Ledger_number, ";
		//else
			$QueryDirSchemaDt= $QueryDirSchemaDt." JournalDt.Ledger_number, ";
				 
		$QueryDirSchemaDt= $QueryDirSchemaDt.   		 
				 "  if(upper($curr) = '".$Base1."', '".$Base1."', if(upper($curr) = '".$Base2."', '".$Base2."', JournalDt.Currency_code)) Currency_code, ".
				 "  Journaldt_desc, Journal_folio, JournalDt_DBCD, if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate) JDate, Cast(if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate) As Date) As OrdDate, ".
                 "  DATEDIFF(date_format(".$agingdate.",'%Y-%m-%d'), date_format(if($dateoption = 1, JournalDt.Journal_date, JournalDt.Journaldt_ValueDate),'%Y-%m-%d')) Days, ";
				 
					if ($fromproject != 'null' || $fromcst != 'null') 
					    $QueryDirSchemaDt= $QueryDirSchemaDt."  if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D', Cstjour_amount1, (-1)*Cstjour_amount1), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D', Cstjour_amount2, (-1)*Cstjour_amount2), if(Journaldt_dbcd = 'D', Cstjour_amount, (-1)*Cstjour_amount))) Amount ";
					else
					    $QueryDirSchemaDt= $QueryDirSchemaDt."  if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D', Journaldt_amount1, (-1)*Journaldt_amount1), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D', Journaldt_amount2, (-1)*Journaldt_amount2), if(Journaldt_dbcd = 'D', Journaldt_amount, (-1)*Journaldt_amount))) Amount ";
					
					$QueryDirSchemaDt= $QueryDirSchemaDt."  from $DirSchema.JournalDt As JournalDt ".
														 "  Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ";
														 //"  Inner join $tablename on JournalDt.Ledger_number = $tablename.Ledger_number ".
					if ($accountno == 3 ) {			   
						$QueryDirSchemaDt= $QueryDirSchemaDt." Inner join Clients on JournalDt.Ledger_number = Clients.Ledger_number ".
															 " Left Join Salesmen As Salesmen On Clients.Salesmen_Code = Salesmen.Ledger_Number ";
					}	  
					  
				    if ($fromproject != 'null' || $fromcst != 'null') {	
					    $QueryDirSchemaDt= $QueryDirSchemaDt."  Left outer Join $DirSchema.CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ";
					  
						if ($projectexist > 0)
						  $QueryDirSchemaDt= $QueryDirSchemaDt." left join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
															   "			 where loginstk.user_account='".$_SESSION['useraccount']."' ".
															   "             and (project_code is not null and project_code != '') ".
															   "		    ) PrjQry1 on CstJour.project_code like concat(PrjQry1.project_code,'%') ";
						 
				    }	
					$QueryDirSchemaDt= $QueryDirSchemaDt." where date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d'))   ";

                    if ($fromproject != 'null' || $fromcst != 'null') {	
						$QueryDirSchemaDt= $QueryDirSchemaDt." 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 ($accountno != 3) 
					    $QueryDirSchemaDt= $QueryDirSchemaDt." And JournalDt.Ledger_Number between ifNull(".$fromledger.",JournalDt.Ledger_Number) and ifNull(". $toledger.",JournalDt.Ledger_Number) ";
					else
                        $QueryDirSchemaDt= $QueryDirSchemaDt." And Salesmen.Ledger_number between ifNull(".$fromledger.",Salesmen.Ledger_number) and ifNull(". $toledger.",Salesmen.Ledger_number)  ";					
					

					
					$QueryDirSchemaDt= $QueryDirSchemaDt." And (($accountno=1 and Journaldt_dbcd = 'C') or ($accountno!=1 and Journaldt_dbcd = 'D')) ";
														 
					if ($RowsDirCount > 1 && $k != 1)	
						$QueryDirSchemaDt= $QueryDirSchemaDt." And Journal.Journal_Type <> 'OP' ";
						
	                
					if ($RowsDirCount > 1 && $j < $RowsDirCount)	
                        $QueryDirSchemaDt= $QueryDirSchemaDt." Union ";
	}					
}


if ($RowsDirCount == 1)	{
    $QueryDirSchemaDt= $QueryDirSchemaDt." Order by Ledger_number, JournalDt.Currency_code, OrdDate Desc, Journal_folio Desc, JournalDt.JournalDt_ID Desc ";
	
} else {
    $QueryDirSchemaDt= $QueryDirSchemaDt.
					 " ) QDirDetail ".
					 " Order by Ledger_number, Currency_code, OrdDate Desc, Journal_folio Desc, JournalDt_ID Desc ";
}									 

//echo $QueryDirSchemaDt;exit;					 
$queryjournal= $queryjournal." ".$QueryDirSchemaDt.						
					") Q2 on Q2.Ledger_Number = Q1.Ledger_Number And Q2.Currency_Code = Q1.Currency_Code ";
					
if ($riskbal == 1 && $accountno == 2) {					
	$queryjournal= $queryjournal." Left Outer Join (  ";
				

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

//if ($RowsDirCount > 1) {
   $QueryCheckBal = " Select Ledger_number, Currency_code, Sum(CheckBalance) As CheckBalance ".
					" from ".
					" (  ";
//}					 

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

    $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;    
	
		$QueryCheckBal= $QueryCheckBal."  Select clients.Ledger_number, if(upper($curr) = '".$Base1."', '".$Base1."', if(upper($curr) = '".$Base2."', '".$Base2."', JournalDt.Currency_code)) Currency_code , ";
					
		if ($fromproject != 'null' || $fromcst != 'null') {
		    $QueryCheckBal= $QueryCheckBal." Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D', Journaldt_amount1, (-1)*Journaldt_amount1), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D', Journaldt_amount2, (-1)*Journaldt_amount2), if(Journaldt_dbcd = 'D', Journaldt_amount, (-1)*Journaldt_amount))),0) ) As  CheckBalance ";
        } else {
		    $QueryCheckBal= $QueryCheckBal." Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(upper($curr) = '".$Base1."', if(Journaldt_dbcd = 'D', Journaldt_amount1, (-1)*Journaldt_amount1), if(upper($curr) = '".$Base2."', if(Journaldt_dbcd = 'D', Journaldt_amount2, (-1)*Journaldt_amount2), if(Journaldt_dbcd = 'D', Journaldt_amount, (-1)*Journaldt_amount))),0) ) As CheckBalance ";
		}
					
		$QueryCheckBal= $QueryCheckBal." from $DirSchema.JournalDt As JournalDt ".
		                               " Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ";
				    
					
	    $QueryCheckBal= $QueryCheckBal."   Inner join ".
										"   ( select clients.ledger_number, concat(acctypesetup.ledger_number,substr(clients.ledger_number,5,length(clients.ledger_number))) accountnumber ".
                                        "     from clients ".
										"     Inner join ledger on clients.Ledger_number = ledger.Ledger_number ".
										"     left join acctype on substr(clients.ledger_number,1,4) = acctype.acctype_ledger ".
										"     left join acctypesetup on upper(acctypesetup.type_code) = upper(acctype.acctype_code) ".
										"     where Clients.Ledger_Number between ifNull(".$fromledger.",Clients.Ledger_Number) and ifNull(". $toledger.",Clients.Ledger_Number) ".
										"     And upper(ifNull(Clients.CostCenter_Code,'-1')) like ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))   ".
										"     And acctypesetup.ledger_number Is Not Null ".
										"    ) Clients on JournalDt.Ledger_Number = Clients.accountnumber  ";
													
					


        if ($fromproject != 'null' || $fromcst != 'null') {
			$QueryCheckBal= $QueryCheckBal." Left outer Join $DirSchema.CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ";

			if ($projectexist > 0)
			  $QueryCheckBal= $QueryCheckBal." left join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
											 "			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
											 "             and (project_code is not null and project_code != '') ".
											 "			 ) PrjQry on CstJour.project_code like concat(PrjQry.project_code,'%') ";
        }
													 
	    $QueryCheckBal= $QueryCheckBal." where JournalDt.JournalDt_Amount1 <> 0 ";
					
					
		if ($RowsDirCount > 1 && $k != 1)	
			$QueryCheckBal= $QueryCheckBal." And Journal.Journal_Type <> 'OP' ";
					
        if ($fromproject != 'null' || $fromcst != 'null') {					
			$QueryCheckBal= $QueryCheckBal." 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')))   ";
        }												 
					
					
        $QueryCheckBal= $QueryCheckBal." group by clients.Ledger_number, JournalDt.Currency_code ";

       	if ($RowsDirCount > 1 && $j < $RowsDirCount)	
            $QueryCheckBal= $QueryCheckBal." Union ";
	}			
} // End Loop For Directories

//if ($RowsDirCount == 1)	{
  //      $QueryCheckBal= $QueryCheckBal." order by clients.Ledger_number, JournalDt.Currency_code ";
//} else {
    $QueryCheckBal= $QueryCheckBal." ) QDirCheckBal ".
								   " Group By Ledger_number, Currency_code ".
								   " Order By Ledger_number, Currency_code ";
//}	
	
//echo $QueryCheckBal; exit;					

$queryjournal= $queryjournal." ".$QueryCheckBal.
					" ) As QCheckBal on QCheckBal.Ledger_Number = Q1.Ledger_Number And QCheckBal.Currency_Code = Q1.Currency_Code  ";
}					

$queryjournal= $queryjournal.					
					" Order By Q2.Ledger_Number, Q2.Currency_code, Q2.OrdDate Desc, Q2.Journal_folio Desc, Q2.JournalDt_ID Desc ".
				" ) As Q4  ".
				" Order By Q4.Ledger_Number, Q4.Currency_code, Q4.OrdDate Desc, Q4.JournalDt_ID Desc ".
				" ) As Q5 ".
				" Order By Q5.Ledger_Number, Q5.Currency_code, Q5.OrdDate Desc, Q5.JournalDt_ID Desc  ) Q6  ".
				" where (($exclude=1 and Q6.AgingBalance Not Between ifNull($rangefrom,0) and ifNull($rangeto,0)) or ($exclude=0 and 1=1)) ".
				" And (($accountno=1 and Q6.AgingBalance < 0) or ($accountno!=1 and Q6.AgingBalance > 0))  ";
				
				$queryjournal= $queryjournal." ) Q7 Group By Ledger_number, Ledger_name, Currency_code ".
											 " Having (($deldays=1 and DelayDays Between ifNull($daysfrom,0) and ifNull($daysto,0)) or ($deldays=0 and 1=1)) ";
				
				
				if ($accountno == 2 && $groupby == 2)
					$queryjournal= $queryjournal." order by Q7.SalesmanCode, if($orderby=1, Q7.Ledger_number, Q7.Ledger_Name), $OrderByCond, Q7.Currency_code, Q7.OrdDate  ";
				else  if ($accountno == 2 && $groupby == 3) 
					$queryjournal= $queryjournal." order by Q7.BusinessType, if($orderby=1, Q7.Ledger_number, Q7.Ledger_Name), $OrderByCond, Q7.Currency_code, Q7.OrdDate  ";
				else  if ($accountno == 3) 
					$queryjournal= $queryjournal." order by Q7.SalesmanCode, if($orderby=1, Q7.Ledger_number, Q7.Ledger_Name), $OrderByCond, Q7.Currency_code, Q7.OrdDate  ";
				else  
					$queryjournal= $queryjournal." order by if($orderby=1, Q7.Ledger_number, Q7.Ledger_Name), $OrderByCond, Q7.Currency_code, Q7.OrdDate  ";
				  
if ($accountno == 3) {				
	$queryjournal= $queryjournal." ) Q8 Group By SalesmanCode, SalesmanName, Currency_code ";
	
}
	
//echo $queryjournal;exit;

$MasterGroup = '';
$MainRecord = '';
$SumBalance = 0;
$SumTotalAmt = 0;
$SumTotalAmtPaid = 0;


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

    if (($MasterGroup == '' || $MasterGroup!= $rowsjournal[5]) && (($accountno == 2 && $groupby == 2) ) )    {
	    
		if ($MasterGroup != '' && $MasterGroup!= $rowsjournal[5]) {
			echo "<tr class='totals'>"; 
			echo "<td align='right' valign='top' colspan='2'> Total </td>";
			echo "<td align='right' valign='top'>&nbsp;</td>";
			echo "<td align='right' valign='top'>". format_currency($SumTotalAmt, 0) ."</td>";
			echo "<td align='right' valign='top'>". format_currency($SumTotalAmtPaid, 0) ."</td>";
			echo "<td align='right' valign='top'>". format_currency($SumBalance, 0) ."</td>";
			echo "<td align='right' valign='top'>&nbsp;</td>";
			echo "</tr>";
			
			echo "<tr>"; 
			echo "<td colspan='18'>&nbsp;</td>";
			echo "</tr>"; 
			
			$SumBalance = 0;
			$SumTotalAmt = 0;
			$SumTotalAmtPaid = 0;
				
		}
		
		echo "<tr>"; 
		echo "<td colspan='18'><table class='group' width='100%' border='0' align='center' cellpadding='0' cellspacing='0'>";
		echo "<tr>";
		echo "   <td width='10%'> Group by Salesman</td>";
		echo "   <td width='7%'>". $rowsjournal[5] ."</td>";
		echo "   <td width='83%'>". $rowsjournal[6] ."</td>";
		echo "</tr>"; 
		echo "</table></td></tr>";
		
		echo "<tr>"; 
		echo "<td colspan='18'>&nbsp;</td>";
		echo "</tr>"; 
		
		$MasterGroup= $rowsjournal[5];
	  	
	}
	if (($MasterGroup == '' || $MasterGroup!= $rowsjournal[4]) && $accountno == 2 && $groupby == 3)    {
	    
		if ($MasterGroup != '' && $MasterGroup!= $rowsjournal[4]) {
			echo "<tr class='totals'>"; 
			echo "<td align='right' valign='top' colspan='2'> Total </td>";
			echo "<td align='right' valign='top'>&nbsp;</td>";
			echo "<td align='right' valign='top'>". format_currency($SumTotalAmt, 0) ."</td>";
			echo "<td align='right' valign='top'>". format_currency($SumTotalAmtPaid, 0) ."</td>";
			echo "<td align='right' valign='top'>". format_currency($SumBalance, 0) ."</td>";
			echo "<td align='right' valign='top'>&nbsp;</td>";
			echo "</tr>";
			
			echo "<tr>"; 
			echo "<td colspan='18'>&nbsp;</td>";
			echo "</tr>"; 
			
			$SumBalance = 0;
			$SumTotalAmt = 0;
			$SumTotalAmtPaid = 0;
				
		}
		
		echo "<tr>"; 
		echo "<td colspan='18'><table class='group' width='100%' border='0' align='center' cellpadding='0' cellspacing='0'>";
		echo "<tr>";
		echo "   <td width='12%'> Group by Business Type</td>";
		echo "   <td width='88%'>". $rowsjournal[4] ."</td>";
		echo "</tr>"; 
		echo "</table></td></tr>";
		
		echo "<tr>"; 
		echo "<td colspan='18'>&nbsp;</td>";
		echo "</tr>";
		
		$MasterGroup= $rowsjournal[4];
	  	
	}
   

		
	echo "<tr>"; 
	echo "<td align='left' valign='top'>". $rowsjournal[0] ."</td>";
	echo "<td align='left' valign='top'>". $rowsjournal[1] ."</td>";
	echo "<td align='center' valign='top'>". $rowsjournal[5] ."</td>";
	echo "<td align='right' valign='top'>". format_currency($rowsjournal[11], $DecimalBase) ."</td>";
	echo "<td align='right' valign='top'>". format_currency($rowsjournal[14], $DecimalBase) ."</td>";
	echo "<td align='right' valign='top'>". format_currency($rowsjournal[10], $DecimalBase) ."</td>";
	echo "<td align='right' valign='top'>". number_format($rowsjournal[13], $DecimalBase) ."</td>";
	echo "</tr>";
	
	echo "<tr>";
	echo "<td colspan='18'><hr width='100%' color='black' size='1'></td>";
	echo "</tr>";
	
	
	$SumTotalAmt = $SumTotalAmt + $rowsjournal[11];
	$SumTotalAmtPaid = $SumTotalAmtPaid + $rowsjournal[14];
	$SumBalance = $SumBalance + $rowsjournal[10];
		
	
}

$result = mysql_query("rollback", $connection);

// Totals For A Group
if ($accountno == 2 && ($groupby == 2 || $groupby == 3)) {

	echo "<tr class='totals'>"; 
	echo "<td align='right' valign='top' colspan='2'> Total </td>";
	echo "<td align='right' valign='top'>&nbsp;</td>";
	echo "<td align='right' valign='top'>". format_currency($SumTotalAmt, 0) ."</td>";
	echo "<td align='right' valign='top'>". format_currency($SumTotalAmtPaid, 0) ."</td>";
	echo "<td align='right' valign='top'>". format_currency($SumBalance, 0) ."</td>";
	echo "<td align='right' valign='top'>&nbsp;</td>";
	echo "</tr>";
			
}
		
// Totals Option CLients Group By None Or Option Of Suppliers And Salesmen
if ($accountno == 1 || $accountno == 3 || ($accountno == 2 && $groupby == 1)) {
	
	echo "<tr>";
	echo "  <td colspan='18'>&nbsp;</td>";
	echo "</tr>";
	
	echo "<tr class='totals'>"; 
	echo "<td align='right' valign='top' colspan='2'> Total </td>";
	echo "<td align='right' valign='top'>&nbsp;</td>";
	echo "<td align='right' valign='top'>". format_currency($SumTotalAmt, 0) ."</td>";
	echo "<td align='right' valign='top'>". format_currency($SumTotalAmtPaid, 0) ."</td>";
	echo "<td align='right' valign='top'>". format_currency($SumBalance, 0) ."</td>";
	echo "<td align='right' valign='top'>&nbsp;</td>";
	echo "</tr>";

}

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

function current_server_time($connection){

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

  return $now;
}

function explodeword($date)
{

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

function format_currency($amount, $DecimalBase) { 

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


print <<< HERE

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

?>