<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<?php

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

print <<< HERE
<HTML>
<HEAD>
<TITLE> Aging of Supplier Invoices Report </TITLE>

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

table.master th { font-size: 14px; 
                  font-weight: bold;
                  font-family:Times-New-Roman;
                }				 
table.master td { font-size: 13px; 
                  font-family:Times-New-Roman;
				  padding-left:3px;
				  padding-right:3px;
                }
table.master tr.group { font-size: 14px; 
                        font-weight: bold;
                        font-family:Times-New-Roman;
                      }				 				

table.master tr.totals { font-size: 12px; 
                         font-weight: bold;
                         font-family:Times-New-Roman;
                       }
		 

</style>
</HEAD>


HERE;


include("config.inc.php");


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


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


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

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


$querysetup="select DecimalBase, DecimalBase1, DecimalBase2, report_color1, report_color2, 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);
} 

//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}


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

print <<< HERE
<table width="100%" border="0" align="center">
<tr>
  <td width='30%'><b>$CompanyName</b></td>
  <td width='50%' align='center'><font size=4><b>Aging of Supplier Invoices</b></font></td>
  <td width='10%'><font size=1><b> Printed Date: </b> <br><b>Time: </b>
  <td width='10%'><font size=1>
HERE;

echo $printdate[2]."/".$printdate[1]."/".$printdate[0];
//echo DATE("d"."/"."m"."/"."Y");
echo "<br>".$dt[1]." ".$dt[2];


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

$dispagingdate = $agingdate;

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

  
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(empty($prtdesc)) 	 $prtdesc = 0;

if($prtreturn == 1) $Label = 'Invoice/Return';
else $Label = 'Invoice';
	

print <<<HERE
</font></td>
</tr>
 
</table>


<table class="params" width="100%" border="0" align="center" >
<tr>
  <td width="100%" valign='top'><b>$SelectedOptions</b></td>
</tr> 
</table>
HERE;

echo "<table  border='0' width='100%' align='center' class='master' style='table-layout:fixed' cellpadding='0' cellspacing='0'>";
echo" <col width=8%>
	  <col width=25%>
	  <col width=6%>
	  <col width=6%>
	  <col width=9%>
	  <col width=9%>
	  <col width=9%>
	  <col width=9%>
	  <col width=9%>
	  <col width=9%> 
	  <col width=9%>
	  <col width=9%>
	  <col width=9%>
	  <col width=9%>
	  <col width=9%>";

	
$ColsSpan = '14';
if ($prtcheck == 1) $ColsSpan = '14';
 

$MainCompanyName=explode('_',$_SESSION['dbName']);  
$QueryDir = " Select Concat(CompanyName, '_', DirYear) As DirSchema, Date_Format(StartFinancialDate,'%Y-%m-%d') As StartFinancialDate, Date_Format(EndFinancialDate,'%Y-%m-%d') As EndFinancialDate, CompanyName, SUBSTRING(DirYear,-4) ".
			" From ".$_SESSION['dbLabel'].".Directories ". 
			" Where Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
			" And ( (ifNull(Date_Format(". $fromdate.",'%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) >= Date_Format(StartFinancialDate,'%Y%m') and ifNull(Date_Format(". $todate.",'%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) <= Date_Format(EndFinancialDate,'%Y%m')) or   ".
			"       (Date_Format(StartFinancialDate,'%Y%m') >= ifNull(Date_Format(". $fromdate.",'%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) and Date_Format(StartFinancialDate,'%Y%m') <= ifNull(Date_Format(". $todate.",'%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) ) or ".
            "       (Date_Format(EndFinancialDate,'%Y%m') >= ifNull(Date_Format(". $fromdate.",'%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) and Date_Format(EndFinancialDate,'%Y%m') <= ifNull(Date_Format(". $todate.",'%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) ) ".
			"      )  ".
			" Order By DirYear ";
			

$ResultDir=mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir1=mysql_query($QueryDir,$connection) or die(mysql_error());
$RowsDirCount = mysql_num_rows($ResultDir);


$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
			InvoiceId,
			SupplierCode,
			SupplierName,
			SalesDate,
			SalesRefer,
			headerjournal,
			SalesTotalBase1,
			SalesTotalBase2,
			Detaillink_date,
			detailreference,
			detailjournal,
			TransPaidBase1,
			TransPaidBase2,
			TransRemBase1,
			TransRemBase2,
			RemainDays,
			detaillink_id,
			counter,
			totalpaid1,
			totalpaid2,
			Q2.PrevAmount1,
			Q2.PrevAmount2,
			CreditLimits,
			PaymentTerms,
			date_format( value_date, '%Y-%m-%d' ) AS value_date,
			trDescription,
			OriginalAmount1,
			OriginalAmount2";

		$query = $query." From ( ";

		$j = 0;				
		$k = 0;

		$query = $query." Select headerlink.headerlink_id As InvoiceId, headerlink.ledger_number As supplierCode,
						ledger.Ledger_name As SupplierName, date_format(headerlink.headerlink_date,'%Y-%m-%d') As SalesDate, ".
						" headerlink.reference As SalesRefer, headerlink.journal_type as headerjournal,".
						" ifNull(headerlink.amountbase1,0) As SalesTotalBase1, ifNull(headerlink.amountbase2,0) As SalesTotalBase2, ".
						"ifNull(date_format( transQuery.trans_date, '%Y-%m-%d' ) , date_format( transQuery1.trans_date, '%Y-%m-%d' )) AS Detaillink_date,
						detaillink.trans_reference as detailreference, detaillink.journal_type as detailjournal,".
						" ifNull(detaillink.amountbase1,0) As TransPaidBase1, ifNull(detaillink.amountbase2,0) As TransPaidBase2, ".
						" ifNull(Q.amountbase1,headerlink.amountbase1) As TransRemBase1, ifNull(Q.amountbase2,headerlink.amountbase2) As TransRemBase2, ".
						" DATEDIFF(headerlink.value_date,$agingdate) as RemainDays, 
						detaillink_id, ifnull(counter,1) as counter, ifnull(paindamnt1,0) as totalpaid1, ifnull(paindamnt2,0) as totalpaid2, ".
						" suppliers.Supplier_CreditLimit As CreditLimits, Supplier_PaymentTerms As PaymentTerms, headerlink.value_date as value_date,headerlink.description As trDescription, 
						ifNull(transQuery.originalAmount1  ,transQuery1.originalAmount1 ) as OriginalAmount1,
						ifNull(transQuery.originalAmount2  ,transQuery1.originalAmount2 ) as OriginalAmount2".
						" From ".$_SESSION['dbLabel'].".headerlink as headerlink ".
						" left Join ".$_SESSION['dbLabel'].".detaillink as detaillink on  detaillink.form_id = headerlink.form_id ".
						" left join
						(select trans.trans_date,trans_type,transdt_id, transdt_amount1 as OriginalAmount1, transdt_amount2 as OriginalAmount2 from transdt left join trans on transdt.trans_id = trans.trans_id ) as transQuery
						on detaillink.journal_type = transQuery.trans_type  and detaillink.relation_id = transQuery.transdt_id
						
						LEFT JOIN ( SELECT purchase_date AS trans_Date, journal_type, supplier_code, purchase_reference,Purchase_TotalBase1  as OriginalAmount1,Purchase_TotalBase2  as OriginalAmount2 FROM purchases  )
						AS transQuery1 ON detaillink.journal_type = transQuery1.journal_type
						AND detaillink.ledger_number = transQuery1.supplier_code
						AND detaillink.Trans_reference = transQuery1.purchase_reference
						".
						" left join(  select d1.form_id as form_id,
									(h1.amountbase1-sum(d1.amountbase1)) as amountbase1, (h1.amountbase2-sum(d1.amountbase2)) as amountbase2,d1.year as year,
									d1.company as company, d1.related_journalType as journal_type,count(*) as counter,sum(d1.amountbase1) as paindamnt1,sum(d1.amountbase2) as paindamnt2
									from ".$_SESSION['dbLabel'].".detaillink as d1
									left join ".$_SESSION['dbLabel'].".headerlink as h1 on h1.form_id = d1.form_id
									group by d1.form_id
							) as Q on Q.form_id = headerlink.form_id and Q.year=headerlink.year
							and Q.company=headerlink.company and Q.journal_type=headerlink.journal_type ".
						" Inner Join Ledger on  Ledger.ledger_Number = headerlink.ledger_number ".
						" Inner join suppliers on suppliers.Ledger_number = headerlink.ledger_number ";
		
		if ($projectexist >	0 && $FI_RepRestrictProject == 1)
			$query = $query.$QueryRestrictPrj." on headerlink.project_code like concat(QP.project_code,'%') ";
										 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$query = $query.$QueryRestrictCst." on headerlink.costcent_code like concat(QC.costcent_code,'%') ";	
			
		$query = $query." Where  upper(headerlink.company) =  Upper('".$MainCompanyName[0]."') and ".
						" Date_format(headerlink.headerlink_date,'%Y-%m-%d') between ifNull(".$fromdate.",date_format(headerlink.headerlink_date,'%Y-%m-%d')) and ifNull(".$todate.",date_format(headerlink.headerlink_date,'%Y-%m-%d'))  ".
						" And headerlink.ledger_number between ifNull(".$fromledger.",headerlink.ledger_number) and ifNull(". $toledger.",headerlink.ledger_number) ";
		$query = $query." And headerlink.journal_type in  ('PI','PR','PC','JP','JV','OP','EX')  and ifnull(headerlink.link_belongToGoup,0) >= '$FI_BelongsToGrp' ";
		
			$query = $query." And upper(ifNull(headerlink.project_code,'-1')) like ifNull(upper(".$fromproject."), upper(ifNull(headerlink.project_code,'-1'))) ".
						" And upper(ifNull(headerlink.costcent_code,'-1')) like ifNull(upper(".$fromcst."), upper(ifNull(headerlink.costcent_code,'-1'))) ";
		if ($prtclosedinv == 0)	$query = $query." and round(ifNull(Q.amountbase1,headerlink.amountbase1),2) <> 0 ";		
		if($examnt1 != '' && $examnt2!='')
			$query = $query." and ifNull(abs(Q.amountbase1),(headerlink.amountbase1)) not between '$examnt1' and '$examnt2' ";	
	
 
$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) ".
				" And IfNull(JournalDt.JournalDt_OldData,0) = 0 ".
				" Group By JournalDt.Ledger_Number ".
				" ) As Q2 on Q2.Ledger_Number = Q1.SupplierCode 
				
				";

$query = $query . "
UNION
SELECT NULL AS
	InvoiceId,
	add_Info.ledger_number AS supplierCode,
	add_Info.ledger_name AS SupplierName,
	ifNull(date_format( add_Info.Trans_Date , '%Y-%m-%d' ), '---' )AS SalesDate,
	NULL AS SalesRefer,
	NULL AS headerjournal,
	0 AS SalesTotalBase1,
	0 AS SalesTotalBase2,
	date_format( add_Info.trans_date, '%Y-%m-%d' ) AS Detaillink_date,
	add_Info.trans_reference AS detailreference,
	add_Info.journal_type AS detailjournal,
	ifNull( add_Info.amountbase1, 0 ) AS TransPaidBase1,
	ifNull( add_Info.amountbase2, 0 ) AS TransPaidBase2,
	0 AS TransRemBase1,
	0 AS TransRemBase2,
	NULL AS RemainDays,
	detaillink_id,
	NULL AS counter,
	0 AS totalpaid1,
	0 AS totalpaid2,
	NULL,
	NULL,
	0 AS CreditLimits,
	NULL PaymentTerms, 
	NULL AS value_date,
	NULL As trDescription,
	ifNull( add_Info.OriginalAmount1, 0 ) AS OriginalAmount1,
	ifNull( add_Info.OriginalAmount2, 0 ) AS OriginalAmount2
FROM
	(
	SELECT
		x.*,
		led.ledger_name,
		ifNull(transQuery.Trans_Date, transQuery1.Trans_Date  ) as trans_date,
		ifNull(transQuery.originalAmount1  , transQuery1.originalAmount1 ) as OriginalAmount1,
		ifNull(transQuery.originalAmount2  , transQuery1.originalAmount2 ) as OriginalAmount2
	FROM
		accesslabelsazar.detaillink AS x
		LEFT JOIN ledger AS led ON x.ledger_number = led.Ledger_number




  left join
		(select trans.trans_date,trans_type,transdt_id, transdt_amount1 as OriginalAmount1, transdt_amount2 as OriginalAmount2 from transdt left join trans on transdt.trans_id = trans.trans_id ) as transQuery
		on x.journal_type = transQuery.trans_type  and x.relation_id = transQuery.transdt_id

	LEFT JOIN 
			( SELECT purchase_date AS trans_Date, journal_type, supplier_code, purchase_reference,Purchase_TotalBase1  as OriginalAmount1,Purchase_TotalBase2  as OriginalAmount2 FROM purchases   )
			AS transQuery1 ON x.journal_type = transQuery1.journal_type
			AND x.ledger_number = transQuery1.supplier_code
			AND x.Trans_reference = transQuery1.purchase_reference
		
	WHERE
		x.ledger_number between ifnull($fromledger,0) and ifNull($toledger, 9999999999999999)
		AND x.form_id IS NULL
		and upper(x.company) =  Upper('".$MainCompanyName[0]."')
		AND Date_format( x.Detaillink_date, '%Y-%m-%d' ) BETWEEN ifNull( $fromdate, date_format( x.Detaillink_date, '%Y-%m-%d' ) )
		AND ifNull( $todate, date_format( x.Detaillink_date, '%Y-%m-%d' ) ) 
		 
	) AS add_Info";
// echo $query;

	   
$query = $query." Order by  SupplierCode,SalesDate,SalesRefer ,Detaillink_date ";
// $query = $query." Order by   SalesDate ,SalesRefer ";

$query = "
select  InvoiceId,
	SupplierCode,
	SupplierName,
	date_format( SalesDate, '%d-%m-%Y' ) AS SalesDate,
	SalesRefer,
	headerjournal,
	round(SalesTotalBase1,5) as SalesTotalBase1,
	round(SalesTotalBase2,5) as SalesTotalBase2,
	date_format( Detaillink_date, '%d-%m-%Y' ) AS Detaillink_date,
	detailreference,
	detailjournal,
	round(TransPaidBase1,2) as TransPaidBase1,
	round(TransPaidBase2,2) as TransPaidBase2,
	round(TransRemBase1,2) as TransRemBase1,
	round(TransRemBase2,2) as TransRemBase2,
	RemainDays,
	detaillink_id,
	counter,
	round(totalpaid1,2) as totalpaid1,
	round(totalpaid2,2) as totalpaid2,
	round(PrevAmount1,2) as PrevAmount1,
	round(PrevAmount2,2) as PrevAmount2,
	CreditLimits,
	PaymentTerms,
	date_format( value_date, '%Y-%m-%d' ) AS value_dateX,
	date_format( value_date, '%d-%m-%Y' ) AS value_date,
	trDescription,
	round(OriginalAmount1,2) as OriginalAmount1,
	round(OriginalAmount2,2) as OriginalAmount2,
	DATEDIFF( value_date, now() ) AS ovd 

	   from ( ".$query."
   ) as fq  ";
   
  

// if($dueInvs==1)
// echo $query = $query . " where DATEDIFF(value_dateX , $agingdate ) > 0 ";

	// $query =" select * from (" . $query . " )as X  order by SupplierCode,SalesRefer,SalesDate,detaillink_date"; 
    // echo $query; echo "<br>";
 //echo $query;//exit;
 	
$ArrayTotalByReport   = Array();
$ArrayTotalByMaster   = Array();
$ArraySalesAmount     = Array();
$ArraySalesRefer      = Array();

$ArrayAllTotal		 = Array();


$PeriodBal = 0;
$remainingAmount = 0;
$totalpaidamt = 0;
$totalremainamt = 0;

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

$ref = '';
$jourtype = '';
$headerid = '';
// echo $query;
$result = mysql_query($query,$connection) or die(mysql_error());

$colorSwitcherIndex = 1;
$FR = 0;
$currentSupp= '';

$ct = 0;


while($rows=mysql_fetch_array($result)){
	if($ct == 0)  {
		$ct++;
		}
	$FR++;
	extract($rows); 
	$color1 = "style='background-color: #FFFFFF'";
	
	$color2 = "style='background-color: #d3d3d3'";
	  
    // Master By Options Names and Totals
	if (trim($MasterByCode) != trim($SupplierCode) && $MasterByCode != '') {
			 
		$StyleClass  = 'totals';
		$TotalsLabel = 'Supplier Total';
		DisplayTotals($ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $StyleClass,$dues) ;
		 
		
		echo "<tr><td colspan='$ColsSpan'>&nbsp;</td></tr>";
	} 
	
			 

	if ($MasterByCode == '' && $MasterByCode != $SupplierCode) {
		
		$MasterByCode = $SupplierCode;
		//if ($MasterByCode == '' || $MasterByCode != $ClientCode) { 
		
		if ($displaycur == $Base1) {
			$BalanceAmount = $PrevAmount1;
		}
		else if ($displaycur == $Base2){
			$BalanceAmount = $PrevAmount2;
		}
		$fromdate = $_GET['fromdate'];
        $todate = $_GET['todate'];
        $agingdate = $_GET['agingdate']; 
		if ($displaycur == $Base1) {
            $Balance =   $RemaingAmounts - $extra_Amounts ;
            $stmntLink = "rep_statementofaccount.php?fromdate=$fromdate&todate=$todate&fromledger=$SupplierCode&toledger=$SupplierCode&dateoption=1&transaction=3&ledgeroption=1&curr=0&currbase1=1&currbase2=0&cum=1&alltypes=0&exclude=0&showunposted=0&prtfolio=1&prtref=1&prtdesc=1&prtvaluedate=0&prtjvtype=0&prtcostcentc=0&prtcostcent=0&prtproject=0&prtprojectc=0&prevbal=1&dtjv=0&dtdate=1&checks=0&parentprj=0&prtaging=0&prtheader=1&prtcstjour=0&prtwording=0&prtwnac=0&showman=0&varprtbreak=1&prtshowuser=0&reporttype=1&userlevel=$FI_BelongsToGrp&grpsalesman=0";
        }else{
            $Balance =   $RemaingAmounts - $extra_Amountsb2 ;
            $stmntLink = "rep_statementofaccount.php?fromdate=$fromdate&todate=$todate&fromledger=$SupplierCode&toledger=$SupplierCode&dateoption=1&transaction=3&ledgeroption=1&curr=0&currbase1=0&currbase2=1&cum=1&alltypes=0&exclude=0&showunposted=0&prtfolio=1&prtref=1&prtdesc=1&prtvaluedate=0&prtjvtype=0&prtcostcentc=0&prtcostcent=0&prtproject=0&prtprojectc=0&prevbal=1&dtjv=0&dtdate=1&checks=0&parentprj=0&prtaging=0&prtheader=1&prtcstjour=0&prtwording=0&prtwnac=0&showman=0&varprtbreak=1&prtshowuser=0&reporttype=1&userlevel=$FI_BelongsToGrp&grpsalesman=0";
        }
		echo "<tr class='group' >"; 
		echo "   <td>&nbsp;</td>";
		echo "</tr>";
		echo "<tr class='group' >";
		echo "	 <td colspan='4'>Supplier: <a target='_blank' href= '$stmntLink'>".$SupplierCode." - ".$SupplierName."</a> </td>";
		echo "	 <td colspan='2'>CL: ".number_format($CreditLimits, $DecimalBase)."</td>";
		echo "	 <td colspan='2'>PT:  ".$PaymentTerms."</td>";
		
		//echo "   <td colspan='7' align='left' valign='top'>Balance:  ". format_currency($BalanceAmount, $DecimalBase) ." $displaycur</td>";
		
		echo "   <td colspan='7' align='left' valign='top'>&nbsp;</td>";
		echo "   <td>&nbsp;</td>";
		echo "</tr>";
		
		
		echo "<tr><td colspan='$ColsSpan'><hr width='100%' color='white' size='1'></td></tr>";
		
		$bright='border-right: 1px  solid black ;';
		$brleft='border-left: 1px  solid black ;';
		$brtop='border-top: 1px  solid black ;';
		$brbottom='border-bottom: 1px  solid black ;';			
				
		echo"<tr height='25' bgcolor='lightgray'>";	  
		echo"<th align='left' style='font-size: 11pt;font-weight: bold;$brleft;$brtop;$brbottom'>&nbsp;Date</th> 
		<th align='left' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom'>&nbsp;Description</th>
			<th align='left' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom'>&nbsp;Ref.</th>
			<th align='left' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom'>&nbsp;Inv. No</th>
			<th align='center' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom'>&nbsp;Type</th> 
			<th align='right' style='font-size: 11pt;font-weight: bold;$brtop;$bright;$brbottom'>Amount&nbsp;&nbsp;</th>
			
			<th align='left' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom'>&nbsp;&nbsp;Date</th>
			<th align='left' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom'>&nbsp;Ref.</th>
			<th align='left' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom'>&nbsp;Type</th> 
			<th align='right' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom;$bright;'>Original Tr. Amount &nbsp;</th>
			<th align='right' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom'>Deducted Amount&nbsp;</th> 
			<th align='right' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom;$bright;'>Balance</th>
			<th align='right' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom;'>&nbsp;Remain Amount</th>
			<th align='right' style='font-size: 11pt;font-weight: bold;$brtop;$brbottom'>Value Date</th>
			<th align='right' style='font-size: 11pt;font-weight: bold;$bright;$brtop;$brbottom'>Over Due by</th>";
		echo"</tr>";
 

		
		$MasterByCode = $SupplierCode;
		$MasterByName = $SupplierName;
		$dues = 0 ;
		unset($ArrayTotalByMaster);
		unset($ArraySalesAmount);
		unset($ArraySalesRefer); 
		unset($ArraySupTotal);
		 
	}

	 
	if ($displaycur == $Base1) {
		
		$NetAmount     = $SalesTotalBase1;
		$PaidAmount    = $TransPaidBase1;
		if($ref != $SalesRefer || $jourtype != $headerjournal || $headerid != $InvoiceId) $remainingAmount = $NetAmount;
		$remainingAmount = $remainingAmount - $PaidAmount;
		$totalpaidamt = $totalpaid1;
		$totalremainamt = $TransRemBase1;
		$myOriginalAmount = $OriginalAmount1;
	}
	else if ($displaycur == $Base2){
		
		$NetAmount     = $SalesTotalBase2;
		$PaidAmount    = $TransPaidBase2;
		if($ref != $SalesRefer || $jourtype != $headerjournal || $headerid != $InvoiceId) $remainingAmount = $NetAmount;
		$remainingAmount = $remainingAmount - $PaidAmount;
		$totalpaidamt = $totalpaid2;
		$totalremainamt = $TransRemBase2;
		$myOriginalAmount = $OriginalAmount2;
	}
	// jp color switcher
    if ($ref != $SalesRefer || $jourtype != $headerjournal || $headerid != $InvoiceId) {
		if($FR > 1)		{
			$colorSwitcherIndex++;	
			$ct = 1;
		}
				
    }
	($colorSwitcherIndex % 2 == 0 ) ? $color = $color2 : $color=$color1;
	// -- end jp color switcher
	 



	if ($ref != $SalesRefer || $jourtype != $headerjournal || $headerid != $InvoiceId) {
		$ArrayAllTotal['AllNetAmount'] = $ArrayAllTotal['AllNetAmount'] + $NetAmount;
		$ArraySupTotal['SupNetAmount'] = $ArraySupTotal['SupNetAmount'] + $NetAmount;
		
		($InvoiceId != null) ? $mydate = $SalesDate : $mydate= '--'; 
		($InvoiceId != null) ? $myValue_date = $value_date : $myValue_date  = '--'; 
		($InvoiceId != null) ? $mySalesRefer = $SalesRefer : $mySalesRefer  = '--'; 
		($InvoiceId != null) ? $myheaderjournal = $headerjournal : $myheaderjournal  = '--'; 
		($InvoiceId != null) ? $mydisplaycur = $displaycur : $mydisplaycur  = '--'; 
		($InvoiceId != null) ? $myNetAmount = format_currency($NetAmount, $DecimalBase)  : $myNetAmount  = '--';
	}
	if ($InvoiceId != null) $PeriodBal = $PeriodBal + $myNetAmount; 
	
	
	$Balance = $PeriodBal - format_currency($NetAmount, $DecimalBase);
	 
	
	$ArrayAllTotal['AllPaidAmount'] = $ArrayAllTotal['AllPaidAmount'] + $PaidAmount;	
	$ArrayAllTotal['AllRemainAmount'] = $ArrayAllTotal['AllRemainAmount'] + $remainingAmount;	 
	$balance =   floatval($ArrayAllTotal['AllNetAmount']) - floatval($ArrayAllTotal['AllPaidAmount']);  
	  
	$ArraySupTotal['SupPaidAmount'] = $ArraySupTotal['SupPaidAmount'] + $PaidAmount;	
	$ArraySupTotal['SupRemainAmount'] = floatval($ArraySupTotal['SupRemainAmount']) + $remainingAmount;	 
	$balance =   $ArraySupTotal['SupNetAmount'] - $ArraySupTotal['SupPaidAmount'];  
	$balance1 = format_currency($balance, $DecimalBase);
	
	
	
	$dispRem = '';
	$dispVDate = '';
	$isBold = '';
	if($ct == $counter){
		if(round(abs($remainingAmount),2)  > 0.005  )  {
			// if($RemainDays > 0 && $InvoiceId != null && $myheaderjournal != 'OP')
			if($RemainDays < 0 && $InvoiceId != null && $myheaderjournal != 'OP')
			{
				 $dues = $dues + $remainingAmount;
			}
			
			$dispRem = $RemainDays;
			$dispVDate = $myValue_date; 
		}else{
			$dispRem = '';
			$dispVDate = '';
		}
		$isBold = 'font-weight : 700';
		if($myheaderjournal == 'OP'){
			$dispRem = '';
			$dispVDate = '';
		}
	}
 
	if($isdetailed == 1 ){
		if($dispRem!='' && $dispVDate!= '')$dispODb = $dispRem * -1; else $dispODb ='';
		 
		if($dueInvs == 1 && $ovd < 0){
			//leftSide
			if($ref != $SalesRefer || $jourtype != $headerjournal || $headerid != $InvoiceId){ 
				
				echo "<tr  $color>";
				echo "   <td align='left' valign='top' style='border-left:1px solid black; padding-left:2px;'> ". $mydate ."</td>";
				
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". $trDescription ."</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". $mySalesRefer ."</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". GetInvNo($mySalesRefer,$myheaderjournal,$connection)  ."</td>";
				echo "   <td align='center' valign='top' style='padding-left:2px;'>". $myheaderjournal ."</td>"; 
			
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>". $myNetAmount ." &nbsp; </td>";
			

			} else {
				$btop = '';
				echo "<tr $color>";
				echo "   <td align='left' valign='top' style='border-left:1px solid black;  padding-left:2px;'></td>"; 
				echo "   <td align='left' valign='top' style='padding-left:2px;'></td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'></td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'></td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;'></td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'></td>";
				
				
			}
			
			// https://azargrp.co/contract/Form_Trans.php?actionmode=&mainaction=edit&txtTransId=13614&message=&TransType=DV
			// https://azargrp.co/contract/Form_TransPreview.php?TransId=15804&TransType=DV
			
			//Right Side
			echo "   <td align='left' valign='top' style='padding-left:2px;'>  $Detaillink_date </td>";
			echo "   <td align='left' valign='top' style='padding-left:2px;'>$detailreference</td>";
			echo "   <td align='left' valign='top' style='padding-left:2px;'>$detailjournal</td>"; 
			echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>". format_currency($myOriginalAmount, $DecimalBase) ."</td>";
			echo "   <td align='right' valign='top' style='padding-right:2px;'>". format_currency($PaidAmount, $DecimalBase) ."</td>";
			
			echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>  $balance1 </td>";
			echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'>". format_currency($remainingAmount, $DecimalBase). "</td>"; 
			
			echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'> $dispVDate </td>";
			
			echo "   <td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;$isBold;'>".  $dispODb ."</td>";
			echo "</tr>"; 
		}else if($dueInvs == 0){
		//leftSide
			if($ref != $SalesRefer || $jourtype != $headerjournal || $headerid != $InvoiceId){
				
					echo "<tr  $color>";
					echo "   <td align='left' valign='top' style='border-left:1px solid black; padding-left:2px;'> ". $mydate ."</td>";
					
					echo "   <td align='left' valign='top' style='padding-left:2px;'>". $trDescription ."</td>";
					echo "   <td align='left' valign='top' style='padding-left:2px;'>". $mySalesRefer ."</td>";
					echo "   <td align='left' valign='top' style='padding-left:2px;'>". GetInvNo($mySalesRefer,$myheaderjournal,$connection) ."</td>";
					echo "   <td align='center' valign='top' style='padding-left:2px;'>". $myheaderjournal ."</td>"; 
				
					echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>". $myNetAmount ." &nbsp; </td>";
				

				} else {
					$btop = '';
					echo "<tr $color>";
					echo "   <td align='left' valign='top' style='border-left:1px solid black;  padding-left:2px;'></td>"; 
					echo "   <td align='left' valign='top' style='padding-left:2px;'></td>";
					echo "   <td align='left' valign='top' style='padding-left:2px;'></td>";
					echo "   <td align='left' valign='top' style='padding-left:2px;'></td>";
					echo "   <td align='right' valign='top' style='padding-right:2px;'></td>";
					echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'></td>";
					
					
				}
				
				// https://azargrp.co/contract/Form_Trans.php?actionmode=&mainaction=edit&txtTransId=13614&message=&TransType=DV
				// https://azargrp.co/contract/Form_TransPreview.php?TransId=15804&TransType=DV
				
				//Right Side
				echo "   <td align='left' valign='top' style='padding-left:2px;'>  $Detaillink_date </td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>$detailreference</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>$detailjournal</td>"; 
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>". format_currency($myOriginalAmount, $DecimalBase) ."</td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;'>". format_currency($PaidAmount, $DecimalBase) ."</td>";
				
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>  $balance1  </td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'>". format_currency($remainingAmount, $DecimalBase). "</td>"; 
				
				echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'> $dispVDate </td>";
				
				echo "   <td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;$isBold;'>".  $dispODb ."</td>";
				echo "</tr>";
		}
	}else{
		if($dueInvs == 1 && $ovd <0){
			if($counter == 0 && empty($form_id) ) {
				if($dispRem!='' && $dispVDate!= '')$dispODb = $dispRem * -1; else $dispODb ='';
				echo "<tr  $color>";
				echo "   <td align='left' valign='top' style='border-left:1px solid black; padding-left:2px;'> ". $mydate ."</td>";
				
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". $trDescription ."</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". $mySalesRefer ."</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". GetInvNo($mySalesRefer,$myheaderjournal,$connection) ."</td>";
				echo "   <td align='center' valign='top' style='padding-left:2px;'>". $myheaderjournal ."</td>"; 
			
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>". $myNetAmount ." &nbsp; </td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>  &nbsp;&nbsp;$Detaillink_date </td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>$detailreference</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>$detailjournal</td>"; 
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>". format_currency($myOriginalAmount, $DecimalBase) ."</td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;'>". format_currency($PaidAmount, $DecimalBase) ."</td>";
				
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>  $balance1 </td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'>". format_currency($remainingAmount, $DecimalBase). "</td>"; 
				
				echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'> $dispVDate</td>";
				echo "   <td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;$isBold;'>". $dispODb ."</td>";
				echo "</tr>"; 	
			}else 
			if ($counter>0 && $ct == $counter ) {
			
				if($dispRem!='' && $dispVDate!= '')$dispODb = $dispRem * -1; else $dispODb ='';
				echo "<tr  $color>";
				echo "   <td align='left' valign='top' style='border-left:1px solid black; padding-left:2px;'> ". $mydate ."</td>";
				
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". $trDescription ."</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". $mySalesRefer ."</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". GetInvNo($mySalesRefer,$myheaderjournal,$connection) ."</td>";
				echo "   <td align='center' valign='top' style='padding-left:2px;'>". $myheaderjournal ."</td>"; 
			
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>". $myNetAmount ." &nbsp; </td>";


				echo "   <td align='left' valign='top' style='padding-left:2px;'>  --  </td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'> --</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'> -- </td>"; 
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'> -- </td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;'> ". format_currency($totalpaid1, $DecimalBase) ."</td>";
				
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'> ". $balance1  ." </td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'>". format_currency($remainingAmount, $DecimalBase). "</td>"; 
				
				echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'> $dispVDate</td>";
				echo "   <td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;$isBold;'>". $dispODb ." </td>";
				echo "</tr>"; 	
				
			}
			
		}else if($dueInvs == 0 ){
		
			if($counter == 0 && empty($form_id) ) {
				if($dispRem!='' && $dispVDate!= '')$dispODb = $dispRem * -1; else $dispODb ='';
				echo "<tr  $color>";
				echo "   <td align='left' valign='top' style='border-left:1px solid black; padding-left:2px;'> ". $mydate ."</td>";
				
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". $trDescription ."</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". $mySalesRefer ."</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". GetInvNo($mySalesRefer,$myheaderjournal,$connection) ."</td>";
				echo "   <td align='center' valign='top' style='padding-left:2px;'>". $myheaderjournal ."</td>"; 
			
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>". $myNetAmount ." &nbsp; </td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>  &nbsp;&nbsp;$Detaillink_date </td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>$detailreference</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>$detailjournal</td>"; 
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>". format_currency($myOriginalAmount, $DecimalBase) ."</td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;'>". format_currency($PaidAmount, $DecimalBase) ."</td>";
				
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>  $balance1 </td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'>". format_currency($remainingAmount, $DecimalBase). "</td>"; 
				
				echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'> $dispVDate</td>";
				echo "   <td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;$isBold;'>". $dispODb ."</td>";
				echo "</tr>"; 	
			}else 
			if ($counter>0 && $ct == $counter ) {
			
				if($dispRem!='' && $dispVDate!= '')$dispODb = $dispRem * -1; else $dispODb ='';
				echo "<tr  $color>";
				echo "   <td align='left' valign='top' style='border-left:1px solid black; padding-left:2px;'> ". $mydate ."</td>";
				
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". $trDescription ."</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". $mySalesRefer ."</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'>". GetInvNo($mySalesRefer,$myheaderjournal,$connection) ."</td>";
				echo "   <td align='center' valign='top' style='padding-left:2px;'>". $myheaderjournal ."</td>"; 
			
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'>". $myNetAmount ." &nbsp; </td>";


				echo "   <td align='left' valign='top' style='padding-left:2px;'>  --  </td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'> --</td>";
				echo "   <td align='left' valign='top' style='padding-left:2px;'> -- </td>"; 
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'> -- </td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;'> ". format_currency($totalpaid1, $DecimalBase) ."</td>";
				
				echo "   <td align='right' valign='top' style='padding-right:2px;$bright;'> ". $balance1  ."</td>";
				echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'>". format_currency($remainingAmount, $DecimalBase). "</td>"; 
				
				echo "   <td align='right' valign='top' style='padding-right:2px;$isBold;'> $dispVDate</td>";
				echo "   <td align='right' valign='top' style='border-right:1px solid black; padding-right:2px;$isBold;'>". $dispODb ." </td>";
				echo "</tr>"; 	
				
			}
			
		}
		
	}
	

	$ct++;
	$RefFound = 0;
	$count = count ($ArraySalesRefer); 
	for ($j=0; $j<$count; $j++){
		if ($ArraySalesRefer[$j] == $SalesRefer)
			$RefFound = 1;
	} 

	if ($RefFound == 0) 
		$ArraySalesRefer[$count] = $SalesRefer;
					
	if($ref != $SalesRefer || $jourtype != $headerjournal || $headerid != $InvoiceId) $ArraySalesAmount[$SalesRefer] = $ArraySalesAmount[$SalesRefer] + $NetAmount;
	$ArrayTotalByMaster['NetAmount']  = 0;
	
	$count = count ($ArraySalesRefer);  
	for ($j=0; $j<$count; $j++){
		$ArrayTotalByMaster['NetAmount']  = $ArrayTotalByMaster['NetAmount']  + $ArraySalesAmount[$ArraySalesRefer[$j]];
	}
	 
	$ArrayTotalByMaster['PaidAmount']   = $ArrayTotalByMaster['PaidAmount'] + $PaidAmount;
	$ArrayTotalByMaster['RemainAmount'] = $ArrayTotalByMaster['NetAmount'] - $ArrayTotalByMaster['PaidAmount'];
	$jourtype = $headerjournal;
	$ref = $SalesRefer;
	$headerid = $InvoiceId;
	$col+=1; 
}


if ($MasterByCode != '') {
	
	$StyleClass  = 'totals';
	$TotalsLabel = 'Supplier Total';
	DisplayTotals($ArrayTotalByMaster, $DecimalBase, $TotalsLabel, $StyleClass , $dues ) ;  
}   
			
$StyleClass  = 'totals';
$TotalsLabel = 'All Suppliers Total';
DisplayAllTotals($ArrayAllTotal, $DecimalBase, $TotalsLabel, $StyleClass  ) ;

echo "</table>";

function DisplayTotals($PArrayTotal, $PDecimalBase, $PTotalsLabel, $PStyleClass, $supplierdues) {

	echo "<tr class='".$PStyleClass."' style='background-color:lightgray ;border-top:1px solid black;'>";
	echo "   
	<td align='left'  style='background-color:lightgray ;border-top:1px solid black;'  valign='top' colspan='5' >".$PTotalsLabel."</td>";
	echo "   <td align='right' style='background-color:lightgray ;border-top:1px solid black;'  valign='top' >". format_currency($PArrayTotal['NetAmount'], $PDecimalBase) ."</td>";
	echo "   <td align='left'  style='background-color:lightgray ;border-top:1px solid black;'  valign='top'  colspan='3'>&nbsp;</td>";
	echo "   <td align='left'  style='background-color:lightgray ;border-top:1px solid black;'  valign='top' >&nbsp;</td>";
	echo "   <td align='right' style='background-color:lightgray ;border-top:1px solid black;'  valign='top' >". format_currency($PArrayTotal['PaidAmount'], $PDecimalBase) ."</td>";
	echo "   <td valign='top' align='right'  style='background-color:lightgray ;border-top:1px solid black;'>". format_currency($PArrayTotal['RemainAmount'], $PDecimalBase) ."</td>";
	
	echo "   <td  align='center' style='background-color:lightgray ;border-top:1px solid black;font-size: 14px!important; font-weight: bolder;'  colspan ='3'  valign='top' > &nbsp;Due Amounts :   ".  format_currency($supplierdues, $PDecimalBase)  ."   </td>";
	// echo "   <td align='left'  style='background-color:lightgray ;border-top:1px solid black;'  valign='top' >&nbsp;</td>";
	echo "</tr>"; 
	
}


function DisplayAllTotals($PArrayTotal, $PDecimalBase, $PTotalsLabel, $PStyleClass) {
	
	echo "<tr><td colspan='15'><hr width='100%' color='black' size='1'></td></tr>";
	
	echo "<tr class='".$PStyleClass."'>";
	echo "   <td align='left'  valign='top' colspan='4' >".$PTotalsLabel."</td>";
	echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['AllNetAmount'], $PDecimalBase) ."</td>";
	echo "   <td align='left'  valign='top'  colspan='4'>&nbsp;</td>"; 
	echo "   <td align='right' valign='top' >". format_currency($PArrayTotal['AllPaidAmount'], $PDecimalBase) ."</td>";
	echo "   <td align='right' valign='top' >". format_currency(($PArrayTotal['AllNetAmount'] - $PArrayTotal['AllPaidAmount']), $PDecimalBase) ."</td>";
	echo "   <td align='left'  valign='top' >&nbsp;</td>";
	echo "   <td align='left'  valign='top' colspan='2' >&nbsp;</td>"; 
	echo "</tr>"; 
	
}
function GetInvNo($invRef,$invType,$connection){
	if($invType == 'JV'){
		$queryInv = "select manual_no from journal where journal_refGovernment =   $invRef  limit 1"; 
		$invRes = mysql_query($queryInv,$connection);
		$invNovalue = mysql_fetch_array($invRes);	
	}else{
		$queryInv = "select purchase_InvoiceNo from purchases where purchase_reference = $invRef and journal_type = '$invType' limit 1"; 
		$invRes = mysql_query($queryInv,$connection);
		$invNovalue = mysql_fetch_array($invRes);
	}
return $invNovalue[0];
}

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;
}
// <script language=javascript>
// if (typeof(window.print) != 'undefined')
// {
    // window.print();
// }
// </script> 
if ($printaccess==1)
print <<< HERE

</BODY>
</HTML>
HERE;
?>