<?php

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

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

$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 Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
			  " 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 Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
			   " and (loginstk.costcent_code is not null and loginstk.costcent_code != '') ".
			   " order by costcent.costcent_code";
$costcentresult = mysql_query($querycostcent,$connection) or die(mysql_error());
$costcentexist  = mysql_num_rows($costcentresult);	




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


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

$dispagingdate = $agingdate;



//Creating a workbook
$workbook = new Spreadsheet_Excel_Writer();

//Sending HTTP headers
$workbook->send('Exp_AgingSupplierInvoices.xls');
 
//Creating a worksheet
$worksheet=&$workbook->addWorksheet('Aging of Supplier Invoices');
$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
$regularleftFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'left'  ));
$regularrightFormat =& $workbook->addFormat(array('size'=>9,
  'align'=>'right'  ));  
  
$TitleFormat =& $workbook->addFormat(array('size'=>11,
  'align'=>'left',
  'bold'=>1
  ));

$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
  ));    
  
$seloptionFormat =& $workbook->addFormat(array('size'=>9,
  'align'=> 'left'  ,
  'valign'=> 'top'  ,
  'bold'=> 1
  ));
$seloptionFormat->setTextWrap();

$SelectedOptions = "Filter by: \n";
if ($fromdate != '')      $SelectedOptions .= "-> Date From: ". $fromdate . "  To: ". $todate ."\n";	
if ($agingdate != '')     $SelectedOptions .= "-> Aging Date: ". $agingdate ."\n";	
if ($displaycur != '')    $SelectedOptions .= "-> Currency: ". $displaycur ."\n";	
if ($fromledger != '')    $SelectedOptions .= "-> Ledger From: ". $fromledger . "  To: ". $toledger ."\n";

  
if (!empty($fromdate))  $fromdate = explodeword($fromdate);
if (!empty($todate))    $todate = explodeword($todate);  
if (!empty($agingdate)) $agingdate = explodeword($agingdate);  
   
$fromledger    = GetSQLValueString($fromledger, 'text');
$toledger      = GetSQLValueString($toledger, 'text');
$fromdate  	   = GetSQLValueString($fromdate, 'date');
$todate        = GetSQLValueString($todate, 'date');     
$agingdate     = GetSQLValueString($agingdate, 'date');  

$fromproject   = GetSQLValueString($fromproject, 'text');
$fromcst   	   = GetSQLValueString($fromcst, 'text');   

if(empty($prtreturn))    $prtreturn = 0;
if(empty($prtclosedinv)) $prtclosedinv = 0;

if($prtreturn == 1) $Label = 'Purchase/Return';
else $Label = 'Purchase';
	
//Display Report Header
$worksheet->write(1,0,$CompanyName, $TitleFormat);
$worksheet->write(1,3,"Aging of Supplier Invoices", $TitleFormat);
               
$worksheet->write(1,7,"Printed Date:", $boldleftFormat);
$worksheet->write(1,8,$printdate[2]."/".$printdate[1]."/".$printdate[0], $regularleftFormat);
$worksheet->write(2,7,"Time:", $boldleftFormat);		
$worksheet->write(2,8,$dt[1]." ".$dt[2], $regularleftFormat);
  
//Displaying Selected Options	
// Merge cells from row 3, col 0 to row 3, col 0
$worksheet->setMerge(3, 0, 8, 6);
$worksheet->write(3,0,$SelectedOptions, $seloptionFormat);  


$RowNum    = 10;
$ColumnNum = 0;



$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 3);
$worksheet->write($RowNum,$ColumnNum,$Label, $boldcenterFormat);
$ColumnNum += 4;
$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 3);
$worksheet->write($RowNum,$ColumnNum,"Payment/Debit Note", $boldcenterFormat);
$ColumnNum += 4;
$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
$worksheet->write($RowNum,$ColumnNum,"Remaining up to ".$dispagingdate, $boldcenterFormat);
$ColumnNum += 2;

$RowNum += 1;
$ColumnNum = 0;	

$worksheet->setColumn ($ColumnNum, $ColumnNum, 12);
$worksheet->write($RowNum,$ColumnNum,"Date", $boldleftFormat);
$ColumnNum += 1;
$worksheet->setColumn ($ColumnNum, $ColumnNum, 12);
$worksheet->write($RowNum,$ColumnNum,"Value Date", $boldleftFormat);
$ColumnNum += 1;
$worksheet->setColumn ($ColumnNum, $ColumnNum, 10);
$worksheet->write($RowNum,$ColumnNum,"Reference", $boldleftFormat);
$ColumnNum += 1;
$worksheet->setColumn ($ColumnNum, $ColumnNum, 15);
$worksheet->write($RowNum,$ColumnNum,"Amount", $boldcenterFormat);
$ColumnNum += 1;

$worksheet->setColumn ($ColumnNum, $ColumnNum, 12);
$worksheet->write($RowNum,$ColumnNum,"Date", $boldleftFormat);
$ColumnNum += 1;
$worksheet->setColumn ($ColumnNum, $ColumnNum, 10);
$worksheet->write($RowNum,$ColumnNum,"Reference", $boldleftFormat);
$ColumnNum += 1;
$worksheet->setColumn ($ColumnNum, $ColumnNum, 15);
$worksheet->write($RowNum,$ColumnNum,"Received Amount", $boldcenterFormat);
$ColumnNum += 1;
$worksheet->setColumn ($ColumnNum, $ColumnNum, 8);
$worksheet->write($RowNum,$ColumnNum,"Days", $boldcenterFormat);
$ColumnNum += 1;

$worksheet->setColumn ($ColumnNum, $ColumnNum, 15);
$worksheet->write($RowNum,$ColumnNum,"Amount", $boldcenterFormat);
$ColumnNum += 1;
$worksheet->setColumn ($ColumnNum, $ColumnNum, 8);
$worksheet->write($RowNum,$ColumnNum,"Days", $boldcenterFormat);
$ColumnNum += 1;
	  
$QueryRestrictPrj = " Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
					" 			   where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
					"              and (project_code is not null and project_code != '') ".
					"			 ) QP  ";
					
$QueryRestrictCst = " Inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
					"			   where loginstk.user_account='".$_SESSION['useraccount']."'  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
					"              and (costcent_code is not null and costcent_code != '') ".
					"			 ) QC  "; 

$query = '';
$query = $query." Select SupplierCode, SupplierName, PurchaseDate, PurchaseValueDate, PurchaseRefer, PurchaseTotalBase1, PurchaseTotalBase2, ".
				" TransDate, TransRefer, TransPaidBase1, TransPaidBase2, PaidDays, TransRemBase1, TransRemBase2, RemainDays, ".
				" OrderPurchaseDate, OrderTransDate, Q2.PrevAmount1, Q2.PrevAmount2 ";
	
$query = $query." From ( ";


$query = $query." Select Purchases.Supplier_Code As SupplierCode, ledger.Ledger_name As SupplierName, date_format(Purchases.Purchase_Date,'%d/%m/%Y') As PurchaseDate, ".
				" date_format(Purchases.Journaldt_ValueDate,'%d/%m/%Y') As PurchaseValueDate, Purchases.Purchase_Reference As PurchaseRefer, ".
				" if(Purchases.Journal_Type='PI', ifNull(AccLink.Sale_NetTotalBase1,0), (-1)*ifNull(AccLink.Sale_NetTotalBase1,0)) As PurchaseTotalBase1, ".
				" if(Purchases.Journal_Type='PI', ifNull(AccLink.Sale_NetTotalBase2,0), (-1)*ifNull(AccLink.Sale_NetTotalBase2,0)) As PurchaseTotalBase2, ".
				" date_format(Trans.Trans_Date,'%d/%m/%Y') As TransDate, Trans.Trans_Reference As TransRefer, ".
				" ifNull(AccLink.Sale_PaidAmntBase1,0) As TransPaidBase1, ifNull(AccLink.Sale_PaidAmntBase2,0) As TransPaidBase2, ".
				" DATEDIFF(date_format(if($dateoption = 1, Trans.Trans_Date, TransDt.TransDt_ValueDate),'%Y-%m-%d'), date_format(if($dateoption = 1, Purchases.Purchase_Date, Purchases.Journaldt_ValueDate),'%Y-%m-%d')) PaidDays, ".
				" ifNull(AccLink.Sale_RemainAmntBase1,0) As TransRemBase1, ifNull(AccLink.Sale_RemainAmntBase2,0) As TransRemBase2, ".
				" DATEDIFF(date_format(".$agingdate.",'%Y-%m-%d'), date_format(if($dateoption = 1, Trans.Trans_Date, TransDt.TransDt_ValueDate),'%Y-%m-%d')) RemainDays, ".
				" Purchases.Purchase_Date As OrderPurchaseDate, Trans.Trans_Date As OrderTransDate ".
				" From Purchases ".
				" Inner Join Acclink on Purchases.Purchase_Reference = Acclink.Link_Ref ".
				" Inner Join TransDt on Acclink.Journal_Id = TransDt.Transdt_Id ".
				" Inner Join Trans on TransDt.Trans_Id = Trans.Trans_Id ".
				" Inner Join Ledger on Purchases.Supplier_Code = Ledger.ledger_Number ";
				
if ($projectexist >	0 && $FI_RepRestrictProject == 1)
	$query = $query.$QueryRestrictPrj." on Purchases.project_code like concat(QP.project_code,'%') ";
									 
if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
	$query = $query.$QueryRestrictCst." on Purchases.costcent_code like concat(QC.costcent_code,'%') ";
		
$query = $query." Where Date_format(Purchases.Purchase_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(Purchases.Purchase_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(Purchases.Purchase_Date,'%Y-%m-%d'))  ".
				" And Purchases.Supplier_Code between ifNull(".$fromledger.",Purchases.Supplier_Code) and ifNull(". $toledger.",Purchases.Supplier_Code) ".
				" And Trans.Trans_Type In ('PV','DV') ".
				" And (($prtreturn=1 and Purchases.journal_Type In ('PI','PR')) or ($prtreturn=0 and Purchases.journal_Type = 'PI')) ".
				" And (($prtclosedinv=1 and 1 = 1) or ($prtclosedinv=0 and ifNull(AccLink.Sale_RemainAmntBase1,0) > 0)) ".
				" And upper(ifNull(Purchases.project_code,'-1')) like ifNull(upper(".$fromproject."), upper(ifNull(Purchases.project_code,'-1'))) ".
				" And upper(ifNull(Purchases.Costcent_Code,'-1')) like ifNull(upper(".$fromcst."), upper(ifNull(Purchases.Costcent_Code,'-1'))) ".
				" And upper(ifNull(Trans.project_code,'-1')) like ifNull(upper(".$fromproject."), upper(ifNull(Trans.project_code,'-1'))) ".
				" And upper(ifNull(Trans.Costcent_Code,'-1')) like ifNull(upper(".$fromcst."), upper(ifNull(Trans.Costcent_Code,'-1'))) ".
				" Union ".
				" Select Purchases.Supplier_Code As SupplierCode, ledger.Ledger_name As SupplierName, date_format(Purchases.Purchase_Date,'%d/%m/%Y') As PurchaseDate, ".
				" date_format(Purchases.Journaldt_ValueDate,'%d/%m/%Y') As PurchaseValueDate, Purchases.Purchase_Reference As PurchaseRefer, ".
				" if(Purchases.Journal_Type='PI', (ifNull(Purchases.Purchase_TotalBase1,0) - ifNull(Purchases.Purchase_DiscountBase1,0) + ifNull(Purchases.Purchase_VATBase1,0)), (-1)*(ifNull(Purchases.Purchase_TotalBase1,0) - ifNull(Purchases.Purchase_DiscountBase1,0) + ifNull(Purchases.Purchase_VATBase1,0))) As PurchaseTotalBase1, ".
				" if(Purchases.Journal_Type='PI', (ifNull(Purchases.Purchase_TotalBase2,0) - ifNull(Purchases.Purchase_DiscountBase2,0) + ifNull(Purchases.Purchase_VATBase2,0)), (-1)*(ifNull(Purchases.Purchase_TotalBase2,0) - ifNull(Purchases.Purchase_DiscountBase2,0) + ifNull(Purchases.Purchase_VATBase2,0))) As PurchaseTotalBase2, ".
				" Null As TransDate, Null As TransRefer, 0 As TransPaidBase1, 0 As TransPaidBase2, 0 PaidDays, ".
				" if(Purchases.Journal_Type='PI', (ifNull(Purchases.Purchase_TotalBase1,0) - ifNull(Purchases.Purchase_DiscountBase1,0) + ifNull(Purchases.Purchase_VATBase1,0)), (-1)*(ifNull(Purchases.Purchase_TotalBase1,0) - ifNull(Purchases.Purchase_DiscountBase1,0) + ifNull(Purchases.Purchase_VATBase1,0))) As TransRemBase1, ".
                " if(Purchases.Journal_Type='PI', (ifNull(Purchases.Purchase_TotalBase2,0) - ifNull(Purchases.Purchase_DiscountBase2,0) + ifNull(Purchases.Purchase_VATBase2,0)), (-1)*(ifNull(Purchases.Purchase_TotalBase2,0) - ifNull(Purchases.Purchase_DiscountBase2,0) + ifNull(Purchases.Purchase_VATBase2,0))) As TransRemBase2, ".
                " DATEDIFF(date_format(".$agingdate.",'%Y-%m-%d'), date_format(if($dateoption = 1, Purchases.Purchase_Date, Purchases.Journaldt_ValueDate),'%Y-%m-%d')) RemainDays, ".
				" Purchases.Purchase_Date As OrderPurchaseDate, Null As OrderTransDate ".
				" From Purchases ".
				" Inner Join Ledger on Purchases.Supplier_Code = Ledger.ledger_Number ";
				
if ($projectexist >	0 && $FI_RepRestrictProject == 1)
	$query = $query.$QueryRestrictPrj." on Purchases.project_code like concat(QP.project_code,'%') ";
									 
if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
	$query = $query.$QueryRestrictCst." on Purchases.costcent_code like concat(QC.costcent_code,'%') ";
	
$query = $query." Where Date_format(Purchases.Purchase_Date,'%Y-%m-%d') between ifNull(". $fromdate.",date_format(Purchases.Purchase_Date,'%Y-%m-%d')) and ifNull(". $todate.",date_format(Purchases.Purchase_Date,'%Y-%m-%d'))  ".
				" And Purchases.Supplier_Code between ifNull(".$fromledger.",Purchases.Supplier_Code) and ifNull(". $toledger.",Purchases.Supplier_Code) ".
				" And Purchase_Reference Not In (Select Link_Ref From Acclink)  ".
				" And (($prtreturn=1 and Purchases.journal_Type In ('PI','PR')) or ($prtreturn=0 and Purchases.journal_Type = 'PI')) ".
				" And upper(ifNull(Purchases.project_code,'-1')) like ifNull(upper(".$fromproject."), upper(ifNull(Purchases.project_code,'-1'))) ".
				" And upper(ifNull(Purchases.Costcent_Code,'-1')) like ifNull(upper(".$fromcst."), upper(ifNull(Purchases.Costcent_Code,'-1'))) ";

				
$query = $query." ) As Q1 ".
			    " Left Join ".
			    " ( Select JournalDt.Ledger_Number, ".
			    "   Sum((if(Journaldt_dbcd = 'D', Journaldt_amount1, 0) - if(Journaldt_dbcd = 'C', Journaldt_amount1, 0))) PrevAmount1, ".
				"   Sum((if(Journaldt_dbcd = 'D', Journaldt_amount2, 0) - if(Journaldt_dbcd = 'C', Journaldt_amount2, 0))) PrevAmount2 ".
				" From JournalDt ".
				" Where Date_format(JournalDt.Journal_Date,'%Y-%m-%d') < ifNull(". $fromdate.",date_format(JournalDt.Journal_Date,'%Y-%m-%d'))  ".
				" And JournalDt.Ledger_Number between ifNull(".$fromledger.",JournalDt.Ledger_Number) and ifNull(". $toledger.",JournalDt.Ledger_Number) ".
				" Group By JournalDt.Ledger_Number ".
				" ) As Q2 on Q2.Ledger_Number = Q1.SupplierCode ";
				
$query = $query." Order by SupplierCode, OrderPurchaseDate, PurchaseRefer, OrderTransDate, TransRefer  ";				
	
//echo $query; exit;

$ArrayTotalByReport   = Array();
$ArrayTotalByMaster   = Array();
$ArrayPurchaseAmount     = Array();
$ArrayPurchaseRefer      = Array();

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

$RowNum    = 13;
$ColumnNum = 0;

$result = mysql_query($query,$connection) or die(mysql_error());
while($rows=mysql_fetch_row($result)){

    // Master By Options Names and Totals
	if (($MasterByCode != $rows[0] && $MasterByCode != '')) {
				
		$StyleClass  = $boldrightFormat;
		$TotalsLabel = 'Supplier Total';
		DisplayTotals($worksheet, $ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $StyleClass, $RowNum, $ColumnNum) ;
		
		//Increment the Rows Counter By 1 and Reset the Columns Counter
		$RowNum += 2;
		$ColumnNum = 0;	
	}
	
	
	if ($MasterByCode == '' || $MasterByCode != $rows[0]) { 
		if ($displaycur == $Base1) {
			$BalanceAmount = $rows[17];
		}
		else if ($displaycur == $Base2){
			$BalanceAmount = $rows[18];
		}
		
		$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 6);
		$worksheet->write($RowNum,$ColumnNum,"Supplier: ".$rows[0]." - ".$rows[1], $boldleftFormat);
		$ColumnNum += 7;
		$worksheet->setMerge($RowNum, $ColumnNum, $RowNum, $ColumnNum + 1);
		$worksheet->write($RowNum,$ColumnNum,"Balance: ".format_currency($BalanceAmount, $DecimalBase)."  ".$displaycur, $boldleftFormat);
		$ColumnNum += 2;
		
		//Increment the Rows Counter By 1 and Reset the Columns Counter
		$RowNum += 1;
		$ColumnNum = 0;	
		
		$MasterByCode = $rows[0];
		$MasterByName = $rows[1];
		
		unset($ArrayTotalByMaster);
		unset($ArrayPurchaseAmount);
		unset($ArrayPurchaseRefer);
	}
	
	if ($displaycur == $Base1) {
		$NetAmount     = $rows[5];
		$PaidAmount    = $rows[9];
		$RemainAmount  = $rows[12];
	}
	else if ($displaycur == $Base2){
		$NetAmount     = $rows[6];
		$PaidAmount    = $rows[10];
		$RemainAmount  = $rows[13];
	}
	
	$worksheet->write($RowNum, $ColumnNum, $rows[2], $regularleftFormat);
	$ColumnNum += 1;
	$worksheet->write($RowNum, $ColumnNum, $rows[3], $regularleftFormat);
	$ColumnNum += 1;
	$worksheet->write($RowNum, $ColumnNum, $rows[4], $regularleftFormat);
	$ColumnNum += 1;
	$worksheet->write($RowNum, $ColumnNum, format_currency($NetAmount, $DecimalBase), $regularrightFormat);
	$ColumnNum += 1;
	
	$worksheet->write($RowNum, $ColumnNum, $rows[7], $regularleftFormat);
	$ColumnNum += 1;
	$worksheet->write($RowNum, $ColumnNum, $rows[8], $regularleftFormat);
	$ColumnNum += 1;
	$worksheet->write($RowNum, $ColumnNum, format_currency($PaidAmount, $DecimalBase), $regularrightFormat);
	$ColumnNum += 1;
	$worksheet->write($RowNum, $ColumnNum, $rows[11], $regularrightFormat);
	$ColumnNum += 1;
	
	$worksheet->write($RowNum, $ColumnNum, format_currency($RemainAmount, $DecimalBase), $regularrightFormat);
	$ColumnNum += 1;
	$worksheet->write($RowNum, $ColumnNum, $rows[14], $regularrightFormat);
	$ColumnNum += 1;
		
	
		
	$RefFound = 0;
	$count = count ($ArrayPurchaseRefer); 
	for ($j=0; $j<$count; $j++){
		if ($ArrayPurchaseRefer[$j] == $rows[4])
			$RefFound = 1;
	}
				
	if ($RefFound == 0) 
		$ArrayPurchaseRefer[$count] = $rows[4];
					
	$ArrayPurchaseAmount[$rows[4]] = $NetAmount;
	$ArrayTotalByMaster['NetAmount']  = 0;
	
	$count = count ($ArrayPurchaseRefer); 
	for ($j=0; $j<$count; $j++){
		$ArrayTotalByMaster['NetAmount']  = $ArrayTotalByMaster['NetAmount']  + $ArrayPurchaseAmount[$ArrayPurchaseRefer[$j]];
	}
	
	
	
	$ArrayTotalByMaster['PaidAmount']   = $ArrayTotalByMaster['PaidAmount'] + $PaidAmount;
	$ArrayTotalByMaster['RemainAmount'] = $ArrayTotalByMaster['NetAmount'] - $ArrayTotalByMaster['PaidAmount'];
	
	//Increment the Rows Counter By 1 and Reset the Columns Counter
	$RowNum += 1;
	$ColumnNum = 0;	
	
}

if ($MasterByCode != '') {
				
	$StyleClass  = $boldrightFormat;
	$TotalsLabel = 'Supplier Total';
	DisplayTotals($worksheet, $ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $StyleClass, $RowNum, $ColumnNum) ;

}
	
	



function DisplayTotals($worksheet, $PArrayTotal, $PDecimalBase, $PTotalsLabel, $PStyleClass, $PRowNum, $PColumnNum) {

	$worksheet->setMerge($PRowNum, $PColumnNum, $PRowNum, $PColumnNum + 2);
	$worksheet->write($PRowNum, $PColumnNum, $PTotalsLabel, $PStyleClass);
	$PColumnNum += 3;
		
	$worksheet->write($PRowNum, $PColumnNum, format_currency($PArrayTotal['NetAmount'], $PDecimalBase), $PStyleClass);
	$PColumnNum += 5;
	
	$worksheet->write($PRowNum, $PColumnNum, format_currency($PArrayTotal['RemainAmount'], $PDecimalBase), $PStyleClass);
	$PColumnNum += 1;
	
}

function format_currency($amount, $DecimalBase) { 

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

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 GetSQLValueString($theValue, $theType) 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

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

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

$workbook->close();

?>