<?php
header("Content-type: text/html; charset=windows-1256");

include("config.inc.php");

require_once('Spreadsheet/Excel/Writer.php');

session_start();
if($_SESSION['dbName']==""){
header("location:../index.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']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");


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

$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  From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


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



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

 /* 
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."'";      

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

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



if (empty($fromacctype))   
   $fromacctype = 'null';
else
   $fromacctype = "'".$fromacctype."'"; 
   
if (empty($frombustype))   
   $frombustype = 'null';
else
   $frombustype = "'".$frombustype."'";     

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

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


   
//Creating a workbook
$workbook = new Spreadsheet_Excel_Writer();
$workbook->setVersion(8);
 
//Sending HTTP headers
$workbook->send('Exp_TrialBalanceComparator.xls');
 
//Creating a worksheet
$worksheet=&$workbook->addWorksheet('TrialBalanceComparator');
$worksheet->setInputEncoding('windows-1256'); 
$worksheet->setLandscape();
 
//set all columns same width
$columnWidth = 10;


//Title Format 
$sheetTitleFormat =& $workbook->addFormat(array('bold'=>1,
  'size'=>10));

//Column Title Format  
$columnTitleFormat =& $workbook->addFormat(array('bold'=>1,
  'top'=>1,
  'bottom'=>1 ,
  'size'=>15,
  'color'=>0x0A,
  ));
  
 
  
// Regular Format
$regularFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'left', 
  'textWrap'=>1 
  ));

// Bold Title Format  
$TitleFormat =& $workbook->addFormat(array('size'=>10,
  'align'=>'left', 
  'bold'=>'1', 
  ));

$TitleFormat1 =& $workbook->addFormat(array('size'=>12,
  'align'=>'left', 
  'bold'=>'1', 
  ));
  
$regularleftFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'left'  ));
$regularrightFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'right'  ));  
  
$boldleftFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'left'  ,
  'valign'=>'top'  ,
  'bold'=>1
  ));  
$boldrightFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'right'  ,
  'bold'=>1
  )); 
$boldcenterFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'center'  ,
  'valign'=>'top'  ,
  'bold'=>1
  ));   
 
//$worksheet->setNumFormat('(0.00)');
 
//Elie and Tarek Format


$regularFormatNum1 =& $workbook->addFormat(array('size'=>9,
  'align'=>'left', 
  'textWrap'=>1 
  )); 
$regularleftFormatNum1 =& $workbook->addFormat(array('size'=>9,
  'align'=>'left'  ));
$regularrightFormatNum1 =& $workbook->addFormat(array('size'=>9,
  'align'=>'right'  ));  
  
$regularFormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$regularleftFormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');
$regularrightFormatNum1->setNumFormat('_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)');

//Elie And  Tarek Formt 
$worksheet->setColumn (0, 0, 11);
$worksheet->setColumn (1, 1, 33);
$worksheet->setColumn (4, 15, 14.5);

// Merge cells from row 0, col 0 to row 2, col 2
$worksheet->setMerge(4, 2, 4, 3);
$worksheet->setMerge(5, 2, 5, 3);

$worksheet->write(1, 0, $CompanyName, $TitleFormat);
$worksheet->write(1, 5, "Trial Balance", $TitleFormat1);
$worksheet->write(1, 7, "Printed Date:", $TitleFormat);
$worksheet->write(1, 8, $printdate[2]."/".$printdate[1]."/".$printdate[0], $TitleFormat);
$worksheet->write(2, 7	, "Time:", $TitleFormat);
$worksheet->write(2, 8, $dt[1]." ".$dt[2], $TitleFormat);
					
				
$worksheet->write(4, 0, "Date", $TitleFormat);
$worksheet->write(4, 1, "From", $TitleFormat);
$worksheet->write(4, 2, $dispfromdate, $regularFormat);

$worksheet->write(4, 5, "Ledger", $TitleFormat);
$worksheet->write(4, 6, "From", $TitleFormat);
$worksheet->write(4, 7, $dispfromledger, $regularFormat);
			
$worksheet->write(5,1,"To", $TitleFormat);  
$worksheet->write(5,2,$disptodate, $regularFormat);  
$worksheet->write(5,6,"To", $TitleFormat);  
$worksheet->write(5,7,$disptoledger, $regularFormat);

$dbNames = $_GET['dbNames'];
$dbNames = explode(',',$dbNames);


$queryjournal = "SELECT Ledger_number, Ledger_name, Document, Ledger_grpdet, Ledger_RequiredDetail, CvCurrBase1, CvCurrBase2,".
						"Project_code, project_name, Costcent_Code, costcent_name, Currency_code, ";
$i = 1;
while($i<=sizeof($dbNames)){
    //echo $querydb;
    $queryjournal = $queryjournal.  " SUM(PrevDebitAmount".$i."), ".
                                    " SUM(PrevDebitAmountBase1".$i."), ".
                                    " SUM(PrevDebitAmountBase2".$i."), ".
                                    " SUM(PrevCreditAmount".$i."), ".
                                    " SUM(PrevCreditAmountBase1".$i."), ".
                                    " SUM(PrevCreditAmountBase2".$i."), ".
                                    " SUM(PrevBalance".$i."), ".
                                    " SUM(PrevBalanceBase1".$i."), ".
                                    " SUM(PrevBalanceBase2".$i."), ".
                                    " SUM(DebitAmount".$i."), ".
                                    " SUM(DebitAmountBase1".$i."), ".
                                    " SUM(DebitAmountBase2".$i."), ".
                                    " SUM(CreditAmount".$i."), ".
                                    " SUM(CreditAmountBase1".$i."), ".
                                    " SUM(CreditAmountBase2".$i."), ".
                                    " SUM(Balance".$i."), ".
                                    " SUM(BalanceBase1".$i."), ".
                                    " SUM(BalanceBase2".$i."), ".
                                    " SUM(ActBalance".$i."), ".
                                    " SUM(ActBalanceBase1".$i."), ".
                                    " SUM(ActBalanceBase2".$i."), ".
                                    " SUM(Ord".$i."), ".
                                    " SUM(CountPrj".$i."), ".
                                    " SUM(CountCst".$i.")";
    if($i<sizeof($dbNames)){
        $queryjournal .= ", "; 
    }
    $i += 1;
}

$queryjournal .= "FROM (";
$querydetail = "";
$i = 1;
	while($i<=sizeof($dbNames)){
		$dbNameUsed = $dbNames[$i-1];
		$dbYear = explode("_",$dbNameUsed);
		$dbYear[1] = substr($dbYear[1],3);
		$trim = explode('-',$fromdate);
		$fromdate = "'$dbYear[1]"."-"."$trim[1]"."-"."$trim[2]";
		$trim = explode('-',$todate);
		$todate = "'$dbYear[1]"."-"."$trim[1]"."-"."$trim[2]";
		// echo $dbNameUsed."//".$dbYear[1]."//".$fromdate."//".$todate;
		$querydetail = "";
	if ($fromproject != 'null' || $fromcst != 'null' || $excludecst != 'null' || $prtprjcst == 1 || $prtprjcst2 == 1) {
	
		$querydetail= $querydetail." select Ledger.Ledger_number, Ledger.Ledger_name, Ledger.Ledger_grpdet, Ledger.Ledger_RequiredDetail,  ".
					" if($currbase1 = 1, '".$Base1."', Null) CvCurrBase1, if($currbase2 = 1, '".$Base2."', Null) CvCurrBase2, ".
					" JournalDt.Document,ifNull(CstJour.Project_code, '{None}') Project_code, ifNull(project.project_name, '{None}') project_name,ifNull(CstJour.Costcent_Code, '{None}') Costcent_Code, ifNull(costcent.costcent_name, '{None}') costcent_name,if($curr!=0, JournalDt.Currency_code, null) Currency_code,  ".
					" 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(CstJour.Cst_increment is not null, Cstjour_amount, 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 = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), 0),0)) PrevDebitAmountBase1, ".
					" 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(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), 0),0)) PrevDebitAmountBase2, ".
					" 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(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount) , 0),0)) PrevCreditAmount, ".
					" 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(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), 0),0)) PrevCreditAmountBase1, ".
					" 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(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), 0),0)) PrevCreditAmountBase2, ".
					" 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(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount)),0) ) PrevBalance, ".
					" 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(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1)),0) ) PrevBalanceBase1, ".
					" 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(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2)),0) ) PrevBalanceBase2, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount) , 0),0)) DebitAmount, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), 0),0)) DebitAmountBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), 0),0)) DebitAmountBase2, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', if(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount) , 0),0)) CreditAmount, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), 0),0)) CreditAmountBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), 0),0)) CreditAmountBase2, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount, Journaldt_amount)),0)) Balance, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount1, Journaldt_amount1)),0)) BalanceBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2), (-1)*if(CstJour.Cst_increment is not null, Cstjour_amount2, Journaldt_amount2)),0)) BalanceBase2, ".
					" Sum(if(CstJour.Project_code is null,0,1)) countprj, Sum(if(CstJour.Costcent_Code is null,0,1)) countcst ";


	} else {
		$querydetail= $querydetail." select Ledger.Ledger_number, Ledger.Ledger_name, Ledger.Ledger_grpdet, Ledger.Ledger_RequiredDetail,  ".
					" if($currbase1 = 1, '".$Base1."', Null) CvCurrBase1, if($currbase2 = 1, '".$Base2."', Null) CvCurrBase2, ".
					" JournalDt.Document,Null Project_code, Null project_name,Null Costcent_Code, Null costcent_name, if($curr!=0, JournalDt.Currency_code, null) Currency_code,  ".
					" sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', 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 = 'D', Journaldt_amount1, 0),0)) PrevDebitAmountBase1, ".
					" sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount2, 0),0)) PrevDebitAmountBase2, ".
					" sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', Journaldt_amount , 0),0)) PrevCreditAmount, ".
					" sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', Journaldt_amount1, 0),0)) PrevCreditAmountBase1, ".
					" sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', Journaldt_amount2, 0),0)) PrevCreditAmountBase2, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount, (-1)*Journaldt_amount),0) ) PrevBalance, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount1, (-1)*Journaldt_amount1),0) ) PrevBalanceBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount2, (-1)*Journaldt_amount2),0) ) PrevBalanceBase2, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount , 0),0)) DebitAmount, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount1, 0),0)) DebitAmountBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount2, 0),0)) DebitAmountBase2, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', Journaldt_amount , 0),0)) CreditAmount, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', Journaldt_amount1, 0),0)) CreditAmountBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'C', Journaldt_amount2, 0),0)) CreditAmountBase2, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount, (-1)*Journaldt_amount),0)) Balance, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount1, (-1)*Journaldt_amount1),0)) BalanceBase1, ".
					" Sum(if(date_format(JournalDt.Journal_date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(JournalDt.Journal_date,'%Y-%m-%d')), if(Journaldt_dbcd = 'D', Journaldt_amount2, (-1)*Journaldt_amount2),0)) BalanceBase2, ".
					" Sum(0) countprj, Sum(0) countcst ";
					
	}			   
	

	$querydetail= $querydetail.
				" from ".$dbNameUsed.".JournalDt ".
				" Left Outer join ".$dbNameUsed.".Ledger on JournalDt.Ledger_number = Ledger.Ledger_number ".
				" Inner join ".$dbNameUsed.".Journal on JournalDt.Journal_id = Journal.Journal_id ";

					//maroun
					if ($options==4)
					$querydetail= $querydetail." inner join ".$dbNameUsed.".Clients on Clients.Ledger_number = JournalDt.Ledger_Number ";				
					if ($options==4)
					{
					$querydetail= $querydetail."	And upper(ifNull(Clients.CostCenter_Code,'-1')) like ifNull(upper(".$cltcst."), upper(ifNull(Clients.CostCenter_Code,'-1')))   ".
					"   And upper(ifNull(Clients.Project_Code,'-1')) like ifNull(upper(".$cltprj."), upper(ifNull(Clients.Project_Code,'-1')))   ";
					}
					
							//maroun
							if (($options == 4 ) && $projectmasterexist > 0) {	
							$querydetail= $querydetail." inner join ( select distinct Masterproject from ".$_SESSION['dbLabel'].".loginstk ".
															"			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
															"             and (Masterproject is not null and Masterproject != '') ".
															"			 ) PrjMasterQry on Clients.project_code like concat(PrjMasterQry.Masterproject,'%') ";
							
							}
				
							//maroun
							if (($options == 4 ) && $costcentermasterexist > 0) {	
							$querydetail= $querydetail." inner join ( select distinct Mastercostcenter from ".$_SESSION['dbLabel'].".loginstk ".
															"			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
															"             and (Mastercostcenter is not null and Mastercostcenter != '') ".
															"			 ) CstMasterQry on Clients.CostCenter_Code like concat(CstMasterQry.Mastercostcenter,'%') ";
							
							}
							//maroun
						if (($options == 4) && $salesmenexist > 0) {
							$querydetail = $querydetail . " 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 ($fromproject != 'null' || $fromcst != 'null' || $excludecst != 'null' || $prtprjcst == 1  || $prtprjcst2 == 1) {
		$querydetail = $querydetail." Left outer Join ".$dbNameUsed.".CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ".
									" Left outer Join ".$dbNameUsed.".project on project.Project_code = Cstjour.Project_code ".
									" Left outer Join ".$dbNameUsed.".costcent on costcent.Costcent_Code = Cstjour.Costcent_Code ";

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

	if ($options == 7) 
	$querydetail= $querydetail." Inner Join ".$dbNameUsed.".acctypesetup on JournalDt.Ledger_number like concat(acctypesetup.Ledger_Number,'%') ";
	
	if ($options == 8)
		$querydetail= $querydetail." Inner Join ".$dbNameUsed.".Clients on Clients.Ledger_number = JournalDt.Ledger_Number ";				 
		
	/*if ($ledgerexist > 0) {
		$querydetail = $querydetail." 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 JournalDt.Ledger_Number like concat(Q3.ledger_number,'%') ) or ($ledgerinclude = 0 and JournalDt.Ledger_Number Not like concat(Q3.ledger_number,'%') ) or JournalDt.Ledger_Number is null) ";	
	}*/

	$querydetail= $querydetail.  
					" where ( ($prtdoc = 0 and ledger.Ledger_number between ifNull(".$fromledger.",ledger.Ledger_number) and ifNull(". $toledger.",ledger.Ledger_number) ) or ".
					"         ($prtdoc = 1 and ledger.Document between ifNull(".$fromledger.",ledger.Document) and ifNull(". $toledger.",ledger.Document) ) ) ".
					" and ( ($prtselper = 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  ".
					"       ($prtselper = 0 and 1 = 1 ) )  ".
					//" and ((ledger.Ledger_inactive = 0 and 1 = 1) or (ledger.Ledger_inactive = 1 and date_format(ledger.Ledger_inactivedate,'%Y%m%d') >= date_format(". $fromdate.",'%Y%m%d'))) ".
					" and (($alltypes = 1 and 1 = 1) or ($alltypes = 0 and $jvtypelen = 0 and 1 = 1) or ($alltypes = 0 and $exclude = 0 and $jvtypelen > 0 and Journal_type in ($jvtype)) or ($alltypes = 0 and $exclude = 1 and $jvtypelen > 0 and Journal_type not in ($jvtype)) ) ".
					" and (($options In (1,7,8) and 1 = 1) or ($options = 4 and ledger.ledger_type = 1) or ($options = 5 and ledger.ledger_type = 2) or ($options In (2,3,6) and ledger.ledger_type In (1,2)) )  ";

	if ($Module_BelongsToGroup == 1)				
		$querydetail= $querydetail." and ifNull(ledger.Ledger_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ".
								" and ifNull(JournalDt.Journal_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0)  ";
								
	if($ledgerinclude== 1 && $ledgerexist > 0) {
		$querydetail = $querydetail." And Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerrepstk ".
									"              where ledgerrepstk.user_account='".$_SESSION['useraccount']."' ".
									"              and (ledger_number is not null and ledger_number != '') ".
									"              and JournalDt.ledger_number like concat(ledgerrepstk.ledger_number,'%') ".
									"            ) ";
	}
	if($ledgerinclude== 0 && $ledgerexist > 0){
		$querydetail = $querydetail." 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 JournalDt.ledger_number like concat(ledgerrepstk.ledger_number,'%') ".
									"                ) ";	
	}
			
	if ($options == 4){
		$querydetail = $querydetail." and ifNull(Clients.Salesmen_Code,'-1') between ifNull(".$fromsalesman.",ifNull(Clients.Salesmen_Code,'-1')) and ifNull(". $tosalesman.",ifNull(Clients.Salesmen_Code,'-1')) ";
	}		
	if ($options == 7) 
	$querydetail= $querydetail." and acctypesetup.type_code = ifNull(".$fromacctype.",acctypesetup.type_code) ";				
	
	if ($options == 8) 
		$querydetail= $querydetail." and ifNull(Clients.Client_BusinessType, -1) = ifNull(".$frombustype.",ifNull(Clients.Client_BusinessType, -1)) ";

	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' || $excludecst != 'null' || $prtprjcst == 1 || $prtprjcst2 == 1) { 

	$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'))) ".
								" and ((".$excludecst." is not null and upper(ifNull(CstJour.Costcent_Code,'-1')) Not Like upper(".$excludecst.")) or ($excludecst is null and 1 = 1) ) ";
								//" and ((CstJour.Cst_increment is not null and (($currbase1 = 1 and ifNull(Cstjour_amount1,0) != 0) or ($currbase2 = 1 and ifNull(Cstjour_amount2,0) != 0) or ($curr = 1 and ifNull(Cstjour_amount,0) != 0))) or ".
								//"      (CstJour.Cst_increment is null and (($currbase1 = 1 and ifNull(Journaldt_amount1,0) != 0) or ($currbase2 = 1 and ifNull(Journaldt_amount2,0) != 0) or ($curr = 1 and ifNull(Journaldt_amount,0) != 0))) ) ";
	} 
	/*else {
	$querydetail= $querydetail." and (($currbase1 = 1 and ifNull(Journaldt_amount1,0) != 0) or ($currbase2 = 1 and ifNull(Journaldt_amount2,0) != 0) or ($curr = 1 and ifNull(Journaldt_amount,0) != 0)) ";
	}*/
	
	/*$querydetail= $querydetail." Group By Ledger.Ledger_number, Ledger.Ledger_name, JournalDt.Currency_code ".
							" order by  Ledger.Ledger_number ";*/

	//echo $querydetail;exit;
	if($i > 1)
		$queryjournal = $queryjournal." UNION ";
	$queryjournal = $queryjournal.  "Select Q3.Ledger_number AS Ledger_number, ".
											" Q3.Ledger_name AS Ledger_name, ".
											" Q3.Document AS Document, ".
											" Q3.Ledger_grpdet AS Ledger_grpdet, ".
											" Q3.Ledger_RequiredDetail AS Ledger_RequiredDetail, ".
											" Q3.CvCurrBase1 AS CvCurrBase1, ".
											" Q3.CvCurrBase2 AS CvCurrBase2, ".
											" Q3.Project_code AS Project_code, ".
											" Q3.project_name AS project_name, ".
											" Q3.Costcent_Code AS Costcent_Code, ".
											" Q3.costcent_name AS costcent_name, ".
											" Q3.Currency_code AS Currency_code, ";
	$j = 1;
	while($j <= sizeof($dbNames)){
		if(fmod($j,$i) == 0){
			if($i==1 && $j>1){
				$queryjournal .= "0 AS PrevDebitAmount".$j.", ".
								" 0 AS PrevDebitAmountBase1".$j.", ".
								" 0 AS PrevDebitAmountBase2".$j.", ".
								" 0 AS PrevCreditAmount".$j.", ".
								" 0 AS PrevCreditAmountBase1".$j.", ".
								" 0 AS PrevCreditAmountBase2".$j.", ".
								" 0 AS PrevBalance".$j.", ".
								" 0 AS PrevBalanceBase1".$j.", ".
								" 0 AS PrevBalanceBase2".$j.", ".
								" 0 AS DebitAmount".$j.", ".
								" 0 AS DebitAmountBase1".$j.", ".
								" 0 AS DebitAmountBase2".$j.", ".
								" 0 AS CreditAmount".$j.", ".
								" 0 AS CreditAmountBase1".$j.", ".
								" 0 AS CreditAmountBase2".$j.", ".
								" 0 AS Balance".$j.", ".
								" 0 AS BalanceBase1".$j.", ".
								" 0 AS BalanceBase2".$j.", ".
								" 0 AS ActBalance".$j.", ".
								" 0 AS ActBalanceBase1".$j.", ".
								" 0 AS ActBalanceBase2".$j.", ".
								" 0 AS Ord".$j.", ".
								" 0 AS CountPrj".$j.", ".
								" 0 AS CountCst".$j;
				if($j < sizeof($dbNames))
					$queryjournal .= ", ";
			}else{
				$queryjournal .= "Q3.PrevDebitAmount AS PrevDebitAmount".$j.", ".
								" Q3.PrevDebitAmountBase1 AS PrevDebitAmountBase1".$j.", ".
								" Q3.PrevDebitAmountBase2 AS PrevDebitAmountBase2".$j.", ".
								" Q3.PrevCreditAmount AS PrevCreditAmount".$j.", ".
								" Q3.PrevCreditAmountBase1 AS PrevCreditAmountBase1".$j.", ".
								" Q3.PrevCreditAmountBase2 AS PrevCreditAmountBase2".$j.", ".
								" Q3.PrevBalance AS PrevBalance".$j.", ".
								" Q3.PrevBalanceBase1 AS PrevBalanceBase1".$j.", ".
								" Q3.PrevBalanceBase2 AS PrevBalanceBase2".$j.", ".
								" Q3.DebitAmount AS DebitAmount".$j.", ".
								" Q3.DebitAmountBase1 AS DebitAmountBase1".$j.", ".
								" Q3.DebitAmountBase2 AS DebitAmountBase2".$j.", ".
								" Q3.CreditAmount AS CreditAmount".$j.", ".
								" Q3.CreditAmountBase1 AS CreditAmountBase1".$j.", ".
								" Q3.CreditAmountBase2 AS CreditAmountBase2".$j.", ".
								" Q3.Balance AS Balance".$j.", ".
								" Q3.BalanceBase1 AS BalanceBase1".$j.", ".
								" Q3.BalanceBase2 AS BalanceBase2".$j.", ".
								" Q3.ActBalance AS ActBalance".$j.", ".
								" Q3.ActBalanceBase1 AS ActBalanceBase1".$j.", ".
								" Q3.ActBalanceBase2 AS ActBalanceBase2".$j.", ".
								" Q3.Ord AS Ord".$j.", ".
								" Q3.CountPrj AS CountPrj".$j.", ".
								" Q3.CountCst AS CountCst".$j;
				if($j < sizeof($dbNames))
					$queryjournal .= ", ";
				}
		}else{
			$queryjournal .= "0 AS PrevDebitAmount".$j.", ".
							" 0 AS PrevDebitAmountBase1".$j.", ".
							" 0 AS PrevDebitAmountBase2".$j.", ".
							" 0 AS PrevCreditAmount".$j.", ".
							" 0 AS PrevCreditAmountBase1".$j.", ".
							" 0 AS PrevCreditAmountBase2".$j.", ".
							" 0 AS PrevBalance".$j.", ".
							" 0 AS PrevBalanceBase1".$j.", ".
							" 0 AS PrevBalanceBase2".$j.", ".
							" 0 AS DebitAmount".$j.", ".
							" 0 AS DebitAmountBase1".$j.", ".
							" 0 AS DebitAmountBase2".$j.", ".
							" 0 AS CreditAmount".$j.", ".
							" 0 AS CreditAmountBase1".$j.", ".
							" 0 AS CreditAmountBase2".$j.", ".
							" 0 AS Balance".$j.", ".
							" 0 AS BalanceBase1".$j.", ".
							" 0 AS BalanceBase2".$j.", ".
							" 0 AS ActBalance".$j.", ".
							" 0 AS ActBalanceBase1".$j.", ".
							" 0 AS ActBalanceBase2".$j.", ".
							" 0 AS Ord".$j.", ".
							" 0 AS CountPrj".$j.", ".
							" 0 AS CountCst".$j;
			if($j < sizeof($dbNames))
				$queryjournal .= ", ";
		}
		$j += 1;
	}
	$queryjournal = $queryjournal." from ".
					" ( ".
					" select Q1.Ledger_number, Q1.Ledger_name, Q1.Document, Q1.Ledger_grpdet, ".
					" Q1.Ledger_RequiredDetail, Q2.CvCurrBase1,Q2.CvCurrBase2, ". 
					" Q2.Project_code, Q2.project_name,Q2.Costcent_Code, Q2.costcent_name,Q2.Currency_code, ".
					" Sum(Q2.PrevDebitAmount) PrevDebitAmount ,  Sum(Q2.PrevDebitAmountBase1) PrevDebitAmountBase1,   Sum(Q2.PrevDebitAmountBase2) PrevDebitAmountBase2, ".
					" Sum(Q2.PrevCreditAmount) PrevCreditAmount, Sum(Q2.PrevCreditAmountBase1) PrevCreditAmountBase1, Sum(Q2.PrevCreditAmountBase2) PrevCreditAmountBase2, ".
					" Sum(Q2.PrevBalance) PrevBalance,           Sum(Q2.PrevBalanceBase1) PrevBalanceBase1,           Sum(Q2.PrevBalanceBase2) PrevBalanceBase2, ".
					" Sum(Q2.DebitAmount) DebitAmount,           Sum(Q2.DebitAmountBase1) DebitAmountBase1,           Sum(Q2.DebitAmountBase2) DebitAmountBase2, ".
					" Sum(Q2.CreditAmount) CreditAmount,         Sum(Q2.CreditAmountBase1) CreditAmountBase1,         Sum(Q2.CreditAmountBase2) CreditAmountBase2, ".
					" Sum(Q2.Balance) Balance,                   Sum(Q2.BalanceBase1) BalanceBase1,                   Sum(Q2.BalanceBase2) BalanceBase2, ".
					" Sum(Q2.PrevBalance + Q2.Balance) ActBalance, Sum(Q2.PrevBalanceBase1 + Q2.BalanceBase1) ActBalanceBase1, Sum(Q2.PrevBalanceBase2 + Q2.BalanceBase2) ActBalanceBase2, ".
					" 2 As Ord, Sum(Q2.countprj) CountPrj, Sum(Q2.countcst) CountCst ".
					" from ".
					" ( select Ledger.Ledger_number, Ledger.Ledger_name, Ledger.Document, Ledger.Ledger_grpdet, ".
					"   Ledger.Ledger_RequiredDetail ".
					"   from ".$dbNameUsed.".Ledger ";
								
									

					
					$queryjournal= $queryjournal."   where ( ($prtdoc = 0 and ledger.Ledger_number between ifNull(".$fromledger.",ledger.Ledger_number) and ifNull(". $toledger.",ledger.Ledger_number) ) or ".
												"           ($prtdoc = 1 and ledger.Document between ifNull(".$fromledger.",ledger.Document) and ifNull(". $toledger.",ledger.Document) ) ) ";
												//"     and ((ledger.Ledger_inactive = 0 and 1 = 1) or (ledger.Ledger_inactive = 1 and date_format(ledger.Ledger_inactivedate,'%Y%m%d') >= date_format(". $fromdate.",'%Y%m%d'))) ";
					
					$queryjournal= $queryjournal." ) Q1, ".
					" (   ";
					
	$queryjournal= $queryjournal.$querydetail;
	$queryjournal= $queryjournal." Group By Ledger.Ledger_number, Ledger.Ledger_name, Currency_code ".
								" order by  Ledger.Ledger_number ";
	$queryjournal= $queryjournal." ) Q2 ".
								//" Where Q2.Ledger_number like concat(Q1.Ledger_number,'%') ".
								" Where ((Q1.Ledger_grpdet = 1 and Q2.Ledger_number like concat(Q1.Ledger_number,'%')) or (Q1.Ledger_grpdet != 1 and Q2.Ledger_number = Q1.Ledger_number)) ".
								" Group by Q1.Ledger_number, Q1.Ledger_name, Q1.Document, Q1.Ledger_grpdet, if(Q1.Ledger_grpdet=0, Q2.Currency_code, null) ";
								
								
	if ($curr == 1) {
		$queryjournal= $queryjournal." union ".
									" select Q2.Ledger_number, Q2.Ledger_name, Q2.Document, Q2.Ledger_grpdet, ".
									" Q2.Ledger_RequiredDetail, Q2.CvCurrBase1,Q2.CvCurrBase2, ". 
									" Q2.Project_code, Q2.project_name,Q2.Costcent_Code, Q2.costcent_name, Null Currency_code, ".
									" Sum(Q2.PrevDebitAmount) PrevDebitAmount ,  Sum(Q2.PrevDebitAmountBase1) PrevDebitAmountBase1,   Sum(Q2.PrevDebitAmountBase2) PrevDebitAmountBase2, ".
									" Sum(Q2.PrevCreditAmount) PrevCreditAmount, Sum(Q2.PrevCreditAmountBase1) PrevCreditAmountBase1, Sum(Q2.PrevCreditAmountBase2) PrevCreditAmountBase2, ".
									" Sum(Q2.PrevBalance) PrevBalance,           Sum(Q2.PrevBalanceBase1) PrevBalanceBase1,           Sum(Q2.PrevBalanceBase2) PrevBalanceBase2, ".
									" Sum(Q2.DebitAmount) DebitAmount,           Sum(Q2.DebitAmountBase1) DebitAmountBase1,           Sum(Q2.DebitAmountBase2) DebitAmountBase2, ".
									" Sum(Q2.CreditAmount) CreditAmount,         Sum(Q2.CreditAmountBase1) CreditAmountBase1,         Sum(Q2.CreditAmountBase2) CreditAmountBase2, ".
									" Sum(Q2.Balance) Balance,                   Sum(Q2.BalanceBase1) BalanceBase1,                   Sum(Q2.BalanceBase2) BalanceBase2, ".
									" Sum(Q2.PrevBalance + Q2.Balance) ActBalance, Sum(Q2.PrevBalanceBase1 + Q2.BalanceBase1) ActBalanceBase1, Sum(Q2.PrevBalanceBase2 + Q2.BalanceBase2) ActBalanceBase2, ".
									" 1 As Ord, Sum(Q2.countprj) CountPrj, Sum(Q2.countcst) CountCst ".
									" from ( ";

		$queryjournal= $queryjournal.$querydetail;							 
		$queryjournal= $queryjournal." Group By Ledger.Ledger_number, Ledger.Ledger_name, Currency_code ".
									" order by  Ledger.Ledger_number ";
		$queryjournal= $queryjournal." ) Q2 ".
									" Group by Q2.Ledger_number, Q2.Ledger_name, Q2.Document, Q2.Ledger_grpdet ";
	}							 
								
	if($prtprjcst == 1 || $prtprjcst2 == 1) {								 
		$queryjournal= $queryjournal." union ".
									" select Q2.Ledger_number, Q2.Ledger_name, Q2.Document, Q2.Ledger_grpdet, ".
									" Q2.Ledger_RequiredDetail, Q2.CvCurrBase1,Q2.CvCurrBase2, ". 
									" Q2.Project_code, Q2.project_name,Q2.Costcent_Code, Q2.costcent_name, Null Currency_code, ".
									" Sum(Q2.PrevDebitAmount) PrevDebitAmount ,  Sum(Q2.PrevDebitAmountBase1) PrevDebitAmountBase1,   Sum(Q2.PrevDebitAmountBase2) PrevDebitAmountBase2, ".
									" Sum(Q2.PrevCreditAmount) PrevCreditAmount, Sum(Q2.PrevCreditAmountBase1) PrevCreditAmountBase1, Sum(Q2.PrevCreditAmountBase2) PrevCreditAmountBase2, ".
									" Sum(Q2.PrevBalance) PrevBalance,           Sum(Q2.PrevBalanceBase1) PrevBalanceBase1,           Sum(Q2.PrevBalanceBase2) PrevBalanceBase2, ".
									" Sum(Q2.DebitAmount) DebitAmount,           Sum(Q2.DebitAmountBase1) DebitAmountBase1,           Sum(Q2.DebitAmountBase2) DebitAmountBase2, ".
									" Sum(Q2.CreditAmount) CreditAmount,         Sum(Q2.CreditAmountBase1) CreditAmountBase1,         Sum(Q2.CreditAmountBase2) CreditAmountBase2, ".
									" Sum(Q2.Balance) Balance,                   Sum(Q2.BalanceBase1) BalanceBase1,                   Sum(Q2.BalanceBase2) BalanceBase2, ".
									" Sum(Q2.PrevBalance + Q2.Balance) ActBalance, Sum(Q2.PrevBalanceBase1 + Q2.BalanceBase1) ActBalanceBase1, Sum(Q2.PrevBalanceBase2 + Q2.BalanceBase2) ActBalanceBase2, ".
									" 3 As Ord, Sum(Q2.countprj) CountPrj, Sum(Q2.countcst) CountCst ".
									" from ( ";

		$queryjournal= $queryjournal.$querydetail;
		$queryjournal= $queryjournal." Group By Ledger.Ledger_number, Ledger.Ledger_name, Currency_code, CstJour.Project_code, project.project_name ".
									" order by  Ledger.Ledger_number, project.project_name ";
		$queryjournal= $queryjournal." ) Q2 ".
									" Group by Q2.Ledger_number, Q2.Ledger_name, Q2.Document, Q2.Ledger_grpdet, Q2.Project_code, Q2.project_name ".
									" Having Sum(Q2.Balance) != 0 ".
									" union ".
									" select Q2.Ledger_number, Q2.Ledger_name, Q2.Document, Q2.Ledger_grpdet, ".
									" Q2.Ledger_RequiredDetail, Q2.CvCurrBase1,Q2.CvCurrBase2, ". 
									" Q2.Project_code, Q2.project_name,Q2.Costcent_Code, Q2.costcent_name, Null Currency_code, ".
									" Sum(Q2.PrevDebitAmount) PrevDebitAmount ,  Sum(Q2.PrevDebitAmountBase1) PrevDebitAmountBase1,   Sum(Q2.PrevDebitAmountBase2) PrevDebitAmountBase2, ".
									" Sum(Q2.PrevCreditAmount) PrevCreditAmount, Sum(Q2.PrevCreditAmountBase1) PrevCreditAmountBase1, Sum(Q2.PrevCreditAmountBase2) PrevCreditAmountBase2, ".
									" Sum(Q2.PrevBalance) PrevBalance,           Sum(Q2.PrevBalanceBase1) PrevBalanceBase1,           Sum(Q2.PrevBalanceBase2) PrevBalanceBase2, ".
									" Sum(Q2.DebitAmount) DebitAmount,           Sum(Q2.DebitAmountBase1) DebitAmountBase1,           Sum(Q2.DebitAmountBase2) DebitAmountBase2, ".
									" Sum(Q2.CreditAmount) CreditAmount,         Sum(Q2.CreditAmountBase1) CreditAmountBase1,         Sum(Q2.CreditAmountBase2) CreditAmountBase2, ".
									" Sum(Q2.Balance) Balance,                   Sum(Q2.BalanceBase1) BalanceBase1,                   Sum(Q2.BalanceBase2) BalanceBase2, ".
									" Sum(Q2.PrevBalance + Q2.Balance) ActBalance, Sum(Q2.PrevBalanceBase1 + Q2.BalanceBase1) ActBalanceBase1, Sum(Q2.PrevBalanceBase2 + Q2.BalanceBase2) ActBalanceBase2, ".
									" 4 As Ord, Sum(Q2.countprj) CountPrj, Sum(Q2.countcst) CountCst ".
									" from ( ";

		$queryjournal= $queryjournal.$querydetail;
		$queryjournal= $queryjournal." Group By Ledger.Ledger_number, Ledger.Ledger_name, Currency_code, CstJour.Costcent_Code, costcent.costcent_name ".
									" order by  Ledger.Ledger_number, costcent.costcent_name ";
		$queryjournal= $queryjournal." ) Q2 ".
									" Group by Q2.Ledger_number, Q2.Ledger_name, Q2.Document, Q2.Ledger_grpdet, Q2.Costcent_Code, Q2.costcent_name ";
									//" Having Sum(Q2.Balance) != 0 ";
	}							 
						
								
	$queryjournal= $queryjournal." ) Q3 ".
								" Where (($prtgrponly = 1 and Q3.Ledger_grpdet = 1 and (($prtparents = 1 and length(Q3.Ledger_number) <= $grplen) or ($prtparents = 0 and length(Q3.Ledger_number) = $grplen))) or ($prtgrponly = 0 and 1 = 1))  ";
		
	if ($prtzerobal == 0){
		$queryjournal= $queryjournal." And (Q3.PrevDebitAmountBase1 != 0 or Q3.PrevCreditAmountBase1 != 0 or Q3.PrevDebitAmountBase2 != 0 or Q3.PrevCreditAmountBase2 != 0 or ".
									" 		Q3.DebitAmountBase1 != 0 or Q3.CreditAmountBase1 != 0 or Q3.DebitAmountBase2 != 0 or Q3.CreditAmountBase2 != 0) ";
	}

	/*if ($prtzerobal == 0 && $currbase1 == 1 && $currbase2 == 1){
		$queryjournal= $queryjournal." And (($prtselper = 1 and round(Q3.BalanceBase1,$DecimalBase1) != 0 and round(Q3.BalanceBase2,$DecimalBase2) != 0) or ($prtselper = 0 and round(Q3.ActBalanceBase1,$DecimalBase1) != 0 and round(Q3.ActBalanceBase2,$DecimalBase2) != 0)) ";
	}
	else if ($prtzerobal == 0 && $currbase1 == 1){
		$queryjournal= $queryjournal." And (($prtselper = 1 and round(Q3.BalanceBase1,$DecimalBase1) != 0) or ($prtselper = 0 and round(Q3.ActBalanceBase1,$DecimalBase1) != 0)) ";
	}
	else if ($prtzerobal == 0 && $currbase2 == 1){
		$queryjournal= $queryjournal." And (($prtselper = 1 and round(Q3.BalanceBase2,$DecimalBase2) != 0) or ($prtselper = 0 and round(Q3.ActBalanceBase2,$DecimalBase2) != 0)) ";
	}*/

								//" And (($prtzerobal = 0 and (($prtselper = 1 and round(Q3.Balance,$DecimalBase) != 0) or ($prtselper = 0 and round(Q3.ActBalance,$DecimalBase) != 0))) or ($prtzerobal = 1 and 1 = 1)) ".
	$queryjournal= $queryjournal." And (($prtdtonly = 1 and Q3.Ledger_grpdet = 0) or ($prtdtonly = 0 and 1 = 1)) ".
								" And (($prtreqdt = 1 and Q3.Ledger_RequiredDetail = 1) or ($prtreqdt = 0 and 1 = 1)) ";

		$i += 1;
    }
    $queryjournal .= " ) AS tt Group By Ledger_number, Ledger_name, Currency_code, Costcent_Code, costcent_name";                      
if($prtprjcst == 0 && $prtprjcst2 == 0) 							 
    $queryjournal= $queryjournal." Order by Ledger_number, Ledger_name, Currency_code ";
else
    $queryjournal= $queryjournal." Order by Ledger_number, Ledger_name, Currency_code, project_name, costcent_name ";	

		  
//echo $queryjournal; exit;
$RowNum    = 10;
$ColumnNum = 0;
$i = 1;
$j = 0;
$temp = 0;
$temp2 = 1;
while($i<=sizeof($dbNames)){
	$dbNameUsed = $dbNames[$i-1];
	$worksheet->write($RowNum,$ColumnNum,$dbNameUsed, $boldleftFormat);
	$RowNum += 1;
	$worksheet->write($RowNum,$ColumnNum,"Ledger Desc.", $boldleftFormat);
	$ColumnNum += 1;
	$worksheet->write($RowNum,$ColumnNum,"", $boldcenterFormat);
	$ColumnNum += 1;
	$worksheet->write($RowNum,$ColumnNum,"Currency", $boldcenterFormat);
	$ColumnNum += 1;
	$worksheet->write($RowNum,$ColumnNum,"C/V", $boldcenterFormat);
	$ColumnNum += 1;

	if ($showactbal != 1) {
		if ($prtselper == 0)	
		{	
			if($showprevdbcd){
				$worksheet->write($RowNum,$ColumnNum,"Previous Debit", $boldcenterFormat);
				$ColumnNum += 1;
				$worksheet->write($RowNum,$ColumnNum,"Previous Credit", $boldcenterFormat);
				$ColumnNum += 1;	
				$worksheet->write($RowNum,$ColumnNum,"Previous Balance", $boldcenterFormat);
				$ColumnNum += 1;
				$worksheet->write($RowNum,$ColumnNum,"Debit", $boldcenterFormat);
				$ColumnNum += 1;
				$worksheet->write($RowNum,$ColumnNum,"Credit", $boldcenterFormat);
				$ColumnNum += 1;
				$worksheet->write($RowNum,$ColumnNum,"Balance", $boldcenterFormat);			
				$ColumnNum += 1;
				$worksheet->write($RowNum,$ColumnNum,"Actual Balance", $boldcenterFormat);
				$ColumnNum += 1;
			}else{
				$worksheet->write($RowNum,$ColumnNum,"Previous Balance", $boldcenterFormat);
				$ColumnNum += 1;
				$worksheet->write($RowNum,$ColumnNum,"Debit", $boldcenterFormat);
				$ColumnNum += 1;
				$worksheet->write($RowNum,$ColumnNum,"Credit", $boldcenterFormat);
				$ColumnNum += 1;
				$worksheet->write($RowNum,$ColumnNum,"Balance", $boldcenterFormat);			
				$ColumnNum += 1;
				$worksheet->write($RowNum,$ColumnNum,"Actual Balance", $boldcenterFormat);
				$ColumnNum += 1;
			}       
		} else	{
			$worksheet->write($RowNum,$ColumnNum,"Debit", $boldcenterFormat);
			$ColumnNum += 1;
			$worksheet->write($RowNum,$ColumnNum,"Credit", $boldcenterFormat);
			$ColumnNum += 1;
			$worksheet->write($RowNum,$ColumnNum,"Balance", $boldcenterFormat);			
			$ColumnNum += 1;
		}
	} else {
		$worksheet->write($RowNum,$ColumnNum,"Actual Balance", $boldcenterFormat);
		$ColumnNum += 1;
	}		

	$RowNum   += 1;
	$ColumnNum = 0;

	if ($prtprjcst == 1) {
		$worksheet->write($RowNum,$ColumnNum,"* Project", $boldleftFormat);
		
	}
	if ($prtprjcst2 == 1) {
		$RowNum   += 1;
		$worksheet->write($RowNum,$ColumnNum,"** Cost center", $boldleftFormat);
	}


	$MasterGroup = '';
	$MainRecord = '';

	$SumPrevDbBase1  = 0;
	$SumPrevCrBase1  = 0;
	$SumPrevBalBase1 = 0;
	$SumDbBase1  = 0;
	$SumCrBase1  = 0;
	$SumBalBase1 = 0;
	$SumActDbBase1  = 0;
	$SumActCrBase1  = 0;
	$SumActBalBase1 = 0;

	$SumPrevDbBase2  = 0;
	$SumPrevCrBase2  = 0;
	$SumPrevBalBase2 = 0;
	$SumDbBase2  = 0;
	$SumCrBase2  = 0;
	$SumBalBase2 = 0;
	$SumActDbBase2  = 0;
	$SumActCrBase2  = 0;
	$SumActBalBase2 = 0;

	$CountProject = 0;
	$CountCostCent = 0;

	$RowNum    = 13;
	
	$resultjournal=mysql_query($queryjournal,$connection) or die(mysql_error());
	while($rowsjournal=mysql_fetch_row($resultjournal)){
		
		$class='';
		
		if($rowsjournal[33+$j] == 3 && $rowsjournal[34+$j] > 0 && $prtprjcst==1)  
			$CountProject = $rowsjournal[34+$j];
		if($rowsjournal[33+$j] == 4 && $rowsjournal[35+$j] > 0 && $prtprjcst2==1) 
			$CountCostCent = $rowsjournal[35+$j];	
		
		/*if (($MasterGroup != '' && $MasterGroup!= $rowsjournal[0]) || ($rowsjournal[33] == 3 && $CountProject > 0) || ($rowsjournal[33] == 4 && $CountCostCent > 0)) {	
			//Increment the Rows Counter By 1 and Reset the Columns Counter
			$RowNum += 1;
			$ColumnNum = 0;
		}*/	
			
		
		
		if (($MasterGroup == '' || $MasterGroup!= $rowsjournal[0])) {	
			$CountProject = 0;
			$CountCostCent = 0;
			
			$RowNum += 1;
			$ColumnNum = $temp;
			
			$worksheet->write($RowNum, $ColumnNum, $rowsjournal[0], $regularleftFormat);
			$ColumnNum += 1;
			$worksheet->write($RowNum, $ColumnNum, $rowsjournal[1], $regularleftFormat);
			$ColumnNum += 1;
		} else if (($MasterGroup != '' && $MasterGroup == $rowsjournal[0] && $rowsjournal[10] == '')) {	
			$CountProject = 0;
			$CountCostCent = 0;
		
			$RowNum += 1;
			$ColumnNum = $temp;
			$ColumnNum += 2;
		} else if($rowsjournal[33+$j] == 3 && $CountProject > 0 && $prtprjcst == 1 )  {
			$RowNum += 1;
			$ColumnNum = $temp;
			
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, "* ". $rowsjournal[8], $regularleftFormat);
			$ColumnNum += 2;
		} else if($rowsjournal[33+$j] == 4 && $CountCostCent > 0  && $prtprjcst2 == 1 )  {
			$RowNum += 1;
			$ColumnNum = $temp;
			
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, "** ". $rowsjournal[10], $regularleftFormat);
			$ColumnNum += 2;
		} else if($curr == 1) {
			$RowNum += 1;
			$ColumnNum = $temp;
			
			$ColumnNum += 2;
		}	
			
		//if ($rowsjournal[3] == 0 && $rowsjournal[11] != ''){	
		if ($rowsjournal[3] == 0){
			//Totals Base1 and Base2
			$SumPrevDbBase1  = $SumPrevDbBase1 + $rowsjournal[13+$j];
			$SumPrevCrBase1  = $SumPrevCrBase1 + $rowsjournal[16+$j];
			$SumPrevBalBase1 = $SumPrevBalBase1 + $rowsjournal[19+$j];
			$SumDbBase1  = $SumDbBase1 + $rowsjournal[22+$j];
			$SumCrBase1  = $SumCrBase1 + $rowsjournal[25+$j];
			$SumBalBase1 = $SumBalBase1 + $rowsjournal[28+$j];
			$SumActDbBase1  = $SumPrevDbBase1 + $SumDbBase1;
			$SumActCrBase1  = $SumPrevCrBase1 + $SumCrBase1;
			$SumActBalBase1 = $SumPrevBalBase1 + $SumBalBase1;
			
			$SumPrevDbBase2  = $SumPrevDbBase2 + $rowsjournal[14+$j];
			$SumPrevCrBase2  = $SumPrevCrBase2 + $rowsjournal[17+$j];
			$SumPrevBalBase2 = $SumPrevBalBase2 + $rowsjournal[20+$j];
			$SumDbBase2  = $SumDbBase2 + $rowsjournal[23+$j];
			$SumCrBase2  = $SumCrBase2 + $rowsjournal[26+$j];
			$SumBalBase2 = $SumBalBase2 + $rowsjournal[29+$j];
			$SumActDbBase2  = $SumPrevDbBase2 + $SumDbBase2;
			$SumActCrBase2  = $SumPrevCrBase2 + $SumCrBase2;
			$SumActBalBase2 = $SumPrevBalBase2 + $SumBalBase2;
		}   
		
		
		if ($rowsjournal[3] == 0 && $rowsjournal[11] != '' && $curr == 1){
		
			// By Currency For Detail
			$worksheet->write($RowNum, $ColumnNum, $rowsjournal[11], $regularleftFormat);
			$ColumnNum += 2;
		
			if ($showactbal != 1) {
				if ($prtselper == 0) {
					if($showprevdbcd == 1){
						$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[12+$j], $regularrightFormatNum1);
						$ColumnNum += 1;
						$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[15+$j], $regularrightFormatNum1);
						$ColumnNum += 1;
						$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[18+$j], $regularrightFormatNum1);
						$ColumnNum += 1;
					}else{
						$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[18+$j], $regularrightFormatNum1);
						$ColumnNum += 1;
					}
				}	
					
				$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[21+$j], $regularrightFormatNum1);
				$ColumnNum += 1;
				$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[24+$j], $regularrightFormatNum1);
				$ColumnNum += 1;
				$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[27+$j], $regularrightFormatNum1);
				$ColumnNum += 1;	
			
				if ($prtselper == 0) {
					$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[30+$j], $regularrightFormatNum1);
					$ColumnNum += 1;
				}	
			} else {
				$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[30+$j], $regularrightFormatNum1);
				$ColumnNum += 1;
			}
		
		
		
			// Counter Value Base1 For Detail
			if ($prtcv == 1 && $currbase1 == 1) {
				$RowNum += 1;
				$ColumnNum += 1;
				
				$worksheet->write($RowNum, $ColumnNum, $rowsjournal[5], $regularleftFormat);
				$ColumnNum += 1;
			
				if ($showactbal != 1) {
					if ($prtselper == 0) {
						if($showprevdbcd == 1){
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[13+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[16+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[19+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
						}else{
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[19+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
						}
					}	
					
					$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[22+$j], $regularrightFormatNum1);
					$ColumnNum += 1;
					$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[25+$j], $regularrightFormatNum1);
					$ColumnNum += 1;
					$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[28+$j],  $regularrightFormatNum1);
					$ColumnNum += 1;  

					if ($prtselper == 0) {
						$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[31+$j], $regularrightFormatNum1);
						$ColumnNum += 1;
					}	
				} else {
					$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[31+$j], $regularrightFormatNum1);
					$ColumnNum += 1;
				}
				
			}   
		}
		else 
		if((($rowsjournal[3] == 1) || ($rowsjournal[3] == 0 && $curr == 0 && $rowsjournal[11] == '' && $rowsjournal[33+$j] != 3 && $rowsjournal[33+$j] != 4) || ($rowsjournal[3] == 0 && $curr == 1)) && $currbase1 == 1)
		{  
			// Counter Value Base1 For Group
			
			if ($currbase1 == 1) {
				$ColumnNum += 1;
				$worksheet->write($RowNum, $ColumnNum, $rowsjournal[5], $regularleftFormat);
				$ColumnNum += 1;
				
			
				if ($showactbal != 1) {
					if ($prtselper == 0) {
						if($showprevdbcd == 1){
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[13+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[16+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[19+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
						}else{
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[19+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
						}
					}	
					
					$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[22+$j],  $regularrightFormatNum1);
					$ColumnNum += 1;
					$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[25+$j],  $regularrightFormatNum1);
					$ColumnNum += 1;
					$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[28+$j],  $regularrightFormatNum1);
					$ColumnNum += 1;  
					
					if ($prtselper == 0) {
						$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[31+$j], $regularrightFormatNum1);
						$ColumnNum += 1;
					}	
				} else {
					$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[31+$j], $regularrightFormatNum1);
					$ColumnNum += 1;
				}	  
			} 
			else if ($prtcv == 1  && $curr == 1 && !(empty($fromcur)) && $rowsjournal[11] != '') {
				$worksheet->write($RowNum, $ColumnNum, $rowsjournal[11], $regularleftFormat);
				$ColumnNum += 2;
			
				if ($showactbal != 1) {
					if ($prtselper == 0) {
						if($showprevdbcd == 1){
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[12+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[15+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
							$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[18+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
						}else{
							$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[18+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
						}
					}	
					
					$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[21+$j],  $regularrightFormatNum1);
					$ColumnNum += 1;
					$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[24+$j],  $regularrightFormatNum1);
					$ColumnNum += 1;
					$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[27+$j], $regularrightFormatNum1);
					$ColumnNum += 1; 
					
					if ($prtselper == 0) {
						$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[30+$j], $regularrightFormatNum1);
						$ColumnNum += 1; 
					}

				} else {
					$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[30+$j],  $regularrightFormatNum1);
					$ColumnNum += 1; 
				}
			}
			else if($curr == 1)
				$ColumnNum += 7; 
				
				

		}   
		else
		if ($rowsjournal[3] == 0 && $curr == 0 && $rowsjournal[11] == '' && (($rowsjournal[33+$j] == 3 && $CountProject > 0) || ($rowsjournal[33+$j] == 4 && $CountCostCent > 0)) )
		{  
			// Counter Value Base1 For Detail Project And CostCenter
			
			if ($prtcv == 1  && $currbase1 == 1) {
				$worksheet->write($RowNum, $ColumnNum, $rowsjournal[5], $regularleftFormat);
				$ColumnNum += 1;
				
				if ($showactbal != 1) {
					if ($prtselper == 0) {
						if($showprevdbcd == 1){
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[13+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
							$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[16+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
							$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[19+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
						}else{
							$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[19+$j], $regularrightFormatNum1);
							$ColumnNum += 1;
						}
					}	
					
					$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[22+$j], $regularrightFormatNum1);
					$ColumnNum += 1;
					$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[25+$j],  $regularrightFormatNum1);
					$ColumnNum += 1;
					$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[28+$j],  $regularrightFormatNum1);
					$ColumnNum += 1;  
					
					if ($prtselper == 0) {
						$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[31+$j], $regularrightFormatNum1);
						$ColumnNum += 1;  
					}	
				} else {
					$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[31+$j], $regularrightFormatNum1);
					$ColumnNum += 1;  
				}	  
			} 
			else 
				$ColumnNum += 6;  
				
		}
		
		// Counter Value Base2
		if (($rowsjournal[3] == 1 && $currbase2 == 1) || ($rowsjournal[3] == 0 && $curr == 0 && $rowsjournal[11] == '' && $rowsjournal[33+$j] != 3 && $rowsjournal[33+$j] != 4 && $currbase2 == 1)
		|| ($rowsjournal[3] == 0 && $curr == 1 && $currbase2 == 1) 
		|| ($rowsjournal[3] == 0 && $curr == 0 && $rowsjournal[11] == '' && $currbase2 == 1 && (($rowsjournal[33+$j] == 3 && $CountProject > 0) || ($rowsjournal[33+$j] == 4 && $CountCostCent > 0))))  	{
			
			if ($currbase1 == 0 && $curr == 0) {
				$ColumnNum += 1;
				
			} else {	
				$RowNum += 1;
				$ColumnNum += 1;
			}
			
			$worksheet->write($RowNum, $ColumnNum, $rowsjournal[6], $regularleftFormat);
			//echo  $rowsjournal[6]." ".$RowNum." ".$ColumnNum."/";
			$ColumnNum += 1;
			
			
			if ($showactbal != 1) {
				if ($prtselper == 0) {
					if($showprevdbcd == 1){
						$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[14+$j], $regularrightFormatNum1);
						$ColumnNum += 1;
						$worksheet->writeNumber($RowNum, $ColumnNum,$rowsjournal[17+$j], $regularrightFormatNum1);
						$ColumnNum += 1;
						$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[20+$j], $regularrightFormatNum1);
						$ColumnNum += 1;
					}else{
						$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[20+$j], $regularrightFormatNum1);
						$ColumnNum += 1;
					}
				}	
					
				$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[23+$j],  $regularrightFormatNum1);
				$ColumnNum += 1;
				$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[26+$j],  $regularrightFormatNum1);
				$ColumnNum += 1;
				$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[29+$j],  $regularrightFormatNum1);
				$ColumnNum += 1;  	
				
				if ($prtselper == 0) {
					$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[32+$j],  $regularrightFormatNum1);
					$ColumnNum += 1;
				}	
			} else {
				$worksheet->writeNumber($RowNum, $ColumnNum, $rowsjournal[32+$j],$regularrightFormatNum1);
				$ColumnNum += 1;
			}

		}	
		
		$MasterGroup = $rowsjournal[0];
		//echo $rowsjournal[6]." ".$rowsjournal[32]." ";
	}
	$temp = $temp + $ColumnNum + 2;
	
	
	if ($currbase1 == 1 || $currbase2 == 1) {

		//Increment the Rows Counter By 1 and Reset the Columns Counter
		$RowNum += 2;
		$ColumnNum = $temp2;

		if ($showactbal != 1) {	  
		
			$worksheet->write($RowNum, $ColumnNum, "", $boldcenterFormat);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, $Base1, $boldcenterFormat);
			$ColumnNum += 2;
			$worksheet->write($RowNum, $ColumnNum, $Base2, $boldcenterFormat);
			$ColumnNum += 1;
			
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, "", $boldcenterFormat);
			$ColumnNum += 2;
			$worksheet->write($RowNum, $ColumnNum, $Base1, $boldcenterFormat);
			$ColumnNum += 1;
			$worksheet->write($RowNum, $ColumnNum, $Base2, $boldcenterFormat);
			$ColumnNum += 1;
			
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, "", $boldcenterFormat);
			$ColumnNum += 2;
			$worksheet->write($RowNum, $ColumnNum, $Base1, $boldcenterFormat);
			$ColumnNum += 1;
			$worksheet->write($RowNum, $ColumnNum, $Base2, $boldcenterFormat);
			$ColumnNum += 1;
			
		} else {
			$worksheet->write($RowNum, $ColumnNum, "", $boldcenterFormat);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, $Base1, $boldcenterFormat);
			$ColumnNum += 2;
			$worksheet->write($RowNum, $ColumnNum, $Base2, $boldcenterFormat);
			$ColumnNum += 1;
		}

		if ($showactbal != 1) {
			$RowNum += 1;
			$ColumnNum = $temp2;
			
			$worksheet->write($RowNum, $ColumnNum, "Total Previous Debit", $boldleftFormat);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumPrevDbBase1, $regularrightFormatNum1);
			$ColumnNum += 2;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumPrevDbBase2,  $regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, "Total Previous Credit", $boldleftFormat);
			$ColumnNum += 2;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumPrevCrBase1,  $regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumPrevCrBase2,  $regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, "Total Previous Balance", $boldleftFormat);
			$ColumnNum += 2;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumPrevBalBase1, $regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumPrevBalBase2,  $regularrightFormatNum1);
			$ColumnNum += 1;
			
			$RowNum += 1;
			$ColumnNum = $temp2;
			
			$worksheet->write($RowNum, $ColumnNum, "Total Debit", $boldleftFormat);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumDbBase1,$regularrightFormatNum1);
			$ColumnNum += 2;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumDbBase2,$regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, "Total Credit", $boldleftFormat);
			$ColumnNum += 2;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumCrBase1, $regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumCrBase2,  $regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, "Total Balance", $boldleftFormat);
			$ColumnNum += 2;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumBalBase1, $regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumBalBase2,  $regularrightFormatNum1);
			$ColumnNum += 1;
			
			$RowNum += 1;
			$ColumnNum = $temp2;
			
			$worksheet->write($RowNum, $ColumnNum, "Total Actual Debit", $boldleftFormat);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumActDbBase1, $regularrightFormatNum1);
			$ColumnNum += 2;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumActDbBase2,$regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, "Total Actual Credit", $boldleftFormat);
			$ColumnNum += 2;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumActCrBase1,$regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumActCrBase2, $regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->write($RowNum, $ColumnNum, "Total Actual Balance", $boldleftFormat);
			$ColumnNum += 2;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumActBalBase1,  $regularrightFormatNum1);
			$ColumnNum += 1;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumActBalBase2,  $regularrightFormatNum1);
			$ColumnNum += 1;
			
		} else {
			$RowNum += 1;
			$ColumnNum = $temp2;
			
			$worksheet->write($RowNum, $ColumnNum, "Total Actual Balance", $boldleftFormat);
			$ColumnNum += 1;
			$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
			$worksheet->writeNumber($RowNum, $ColumnNum,$SumActBalBase1,  $regularrightFormatNum1);
			$ColumnNum += 2;
			$worksheet->writeNumber($RowNum, $ColumnNum, $SumActBalBase2,  $regularrightFormatNum1);
			$ColumnNum += 1;
			
		}
	}
	$temp2 += $ColumnNum;
	$RowNum = 10;
	$ColumnNum = $temp;
	$j = $j + 24;
	
	$i += 1;
	
}


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

$workbook->close();
	
?>