<?php

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

include("config.inc.php");
include("Functions_Trans.php");

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


$querylog="SELECT FA_InvoicesAllocation as loginaccess, 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('".$HTTP_SESSION_VARS['dbName']."')	";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

if ($loginaccess=='' or $loginaccess==0)
	header("location:menu.php");




//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ifNull(Client_ValidateProject,0) As Client_ValidateProject, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_RestrictProjCost,0) As Module_RestrictProjCost, ifNull(Module_RestrictCost,0) As Module_RestrictCost, ".
			 " ifNull(Module_ProjectParent,0) As Module_ProjectParent, ifNull(Module_CostCenterParent,0) As Module_CostCenterParent, ".
			 " ifNull(Module_Delivery,0) As Module_Delivery, ifNull(Module_AcctrxPostRV,0) As Module_AcctrxPostRV, ".
			 " ifNull(Module_AcctrxPostCV,0) As Module_AcctrxPostCV ". 
             " 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 ".$HTTP_SESSION_VARS['dbLabel'].".loginstk on (($Module_ProjectParent=1 and project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%')) or ($Module_ProjectParent=0 and project.project_code = loginstk.project_code )) ".
			  " where user_account='".$HTTP_SESSION_VARS['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 ".$HTTP_SESSION_VARS['dbLabel'].".loginstk on (($Module_CostCenterParent=1 and costcent.costcent_code like concat(ifnull(loginstk.costcent_code,costcent.costcent_code),'%')) or ($Module_CostCenterParent=0 and costcent.costcent_code = loginstk.costcent_code )) ".
			   " where user_account='".$HTTP_SESSION_VARS['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);	

// Setting Initial Values For Parameters
$querydate=" Select Date_Format(Min(Journal_date),'%d/%m/%Y') As DefaultFromDate, ".
           " Date_Format(Max(Journal_date),'%d/%m/%Y') As DefaultToDate, Date_Format(NOW(),'%d/%m/%Y') As DefaultAgingDate ".
		   " From JournalDt ";
$resultdate=mysql_query($querydate,$connection) or die(mysql_error());
$rowdate=mysql_fetch_row($resultdate);

if (!isset($fromdate))  $fromdate = $rowdate[0];
if (!isset($todate))    $todate   = $rowdate[1];

if (!isset($dispfromdate))  $dispfromdate = $fromdate;
if (!isset($disptodate))    $disptodate   = $todate;

if (!empty($fromdate))  $fromdate = explodeword($fromdate);
if (!empty($todate))    $todate   = explodeword($todate);    
//echo $fromdate;
$sub_query = "Select Ledger_Name From Ledger Where Ledger_Number = $fromledger";
$sub_result = selectData($connection, $sub_query);
$fromledgername = $sub_result[0];

$sub_query = "Select Ledger_Name From Ledger Where Ledger_Number = $toledger";
$sub_result = selectData($connection, $sub_query);
$toledgername = $sub_result[0];

$dispfromledger 	= $fromledger;
$dispfromledgername = $fromledgername;
$disptoledger 		= $toledger;
$disptoledgername 	= $toledgername;

$fromledger    = GetSQLValueString($fromledger, 'text');
$toledger      = GetSQLValueString($toledger, 'text');




print <<< HERE
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 


<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">
<link rel="stylesheet" type="text/css" media="all" href="js/grid/UI_DataGrid_V1.css">
<script type="text/javascript" language="javascript">

function SearchForm() {
	var x=document.invoices;
	
	x.actionmode.value = 'Search';
	x.submit();
}

function SubmitForm() {
	var x=document.invoices;
	
	var vFromLedger = x.fromledger.value;
	var vToLedger   = x.toledger.value;
	var vFromDate   = x.fromdate.value;
	var vToDate     = x.todate.value;
	
	var vRemainAmountSI = 0;
	var vRemainAmountSR = 0;
	var vRemainAmountRV = 0;
	var vRemainAmountCV = 0;
	var vRemainAmountJV = 0;
	var vRemainAmountDB = 0;
	var vTotalPaidAmount = 0;
	var vClosedCounter = 0;
	
	var vSchemaSI = '';
	var vSchemaSR = '';
	var vSchemaRV = '';
	var vSchemaCV = '';
	var vSchemaJV = '';
	var vSchemaDB = '';
	
	var vPaidAmountsArray  = new Array();
	
	var vInvoicesID    = new Array();
	var vSalesJVID     = new Array();
	var vOtherDBID     = new Array();
	var vRetInvoicesID = new Array();
	var vReceiptsID    = new Array();
	var vCredNotesID   = new Array();
	var vJournalsID    = new Array();
	
	for (var i=0; i<document.getElementsByName('ChkSI[]').length; i++) {
		if (document.getElementsByName('ChkSI[]')[i].checked) {
			vSchemaSI = document.getElementsByName('DirSchemaSI[]')[i].value;
			vRemainAmountSI	= document.getElementsByName('RemainAmountSI[]')[i].value;
			
			if (document.getElementsByName('JourTypeSI[]')[i].value != 'JS'){ 
				vInvoicesID.push([document.getElementsByName('ChkSI[]')[i].value, vSchemaSI]);
			} else {
				vSalesJVID.push([document.getElementsByName('ChkSI[]')[i].value, vSchemaSI]);
			}
			
		}	
	}
	for (var i=0; i<document.getElementsByName('ChkDB[]').length; i++) {
		if (document.getElementsByName('ChkDB[]')[i].checked) {
			vSchemaDB = document.getElementsByName('DirSchemaDB[]')[i].value;
			vRemainAmountDB	= document.getElementsByName('RemainAmountDB[]')[i].value;
			vOtherDBID.push([document.getElementsByName('ChkDB[]')[i].value, vSchemaDB]);
		}	
	}
	
	for (var i=0; i<document.getElementsByName('ChkSR[]').length; i++) {
		if (document.getElementsByName('ChkSR[]')[i].checked) {
			vSchemaSR = document.getElementsByName('DirSchemaSR[]')[i].value;
			vRetInvoicesID.push([document.getElementsByName('ChkSR[]')[i].value, vSchemaSR]);
			vRemainAmountSR	= document.getElementsByName('RemainAmountSR[]')[i].value;
			vPaidAmountsArray.push(vRemainAmountSR);
		}	
	}
	for (var i=0; i<document.getElementsByName('ChkRV[]').length; i++) {
		if (document.getElementsByName('ChkRV[]')[i].checked) {
			vSchemaRV = document.getElementsByName('DirSchemaRV[]')[i].value;
			vReceiptsID.push([document.getElementsByName('ChkRV[]')[i].value, vSchemaRV]);
			vRemainAmountRV	= document.getElementsByName('RemainAmountRV[]')[i].value;
			vPaidAmountsArray.push(vRemainAmountRV);
		}	
	}
		
	for (var i=0; i<document.getElementsByName('ChkCV[]').length; i++) {
		if (document.getElementsByName('ChkCV[]')[i].checked) {
			vSchemaCV = document.getElementsByName('DirSchemaCV[]')[i].value;
			vCredNotesID.push([document.getElementsByName('ChkCV[]')[i].value, vSchemaCV]);
			vRemainAmountCV	= document.getElementsByName('RemainAmountCV[]')[i].value;
			vPaidAmountsArray.push(vRemainAmountCV);
		}	
	}
	for (var i=0; i<document.getElementsByName('ChkJV[]').length; i++) {
		if (document.getElementsByName('ChkJV[]')[i].checked){
			vSchemaJV = document.getElementsByName('DirSchemaJV[]')[i].value;
			vJournalsID.push([document.getElementsByName('ChkJV[]')[i].value, vSchemaJV]);
			vRemainAmountJV	= document.getElementsByName('RemainAmountJV[]')[i].value;
			vPaidAmountsArray.push(vRemainAmountJV);
		}	
	}
	
	
	vPaidAmountsArray.sort(function(a,b){return b-a});
	for (var i=0; i < vPaidAmountsArray.length; i++) {
		var vAmount = vPaidAmountsArray[i]; 
		vTotalPaidAmount = parseFloat(vTotalPaidAmount) + parseFloat(vAmount);
		
		if(roundNumber(vTotalPaidAmount,2) > roundNumber(vRemainAmountSI,2)) vClosedCounter += 1;
	}
	

	
	if (vInvoicesID.length == 0 && vSalesJVID.length == 0 && vOtherDBID.length == 0) {
		alert("Please select at least one invoice.");
	} 
	else if (vRetInvoicesID.length == 0 && vReceiptsID.length == 0 && vCredNotesID.length == 0 && vJournalsID.length == 0) {
		alert("Please select at least one receipt/return invoice/credit note or others.");
	}	
	else if (vClosedCounter > 1) {
		alert("Please check for total amount paid.");
	}
	else {
		vInvoicesID    = vInvoicesID.join('-');
		vRetInvoicesID = vRetInvoicesID.join('-');
		vReceiptsID    = vReceiptsID.join('-');
		vCredNotesID   = vCredNotesID.join('-');
		vJournalsID    = vJournalsID.join('-');
		vSalesJVID     = vSalesJVID.join('-');
		vOtherDBID     = vOtherDBID.join('-');
		
		x.action = "Form_InvoicesAllocation_Actions.php?mode=AllocateInvoices&PInvoicesID="+vInvoicesID+"&PRetInvoicesID="+vRetInvoicesID+
				   "&PReceiptsID="+vReceiptsID+"&PCredNotesID="+vCredNotesID+"&PJournalsID="+vJournalsID+"&PSalesJVID="+vSalesJVID+
				   "&POtherDBID="+vOtherDBID+"&fromledger="+vFromLedger+"&toledger="+vToLedger+"&fromdate="+vFromDate+"&todate="+vToDate;
		x.submit();
	}	

}

function SelectInvoice(TagValue, JourType) {
	
	for (var i=0; i<document.getElementsByName('ChkSI[]').length; i++) {
		document.getElementsByName('ChkSI[]')[i].checked = false;
		if (document.getElementsByName('ChkSI[]')[i].value == TagValue && JourType == 'SI') {
			document.getElementsByName('ChkSI[]')[i].checked = true;
		}
	}
	
	for (var i=0; i<document.getElementsByName('ChkDB[]').length; i++) {
		document.getElementsByName('ChkDB[]')[i].checked = false;
		if (document.getElementsByName('ChkDB[]')[i].value == TagValue && JourType == 'DB') {
			document.getElementsByName('ChkDB[]')[i].checked = true;
		}
	}

}

function showlistledger(str){

	var str1 = 2;
	window.open('select_accountno.php?item='+str+'&accountoption='+str1,'mywindow','width=710,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistProject(frm) {
	window.open('List_SorProject.php?frm='+frm+'&item=','mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistCostcenter(frm){

  window.open('List_SorCostcenter.php?frm='+frm+'&item=','mywindow','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}


function roundNumber(num, dec) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
  newnumber = parseFloat(newnumber); 
  
  return newnumber;
}


</script>
<title>Invoices Allocation</title>
<style type="text/css">

body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
}
body {
	margin-top: 2px;
	margin-left: 1px;
}
a:link {
	text-decoration: none;
	color: #0000FF;
}
a:visited {
	text-decoration: none;
	color: #0000FF;
}
a:hover {
	text-decoration: none;
	color: #0000FF;
}
a:active {
	text-decoration: none;
	color: #0000FF;
}

.style12 {
	font-size: 9px;
	color: #999999;
	font-weight: bold;
}
.style15 {color: #5151FF; font-size: 10px;}
.style16 {
	font-size: 16px;
	color: #FF0000;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
}
.style17 {font-size: 9px}
.style25 {color: #999999; font-weight: bold; font-size: 10px; }
.style26 {color: #FF0000}
.style27 {color: #999999 ;font-size: 10px;}
.style28 {color: #FFFFFF ;font-size: 10px;}

</style>

<link type="text/css" rel="stylesheet" href="dhtmlgoodies_calendar.css?random=20051112" media="screen"></LINK>
<SCRIPT type="text/javascript" src="dhtmlgoodies_calendar.js?random=20060118"></script>
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>
</head>
<body>
<form name='invoices' method='post' action=''>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='message' value='$message' size='200'>
HERE;

//$style= "style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'";

$MainCompanyName=explode('_',$HTTP_SESSION_VARS['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, DirYear ".
			" From ".$HTTP_SESSION_VARS['dbLabel'].".Directories ". 
			" Where Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
			" And ( (ifNull(Date_Format('".$fromdate."','%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) >= Date_Format(StartFinancialDate,'%Y%m') and ifNull(Date_Format('".$todate."','%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) <= Date_Format(EndFinancialDate,'%Y%m')) or   ".
			//"  		(ifNull(Date_Format(". $fromdate.",'%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) <= Date_Format(StartFinancialDate,'%Y%m') and ifNull(Date_Format(". $todate.",'%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) >= Date_Format(EndFinancialDate,'%Y%m')) or ".
			"       (Date_Format(StartFinancialDate,'%Y%m') >= ifNull(Date_Format('".$fromdate."','%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) and Date_Format(StartFinancialDate,'%Y%m') <= ifNull(Date_Format('".$todate."','%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) ) or ".
            "       (Date_Format(EndFinancialDate,'%Y%m') >= ifNull(Date_Format('".$fromdate."','%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) and Date_Format(EndFinancialDate,'%Y%m') <= ifNull(Date_Format('".$todate."','%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) ) ".
			"      )  ".
			" Order By DirYear ";
			
//echo $QueryDir; exit;
$ResultDir=mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir1=mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir2=mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir3=mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir4=mysql_query($QueryDir,$connection) or die(mysql_error());
$ResultDir5=mysql_query($QueryDir,$connection) or die(mysql_error());
$RowsDirCount = mysql_num_rows($ResultDir);

$QueryRestrictPrj = " Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
					" 			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
					"              and (project_code is not null and project_code != '') ".
					"			 ) QP  ";
					
$QueryRestrictCst = " Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
					"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
					"              and (costcent_code is not null and costcent_code != '') ".
					"			 ) QC  ";

					
$j = 0;				
$k = 0;
$QuerySI = '';
$QuerySI =  " Select InvoiceId, ClientCode, ClientName, SalesDate, SalesValueDate, SalesRefer, ".
			" SalesTotalBase1, SalesTotalBase2, SalesRemBase1, SalesRemBase2, OrderSalesDate, JournalType, DirSchema ".
			" From ".
			" (  ";
				
// Reading Data For Many Years Or Different Directories					 
while($RowsDir=mysql_fetch_row($ResultDir)){

    $j = $j + 1;    
	//if ($RowsDirCount > 1)
	   $DirSchema   = $RowsDir[0];
	   $DirFromDate = $RowsDir[1];
	   $DirToDate   = $RowsDir[2];
	   $DirCompany  = $RowsDir[3];
	   $DirYear	    = $RowsDir[4];
	   
	//else
       //$DirSchema = '';	
    
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
		$k = $k + 1; 
				
		if($Module_Delivery == 0 ) {
			$QuerySI = $QuerySI.
					" Select Deliveries.Delivery_Id As InvoiceId, Deliveries.Client_Code As ClientCode, ledger.Ledger_name As ClientName, date_format(Deliveries.Delivery_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(Deliveries.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Deliveries.Delivery_Reference As SalesRefer, ".
					" ifNull(AccLink.Sale_NetTotalBase1,0) As SalesTotalBase1, ifNull(AccLink.Sale_NetTotalBase2,0) As SalesTotalBase2, ".
					" (ifNull(AccLink.Sale_NetTotalBase1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
					" (ifNull(AccLink.Sale_NetTotalBase2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2, ".
					" Deliveries.Delivery_Date As OrderSalesDate, 'SI' As JournalType, '$DirSchema' As DirSchema ".
					" From $DirSchema.Deliveries As Deliveries ".
					//" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Deliveries.Delivery_Reference = Acclink.Link_Ref ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Deliveries.Delivery_Id = Acclink.Link_ID ".
					" Inner Join $DirSchema.Ledger As Ledger on Deliveries.Client_Code = Ledger.ledger_Number ";
					
			if ($projectexist >	0 && $FI_RepRestrictProject == 1)
				$QuerySI = $QuerySI.$QueryRestrictPrj." on Deliveries.project_code like concat(QP.project_code,'%') ";
											 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
				$QuerySI = $QuerySI.$QueryRestrictCst." on Deliveries.costcent_code like concat(QC.costcent_code,'%') ";
		
			$QuerySI = $QuerySI.
					" Where Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ".
					" And Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ".
					" And Deliveries.Client_Code between ifNull(".$fromledger.",Deliveries.Client_Code) and ifNull(". $toledger.",Deliveries.Client_Code) ".
					" And Deliveries.journal_Type = 'DI' ".
					" And IfNull(Deliveries.Delivery_OldData,0) = 0 ".
					" And Acclink.Link_Type In ('DI','SI') ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					" Group By Deliveries.Delivery_Id  ".
					" Having Round(ifNull(SalesRemBase1,0),2) > 0 ".
					" Union ".
					" Select Deliveries.Delivery_Id As InvoiceId, Deliveries.Client_Code As ClientCode, ledger.Ledger_name As ClientName, date_format(Deliveries.Delivery_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(Deliveries.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Deliveries.Delivery_Reference As SalesRefer, ".
					" (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As SalesTotalBase1, ".
					" (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As SalesTotalBase2, ".
					" (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As SalesRemBase1, ".
					" (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As SalesRemBase2, ".
					" Deliveries.Delivery_Date As OrderSalesDate, 'SI' As JournalType, '$DirSchema' As DirSchema ".
					" From $DirSchema.Deliveries As Deliveries ".
					" Inner Join $DirSchema.Ledger As Ledger on Deliveries.Client_Code = Ledger.ledger_Number ";
					
			if ($projectexist >	0 && $FI_RepRestrictProject == 1)
				$QuerySI = $QuerySI.$QueryRestrictPrj." on Deliveries.project_code like concat(QP.project_code,'%') ";
											 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
				$QuerySI = $QuerySI.$QueryRestrictCst." on Deliveries.costcent_code like concat(QC.costcent_code,'%') ";
		
			$QuerySI = $QuerySI.
					" Where Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ".
					" And Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ".
					" And Deliveries.Client_Code between ifNull(".$fromledger.",Deliveries.Client_Code) and ifNull(". $toledger.",Deliveries.Client_Code) ".
					" And Deliveries.journal_Type = 'DI' ".
					" And IfNull(Deliveries.Delivery_OldData,0) = 0 ".
					" And Deliveries.Delivery_Id Not In (Select ifNull(Link_ID,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                          		 	 Where Acclink.Link_Type In ('DI','SI') ".
					" 								 	 And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					"                                	 And upper(Acclink.CompanyName) = upper('".$DirCompany."') ) ";				
					
		} else {
						
			$QuerySI = $QuerySI.
					" Select Sales.Sale_Id As InvoiceId, Sales.Client_Code As ClientCode, ledger.Ledger_name As ClientName, date_format(Sales.Sale_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(Sales.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Sales.Sale_Reference As SalesRefer, ".
					" ifNull(AccLink.Sale_NetTotalBase1,0) As SalesTotalBase1, ifNull(AccLink.Sale_NetTotalBase2,0) As SalesTotalBase2, ".
					" (ifNull(AccLink.Sale_NetTotalBase1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
					" (ifNull(AccLink.Sale_NetTotalBase2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2, ".
					" Sales.Sale_Date As OrderSalesDate, Sales.Journal_Type As JournalType, '$DirSchema' As DirSchema ".
					" From $DirSchema.Sales As Sales ".
					//" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Sales.Sale_Reference = Acclink.Link_Ref ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Sales.Sale_Id = Acclink.Link_ID ".
					" Inner Join $DirSchema.Ledger As Ledger on Sales.Client_Code = Ledger.ledger_Number ";
					
			if ($projectexist >	0 && $FI_RepRestrictProject == 1)
				$QuerySI = $QuerySI.$QueryRestrictPrj." on Sales.project_code like concat(QP.project_code,'%') ";
											 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
				$QuerySI = $QuerySI.$QueryRestrictCst." on Sales.Costcenter_code like concat(QC.costcent_code,'%') ";	
		
			$QuerySI = $QuerySI.
					" Where Date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Sales.Sale_Date,'%Y-%m-%d'))  ".
					" And Date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Sales.Sale_Date,'%Y-%m-%d'))  ".
					" And Sales.Client_Code between ifNull(".$fromledger.",Sales.Client_Code) and ifNull(". $toledger.",Sales.Client_Code) ".
					" And Sales.Journal_Type = 'SI' ".
					" And IfNull(Sales.Sale_OldData,0) = 0 ".
					" And Acclink.Link_Type In ('DI','SI') ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					" Group By Sales.Sale_Id  ".
					" Having Round(ifNull(SalesRemBase1,0),2) > 0 ".
					" Union ".
					" Select Sales.Sale_Id As InvoiceId, Sales.Client_Code As ClientCode, ledger.Ledger_name As ClientName, date_format(Sales.Sale_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(Sales.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Sales.Sale_Reference As SalesRefer, ".
					" (ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) As SalesTotalBase1, ".
					" (ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) As SalesTotalBase2, ".
					" (ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) As TransRemBase1, ".
					" (ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) As TransRemBase2, ".
					" Sales.Sale_Date As OrderSalesDate, Sales.Journal_Type As JournalType, '$DirSchema' As DirSchema ".
					" From $DirSchema.Sales As Sales ".
					" Inner Join $DirSchema.Ledger As Ledger on Sales.Client_Code = Ledger.ledger_Number ";
					
			if ($projectexist >	0 && $FI_RepRestrictProject == 1)
				$QuerySI = $QuerySI.$QueryRestrictPrj." on Sales.project_code like concat(QP.project_code,'%') ";
											 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
				$QuerySI = $QuerySI.$QueryRestrictCst." on Sales.Costcenter_code like concat(QC.costcent_code,'%') ";	
		
			$QuerySI = $QuerySI.
					" Where Date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Sales.Sale_Date,'%Y-%m-%d'))  ".
					" And Date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Sales.Sale_Date,'%Y-%m-%d'))  ".
					" And Sales.Client_Code between ifNull(".$fromledger.",Sales.Client_Code) and ifNull(". $toledger.",Sales.Client_Code) ".
					" And Sales.Journal_Type = 'SI' ".
					" And IfNull(Sales.Sale_OldData,0) = 0 ".
					" And Sales.Sale_Id Not In ( Select ifNull(Link_ID,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                            Where Acclink.Link_Type In ('DI','SI') ".
					" 							 And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					"                            And upper(Acclink.CompanyName) = upper('".$DirCompany."') ) ";
					
		}
		
		$QuerySI = $QuerySI.
					" Union ".
					" Select SalesJV.SalesJV_Id As InvoiceId, SalesJV.Client_Code As ClientCode, ledger.Ledger_name As ClientName, date_format(SalesJV.SalesJV_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(SalesJV.JournalDt_ValueDate,'%d/%m/%Y') As SalesValueDate, SalesJV.SalesJV_Reference As SalesRefer, ".
					" ifNull(AccLink.Sale_NetTotalBase1,0) As SalesTotalBase1, ifNull(AccLink.Sale_NetTotalBase2,0) As SalesTotalBase2, ".
					" (ifNull(AccLink.Sale_NetTotalBase1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
					" (ifNull(AccLink.Sale_NetTotalBase2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2, ".
					" SalesJV.SalesJV_Date As OrderSalesDate, SalesJV.journal_Type As JournalType, '$DirSchema' As DirSchema ".
					" From $DirSchema.SalesJV As SalesJV ".
					//" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on SalesJV.SalesJV_Reference = Acclink.Link_Ref ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on SalesJV.SalesJV_Id = Acclink.Link_ID ".
					" Inner Join $DirSchema.Ledger As Ledger on SalesJV.Client_Code = Ledger.ledger_Number ";
					
			if ($projectexist >	0 && $FI_RepRestrictProject == 1)
				$QuerySI = $QuerySI.$QueryRestrictPrj." on SalesJV.project_code like concat(QP.project_code,'%') ";
											 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
				$QuerySI = $QuerySI.$QueryRestrictCst." on SalesJV.Costcenter_Code like concat(QC.costcent_code,'%') ";
		
			$QuerySI = $QuerySI.
					" Where Date_format(SalesJV.SalesJV_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(SalesJV.SalesJV_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(SalesJV.SalesJV_Date,'%Y-%m-%d'))  ".
					" And Date_format(SalesJV.SalesJV_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(SalesJV.SalesJV_Date,'%Y-%m-%d')) and ifNull('".$toate."',date_format(SalesJV.SalesJV_Date,'%Y-%m-%d'))  ".
					" And SalesJV.Client_Code between ifNull(".$fromledger.",SalesJV.Client_Code) and ifNull(". $toledger.",SalesJV.Client_Code) ".
					" And SalesJV.journal_Type = 'JS' ".
					" And IfNull(SalesJV.SalesJv_OldData,0) = 0 ".
					" And Acclink.Link_Type = 'JS' ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					" Group By SalesJV.SalesJV_Id  ".
					" Having Round(ifNull(SalesRemBase1,0),2) > 0 ".
					" Union ".
					" Select SalesJV.SalesJV_Id As InvoiceId, SalesJV.Client_Code As ClientCode, ledger.Ledger_name As ClientName, date_format(SalesJV.SalesJV_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(SalesJV.JournalDt_ValueDate,'%d/%m/%Y') As SalesValueDate, SalesJV.SalesJV_Reference As SalesRefer, ".
					" (ifNull(SalesJV.SalesJV_TotalBase1,0) - ifNull(SalesJV.SalesJV_DiscountAmount1,0) + ifNull(SalesJV.SalesJV_VatBase1,0)) As SalesTotalBase1, ".
					" (ifNull(SalesJV.SalesJV_TotalBase2,0) - ifNull(SalesJV.SalesJV_DiscountAmount2,0) + ifNull(SalesJV.SalesJV_VatBase2,0)) As SalesTotalBase2, ".
					" (ifNull(SalesJV.SalesJV_TotalBase1,0) - ifNull(SalesJV.SalesJV_DiscountAmount1,0) + ifNull(SalesJV.SalesJV_VatBase1,0)) As SalesRemBase1, ".
					" (ifNull(SalesJV.SalesJV_TotalBase2,0) - ifNull(SalesJV.SalesJV_DiscountAmount2,0) + ifNull(SalesJV.SalesJV_VatBase2,0)) As SalesRemBase2, ".
					" SalesJV.SalesJV_Date As OrderSalesDate, SalesJV.journal_Type As JournalType, '$DirSchema' As DirSchema ".
					" From $DirSchema.SalesJV As SalesJV ".
					" Inner Join $DirSchema.Ledger As Ledger on SalesJV.Client_Code = Ledger.ledger_Number ";
					
			if ($projectexist >	0 && $FI_RepRestrictProject == 1)
				$QuerySI = $QuerySI.$QueryRestrictPrj." on SalesJV.project_code like concat(QP.project_code,'%') ";
											 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
				$QuerySI = $QuerySI.$QueryRestrictCst." on SalesJV.Costcenter_Code like concat(QC.costcent_code,'%') ";
		
			$QuerySI = $QuerySI.
					" Where Date_format(SalesJV.SalesJV_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(SalesJV.SalesJV_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(SalesJV.SalesJV_Date,'%Y-%m-%d'))  ".
					" And SalesJV.Client_Code between ifNull(".$fromledger.",SalesJV.Client_Code) and ifNull(". $toledger.",SalesJV.Client_Code) ".
					" And SalesJV.journal_Type = 'JS' ".
					" And IfNull(SalesJV.SalesJv_OldData,0) = 0 ".
					" And SalesJV.SalesJV_Id Not In ( Select ifNull(Link_ID,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                          		  Where Acclink.Link_Type = 'JS'  ".
					" 								  And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					" 								  And upper(Acclink.CompanyName) = upper('".$DirCompany."') ) ";

	            
		if ($RowsDirCount > 1 && $j < $RowsDirCount)	
            $QuerySI = $QuerySI." Union ";	
			
	}					
}

$QuerySI = $QuerySI.
			" ) QDirDetail ".
			" Where ifNull(SalesTotalBase1,0) > 0 ".
			" Order by ClientCode, OrderSalesDate Asc, SalesRefer Asc  ";
			
//echo $QuerySI;
//exit;				

$j = 0;				
$k = 0;
$QueryDB = '';
$QueryDB =  " Select InvoiceId, ClientCode, ClientName, SalesDate, SalesValueDate, SalesRefer, ".
			" SalesTotalBase1, SalesTotalBase2, SalesRemBase1, SalesRemBase2, OrderSalesDate, JournalType, DirSchema ".
			" From ".
			" (  ";
				
// Reading Data For Many Years Or Different Directories					 
while($RowsDir=mysql_fetch_row($ResultDir5)){

    $j = $j + 1;    
	//if ($RowsDirCount > 1)
	   $DirSchema   = $RowsDir[0];
	   $DirFromDate = $RowsDir[1];
	   $DirToDate   = $RowsDir[2];
	   $DirCompany  = $RowsDir[3];
	   $DirYear	    = $RowsDir[4];
	   
	//else
       //$DirSchema = '';	
    
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
		$k = $k + 1; 
			
		$QueryDB = $QueryDB.
					" Select JournalDt.JournalDt_Id As InvoiceId, JournalDt.Ledger_number As ClientCode, ledger.Ledger_name As ClientName, date_format(Journal.Journal_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Journal.Journal_refgovernment As SalesRefer, ".
					" ifNull(Journaldt_amount1,0) As SalesTotalBase1, ifNull(Journaldt_amount2,0) As SalesTotalBase2, ".
					" (ifNull(Journaldt_amount1,0) - Sum(ifNull(AccLink.Sale_ReturnAmntbase1,0) + ifNull(AccLink.Sale_PaidAmntBase1,0))) As SalesRemBase1, ".
					" (ifNull(Journaldt_amount2,0) - Sum(ifNull(AccLink.Sale_ReturnAmntbase2,0) + ifNull(AccLink.Sale_PaidAmntBase2,0))) As SalesRemBase2, ".
					" Journal.Journal_Date As OrderSalesDate, Journal.Journal_Type As JournalType, '$DirSchema' As DirSchema ".
					" From $DirSchema.JournalDt As JournalDt ".
					" Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Acclink.Link_ID = JournalDt.JournalDt_Id And Acclink.Link_Type = Journal.Journal_Type ".
					" Inner Join $DirSchema.Ledger As Ledger on JournalDt.ledger_Number = Ledger.ledger_Number ".
					" Where JournalDt.Ledger_number between ifNull(".$fromledger.",JournalDt.Ledger_number) and ifNull(". $toledger.",JournalDt.Ledger_number) ".
					" And Date_format(Journal.Journal_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Journal.Journal_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Journal.Journal_Date,'%Y-%m-%d'))  ".
					" And Date_format(Journal.Journal_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Journal.Journal_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Journal.Journal_Date,'%Y-%m-%d'))  ".
					" And JournalDt.Journaldt_dbcd = 'D' ".
					" And Journal.Journal_Type Not In ('CV','SI','SR') ".
					" And IfNull(JournalDt.JournalDt_OldData,0) = 0 ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.DirYear) = upper('".$DirYear."') ";
					
		if ($RowsDirCount > 1 && $k != 1)	
			$QueryDB = $QueryDB." And Journal.Journal_Type <> 'OP' ";			
						
		$QueryDB = $QueryDB.
					" Group By JournalDt.JournalDt_Id  ".
					" Having Round(ifNull(SalesRemBase1,0),2) > 0 ".
					" Union ".
					" Select JournalDt.JournalDt_Id As InvoiceId, JournalDt.Ledger_number As ClientCode, ledger.Ledger_name As ClientName, date_format(Journal.Journal_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Journal.Journal_refgovernment As SalesRefer, ".
					" ifNull(Journaldt_amount1,0) As SalesTotalBase1, ifNull(Journaldt_amount2,0) As SalesTotalBase2, ".
					" ifNull(Journaldt_amount1,0) As SalesRemBase1, ifNull(Journaldt_amount2,0) As SalesRemBase2, ".
					" Journal.Journal_Date As OrderSalesDate, Journal.Journal_Type As JournalType, '$DirSchema' As DirSchema ".
					" From $DirSchema.JournalDt As JournalDt ".
					" Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ".
					" Inner Join $DirSchema.Ledger As Ledger on JournalDt.ledger_Number = Ledger.ledger_Number ".
					" Where JournalDt.Ledger_number between ifNull(".$fromledger.",JournalDt.Ledger_number) and ifNull(". $toledger.",JournalDt.Ledger_number) ".
					" And Date_format(Journal.Journal_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Journal.Journal_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Journal.Journal_Date,'%Y-%m-%d'))  ".
					" And Date_format(Journal.Journal_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Journal.Journal_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Journal.Journal_Date,'%Y-%m-%d'))  ".
					" And JournalDt.Journaldt_dbcd = 'D' ".
					" And Journal.Journal_Type Not In ('CV','SI','SR') ".
					" And IfNull(JournalDt.JournalDt_OldData,0) = 0 ".
					" And JournalDt.JournalDt_Id Not In (Select ifNull(Acclink.Link_ID,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                          		 	 Where Acclink.Link_Type Not In ('SI','SR','JS') ".
					" 									 And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" 									 And upper(Acclink.CompanyName) = upper('".$DirCompany."')) ";
					
		if ($RowsDirCount > 1 && $k != 1)	
			$QueryDB = $QueryDB." And Journal.Journal_Type <> 'OP' ";
					
		if ($RowsDirCount > 1 && $j < $RowsDirCount)	
            $QueryDB = $QueryDB." Union ";	
			
	}					
}

$QueryDB = $QueryDB.
			" ) QDirDetail ".
			" Order by ClientCode, OrderSalesDate Asc, SalesRefer Asc  ";
			
//echo $QueryDB;
//exit;		 

$j = 0;				
$k = 0;
$QuerySR = '';
$QuerySR =  " Select InvoiceId, ClientCode, ClientName, SalesDate, SalesValueDate, SalesRefer, ".
			" SalesTotalBase1, SalesTotalBase2, SalesRemBase1, SalesRemBase2, OrderSalesDate, DirSchema ".
			" From ".
			" (  ";
				
// Reading Data For Many Years Or Different Directories					 
while($RowsDir=mysql_fetch_row($ResultDir1)){

    $j = $j + 1;    
	//if ($RowsDirCount > 1)
	   $DirSchema   = $RowsDir[0];
	   $DirFromDate = $RowsDir[1];
	   $DirToDate   = $RowsDir[2];
	   $DirCompany  = $RowsDir[3];
	   $DirYear	    = $RowsDir[4];
	   
	//else
       //$DirSchema = '';	
    
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
		$k = $k + 1; 
				
		if($Module_Delivery == 0 ) {
			$QuerySR = $QuerySR.
					" Select Deliveries.Delivery_Id As InvoiceId, Deliveries.Client_Code As ClientCode, ledger.Ledger_name As ClientName, date_format(Deliveries.Delivery_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(Deliveries.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Deliveries.Delivery_Reference As SalesRefer, ".
					" (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As SalesTotalBase1, ".
					" (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As SalesTotalBase2, ".
					" ((ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) - Sum(ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
					" ((ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) - Sum(ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2, ".
					" Deliveries.Delivery_Date As OrderSalesDate, '$DirSchema' As DirSchema ".
					" From $DirSchema.Deliveries As Deliveries ".
					//" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Deliveries.Delivery_Reference = Acclink.Return_Ref ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Deliveries.Delivery_Id = Acclink.Return_ID ".
					" Inner Join $DirSchema.Ledger As Ledger on Deliveries.Client_Code = Ledger.ledger_Number ";
					
			if ($projectexist >	0 && $FI_RepRestrictProject == 1)
				$QuerySR = $QuerySR.$QueryRestrictPrj." on Deliveries.project_code like concat(QP.project_code,'%') ";
											 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
				$QuerySR = $QuerySR.$QueryRestrictCst." on Deliveries.costcent_code like concat(QC.costcent_code,'%') ";
		
			$QuerySR = $QuerySR.
					" Where Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ".
					" And Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ".
					" And Deliveries.Client_Code between ifNull(".$fromledger.",Deliveries.Client_Code) and ifNull(". $toledger.",Deliveries.Client_Code) ".
					" And Deliveries.journal_Type = 'DR' ".
					" And IfNull(Deliveries.Delivery_OldData,0) = 0 ".
					" And Acclink.Return_Type In ('DR','SR') ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" Group By Deliveries.Delivery_Id  ".
					" Having Round(ifNull(SalesRemBase1,0),2) > 0 ".
					" Union ".
					" Select Deliveries.Delivery_Id As InvoiceId, Deliveries.Client_Code As ClientCode, ledger.Ledger_name As ClientName, date_format(Deliveries.Delivery_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(Deliveries.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Deliveries.Delivery_Reference As SalesRefer, ".
					" (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As SalesTotalBase1, ".
					" (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As SalesTotalBase2, ".
					" (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As SalesRemBase1, ".
					" (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As SalesRemBase2, ".
					" Deliveries.Delivery_Date As OrderSalesDate, '$DirSchema' As DirSchema ".
					" From $DirSchema.Deliveries As Deliveries ".
					" Inner Join $DirSchema.Ledger As Ledger on Deliveries.Client_Code = Ledger.ledger_Number ";
					
			if ($projectexist >	0 && $FI_RepRestrictProject == 1)
				$QuerySR = $QuerySR.$QueryRestrictPrj." on Deliveries.project_code like concat(QP.project_code,'%') ";
											 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
				$QuerySR = $QuerySR.$QueryRestrictCst." on Deliveries.costcent_code like concat(QC.costcent_code,'%') ";
		
			$QuerySR = $QuerySR.
					" Where Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ".
					" And Date_format(Deliveries.Delivery_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Deliveries.Delivery_Date,'%Y-%m-%d'))  ".
					" And Deliveries.Client_Code between ifNull(".$fromledger.",Deliveries.Client_Code) and ifNull(". $toledger.",Deliveries.Client_Code) ".
					" And Deliveries.journal_Type = 'DR' ".
					" And IfNull(Deliveries.Delivery_OldData,0) = 0 ".
					" And Deliveries.Delivery_Id Not In (Select ifNull(Return_ID,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                          		 	 Where Acclink.Return_Type In ('DR','SR') ".
					" 								 	 And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" 								 	 And upper(Acclink.CompanyName) = upper('".$DirCompany."')) ";
					
		} else {
						
			$QuerySR = $QuerySR.
					" Select Sales.Sale_Id As InvoiceId, Sales.Client_Code As ClientCode, ledger.Ledger_name As ClientName, date_format(Sales.Sale_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(Sales.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Sales.Sale_Reference As SalesRefer, ".
					" (ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) As SalesTotalBase1, ".
					" (ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) As SalesTotalBase2, ".
					" ((ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
					" ((ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2, ".
					" Sales.Sale_Date As OrderSalesDate, '$DirSchema' As DirSchema ".
					" From $DirSchema.Sales As Sales ".
					//" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Sales.Sale_Reference = Acclink.Return_Ref ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Sales.Sale_Id = Acclink.Return_ID ".
					" Inner Join $DirSchema.Ledger As Ledger on Sales.Client_Code = Ledger.ledger_Number ";
					
			if ($projectexist >	0 && $FI_RepRestrictProject == 1)
				$QuerySR = $QuerySR.$QueryRestrictPrj." on Sales.project_code like concat(QP.project_code,'%') ";
											 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
				$QuerySR = $QuerySR.$QueryRestrictCst." on Sales.Costcenter_code like concat(QC.costcent_code,'%') ";	
		
			$QuerySR = $QuerySR.
					" Where Date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Sales.Sale_Date,'%Y-%m-%d'))  ".
					" And Date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Sales.Sale_Date,'%Y-%m-%d'))  ".
					" And Sales.Client_Code between ifNull(".$fromledger.",Sales.Client_Code) and ifNull(". $toledger.",Sales.Client_Code) ".
					" And Sales.Journal_Type = 'SR' ".
					" And IfNull(Sales.Sale_OldData,0) = 0 ".
					" And Acclink.Return_Type In ('DR','SR') ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" Group By Sales.Sale_Id  ".
					" Having Round(ifNull(SalesRemBase1,0),2) > 0 ".
					" Union ".
					" Select Sales.Sale_Id As InvoiceId, Sales.Client_Code As ClientCode, ledger.Ledger_name As ClientName, date_format(Sales.Sale_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(Sales.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Sales.Sale_Reference As SalesRefer, ".
					" (ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) As SalesTotalBase1, ".
					" (ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) As SalesTotalBase2, ".
					" (ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) As TransRemBase1, ".
					" (ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) As TransRemBase2, ".
					" Sales.Sale_Date As OrderSalesDate, '$DirSchema' As DirSchema ".
					" From $DirSchema.Sales As Sales ".
					" Inner Join $DirSchema.Ledger As Ledger on Sales.Client_Code = Ledger.ledger_Number ";
					
			if ($projectexist >	0 && $FI_RepRestrictProject == 1)
				$QuerySR = $QuerySR.$QueryRestrictPrj." on Sales.project_code like concat(QP.project_code,'%') ";
											 
			if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
				$QuerySR = $QuerySR.$QueryRestrictCst." on Sales.Costcenter_code like concat(QC.costcent_code,'%') ";	
		
			$QuerySR = $QuerySR.
					" Where Date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Sales.Sale_Date,'%Y-%m-%d'))  ".
					" And Date_format(Sales.Sale_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Sales.Sale_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Sales.Sale_Date,'%Y-%m-%d'))  ".
					" And Sales.Client_Code between ifNull(".$fromledger.",Sales.Client_Code) and ifNull(". $toledger.",Sales.Client_Code) ".
					" And Sales.Journal_Type = 'SR' ".
					" And IfNull(Sales.Sale_OldData,0) = 0 ".
					" And Sales.Sale_Id Not In ( Select ifNull(Return_ID,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                            Where Acclink.Return_Type In ('DR','SR') ".
					" 							 And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" 							 And upper(Acclink.CompanyName) = upper('".$DirCompany."')) ";
					
		}

	            
		if ($RowsDirCount > 1 && $j < $RowsDirCount)	
            $QuerySR = $QuerySR." Union ";	
			
	}					
}

$QuerySR = $QuerySR.
			" ) QDirDetail ".
			" Order by ClientCode, OrderSalesDate Asc, SalesRefer Asc  ";

//echo $QuerySR;
//exit;	

$j = 0;				
$k = 0;
$QueryRV = '';
$QueryRV =  " Select InvoiceId, ClientCode, ClientName, SalesDate, SalesValueDate, SalesRefer, ".
			" SalesTotalBase1, SalesTotalBase2, SalesRemBase1, SalesRemBase2, OrderSalesDate, DirSchema, InvoiceDtId ".
			" From ".
			" (  ";
				
// Reading Data For Many Years Or Different Directories					 
while($RowsDir=mysql_fetch_row($ResultDir2)){

    $j = $j + 1;    
	//if ($RowsDirCount > 1)
	   $DirSchema   = $RowsDir[0];
	   $DirFromDate = $RowsDir[1];
	   $DirToDate   = $RowsDir[2];
	   $DirCompany  = $RowsDir[3];
	   $DirYear	    = $RowsDir[4];
	   
	//else
       //$DirSchema = '';	
    
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
		$k = $k + 1; 
				
		$QueryRV = $QueryRV.
					" Select Trans.Trans_Id As InvoiceId, TransDt.TransDt_Id As InvoiceDtId, TransDt.Ledger_number As ClientCode, ledger.Ledger_name As ClientName, date_format(Trans.Trans_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(TransDt.TransDt_ValueDate,'%d/%m/%Y') As SalesValueDate, Trans.Trans_Reference As SalesRefer, ".
					" ifNull(TransDt.Transdt_Amount1,0) As SalesTotalBase1, ifNull(TransDt.Transdt_Amount2,0) As SalesTotalBase2, ".
					" (ifNull(TransDt.Transdt_Amount1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0))) As SalesRemBase1, ".
					" (ifNull(TransDt.Transdt_Amount2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0))) As SalesRemBase2, ".
					" Trans.Trans_Date As OrderSalesDate, '$DirSchema' As DirSchema ".
					" From $DirSchema.TransDt As TransDt ".
					" Inner Join $DirSchema.Trans As Trans on TransDt.Trans_Id = Trans.Trans_Id ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Acclink.Journal_Id = TransDt.TransDt_Id ".
					" Inner Join $DirSchema.Ledger As Ledger on TransDt.ledger_Number = Ledger.ledger_Number ";
					
		if ($projectexist >	0 && $FI_RepRestrictProject == 1)
			$QueryRV = $QueryRV.$QueryRestrictPrj." on Trans.project_code like concat(QP.project_code,'%') ";
											 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$QueryRV = $QueryRV.$QueryRestrictCst." on Trans.costcent_code like concat(QC.costcent_code,'%') ";
		
		$QueryRV = $QueryRV.
					" Where TransDt.Ledger_number between ifNull(".$fromledger.",TransDt.Ledger_number) and ifNull(". $toledger.",TransDt.Ledger_number) ".
					" And Date_format(Trans.Trans_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Trans.Trans_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Trans.Trans_Date,'%Y-%m-%d'))  ".
					" And Date_format(Trans.Trans_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Trans.Trans_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Trans.Trans_Date,'%Y-%m-%d'))  ".
					" And Trans.Trans_Type = 'RV' ".
					" And IfNull(TransDt.TransDt_OldData,0) = 0 ".
					" And TransDt.TransDt_dbcd = 'C' ".
					" And Acclink.Journal_Type = 'RV' ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" Group By Trans.Trans_Id, TransDt.TransDt_Id  ".
					" Having Round(ifNull(SalesRemBase1,0),2) > 0 ".
					" Union ".
					" Select Trans.Trans_Id As InvoiceId, TransDt.TransDt_Id As InvoiceDtId, TransDt.Ledger_number As ClientCode, ledger.Ledger_name As ClientName, date_format(Trans.Trans_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(TransDt.TransDt_ValueDate,'%d/%m/%Y') As SalesValueDate, Trans.Trans_Reference As SalesRefer, ".
					" ifNull(TransDt.Transdt_Amount1,0) As SalesTotalBase1, ifNull(TransDt.Transdt_Amount2,0) As SalesTotalBase2, ".
					" ifNull(TransDt.Transdt_Amount1,0) As SalesRemBase1, ifNull(TransDt.Transdt_Amount2,0) As SalesRemBase2, ".
					" Trans.Trans_Date As OrderSalesDate, '$DirSchema' As DirSchema ".
					" From $DirSchema.TransDt As TransDt ".
					" Inner Join $DirSchema.Trans As Trans on TransDt.Trans_Id = Trans.Trans_Id ".
					" Inner Join $DirSchema.Ledger As Ledger on TransDt.ledger_Number = Ledger.ledger_Number ";
					
		if ($projectexist >	0 && $FI_RepRestrictProject == 1)
			$QueryRV = $QueryRV.$QueryRestrictPrj." on Trans.project_code like concat(QP.project_code,'%') ";
											 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$QueryRV = $QueryRV.$QueryRestrictCst." on Trans.costcent_code like concat(QC.costcent_code,'%') ";
		
		$QueryRV = $QueryRV.
					" Where TransDt.Ledger_number between ifNull(".$fromledger.",TransDt.Ledger_number) and ifNull(". $toledger.",TransDt.Ledger_number) ".
					" And Date_format(Trans.Trans_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Trans.Trans_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Trans.Trans_Date,'%Y-%m-%d'))  ".
					" And Date_format(Trans.Trans_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Trans.Trans_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Trans.Trans_Date,'%Y-%m-%d'))  ".
					" And Trans.Trans_Type = 'RV' ".
					" And TransDt.TransDt_dbcd = 'C' ".
					" And IfNull(TransDt.TransDt_OldData,0) = 0 ".
					" And TransDt.Transdt_Id Not In (Select ifNull(Acclink.Journal_Id,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                          		 Where Acclink.Journal_Type = 'RV' ".
					" 								 And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" 								 And upper(Acclink.CompanyName) = upper('".$DirCompany."')) ";
	            
		if ($RowsDirCount > 1 && $j < $RowsDirCount)	
            $QueryRV = $QueryRV." Union ";	
			
	}					
}

$QueryRV = $QueryRV.
			" ) QDirDetail ".
			" Order by ClientCode, OrderSalesDate Asc, SalesRefer Asc  ";
			
//echo $QueryRV;
//exit;	


$j = 0;				
$k = 0;
$QueryCV = '';
$QueryCV =  " Select InvoiceId, ClientCode, ClientName, SalesDate, SalesValueDate, SalesRefer, ".
			" SalesTotalBase1, SalesTotalBase2, SalesRemBase1, SalesRemBase2, OrderSalesDate, DirSchema, InvoiceDtId ".
			" From ".
			" (  ";
				
// Reading Data For Many Years Or Different Directories					 
while($RowsDir=mysql_fetch_row($ResultDir3)){

    $j = $j + 1;    
	//if ($RowsDirCount > 1)
	   $DirSchema   = $RowsDir[0];
	   $DirFromDate = $RowsDir[1];
	   $DirToDate   = $RowsDir[2];
	   $DirCompany  = $RowsDir[3];
	   $DirYear	    = $RowsDir[4];
	   
	//else
       //$DirSchema = '';	
    
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
		$k = $k + 1; 
				
		$QueryCV = $QueryCV.
					" Select Trans.Trans_Id As InvoiceId, TransDt.TransDt_Id As InvoiceDtId, TransDt.Ledger_number As ClientCode, ledger.Ledger_name As ClientName, date_format(Trans.Trans_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(TransDt.TransDt_ValueDate,'%d/%m/%Y') As SalesValueDate, Trans.Trans_Reference As SalesRefer, ".
					" ifNull(TransDt.Transdt_Amount1,0) As SalesTotalBase1, ifNull(TransDt.Transdt_Amount2,0) As SalesTotalBase2, ".
					" (ifNull(TransDt.Transdt_Amount1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0))) As SalesRemBase1, ".
					" (ifNull(TransDt.Transdt_Amount2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0))) As SalesRemBase2, ".
					" Trans.Trans_Date As OrderSalesDate, '$DirSchema' As DirSchema ".
					" From $DirSchema.TransDt As TransDt ".
					" Inner Join $DirSchema.Trans As Trans on TransDt.Trans_Id = Trans.Trans_Id ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Acclink.Journal_Id = TransDt.TransDt_Id ".
					" Inner Join $DirSchema.Ledger As Ledger on TransDt.ledger_Number = Ledger.ledger_Number ";
					
		if ($projectexist >	0 && $FI_RepRestrictProject == 1)
			$QueryCV = $QueryCV.$QueryRestrictPrj." on Trans.project_code like concat(QP.project_code,'%') ";
											 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$QueryCV = $QueryCV.$QueryRestrictCst." on Trans.costcent_code like concat(QC.costcent_code,'%') ";
		
		$QueryCV = $QueryCV.
					" Where TransDt.Ledger_number between ifNull(".$fromledger.",TransDt.Ledger_number) and ifNull(". $toledger.",TransDt.Ledger_number) ".
					" And Date_format(Trans.Trans_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Trans.Trans_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Trans.Trans_Date,'%Y-%m-%d'))  ".
					" And Date_format(Trans.Trans_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Trans.Trans_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Trans.Trans_Date,'%Y-%m-%d'))  ".
					" And Trans.Trans_Type = 'CV' ".
					" And IfNull(TransDt.TransDt_OldData,0) = 0 ".
					" And Acclink.Journal_Type = 'CV' ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" Group By Trans.Trans_Id, TransDt.TransDt_Id  ".
					" Having Round(ifNull(SalesRemBase1,0),2) > 0 ".
					" Union ".
					" Select Trans.Trans_Id As InvoiceId, TransDt.TransDt_Id As InvoiceDtId, TransDt.Ledger_number As ClientCode, ledger.Ledger_name As ClientName, date_format(Trans.Trans_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(TransDt.TransDt_ValueDate,'%d/%m/%Y') As SalesValueDate, Trans.Trans_Reference As SalesRefer, ".
					" ifNull(TransDt.Transdt_Amount1,0) As SalesTotalBase1, ifNull(TransDt.Transdt_Amount2,0) As SalesTotalBase2, ".
					" ifNull(TransDt.Transdt_Amount1,0) As SalesRemBase1, ifNull(TransDt.Transdt_Amount2,0) As SalesRemBase2, ".
					" Trans.Trans_Date As OrderSalesDate, '$DirSchema' As DirSchema ".
					" From $DirSchema.TransDt As TransDt ".
					" Inner Join $DirSchema.Trans As Trans on TransDt.Trans_Id = Trans.Trans_Id ".
					" Inner Join $DirSchema.Ledger As Ledger on TransDt.ledger_Number = Ledger.ledger_Number ";
					
		if ($projectexist >	0 && $FI_RepRestrictProject == 1)
			$QueryCV = $QueryCV.$QueryRestrictPrj." on Trans.project_code like concat(QP.project_code,'%') ";
											 
		if ($costcentexist > 0 && $FI_RepRestrictCostcenter == 1)
			$QueryCV = $QueryCV.$QueryRestrictCst." on Trans.costcent_code like concat(QC.costcent_code,'%') ";
		
		$QueryCV = $QueryCV.
					" Where TransDt.Ledger_number between ifNull(".$fromledger.",TransDt.Ledger_number) and ifNull(". $toledger.",TransDt.Ledger_number) ".
					" And Date_format(Trans.Trans_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Trans.Trans_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Trans.Trans_Date,'%Y-%m-%d'))  ".
					" And Date_format(Trans.Trans_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Trans.Trans_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Trans.Trans_Date,'%Y-%m-%d'))  ".
					" And Trans.Trans_Type = 'CV' ".
					" And IfNull(TransDt.TransDt_OldData,0) = 0 ".
					" And TransDt.Transdt_Id Not In (Select ifNull(Acclink.Journal_Id,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                          		 Where Acclink.Journal_Type = 'CV' ".
					" 								 And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" 								 And upper(Acclink.CompanyName) = upper('".$DirCompany."')) ";
	            
		if ($RowsDirCount > 1 && $j < $RowsDirCount)	
            $QueryCV = $QueryCV." Union ";	
			
	}					
}

$QueryCV = $QueryCV.
			" ) QDirDetail ".
			" Order by ClientCode, OrderSalesDate Asc, SalesRefer Asc  ";
			
//echo $QueryCV;
//exit;	

$j = 0;				
$k = 0;
$QueryJV = '';
$QueryJV =  " Select InvoiceId, ClientCode, ClientName, SalesDate, SalesValueDate, SalesRefer, ".
			" SalesTotalBase1, SalesTotalBase2, SalesRemBase1, SalesRemBase2, OrderSalesDate, JournalType, DirSchema, InvoiceDtId ".
			" From ".
			" (  ";
				
// Reading Data For Many Years Or Different Directories					 
while($RowsDir=mysql_fetch_row($ResultDir4)){

    $j = $j + 1;    
	//if ($RowsDirCount > 1)
	   $DirSchema   = $RowsDir[0];
	   $DirFromDate = $RowsDir[1];
	   $DirToDate   = $RowsDir[2];
	   $DirCompany  = $RowsDir[3];
	   $DirYear	    = $RowsDir[4];
	   
	//else
       //$DirSchema = '';	
    
	if ($RowsDirCount > 1) {
		$QuerySchemaExists = "Show Schemas where `Database` = '".$DirSchema."'  ";   
		$ResultSchemaExists=mysql_query($QuerySchemaExists,$connection) or die(mysql_error());
		$SchemaExists = mysql_num_rows($ResultSchemaExists);
		
	}
	
	if (($RowsDirCount > 1 && $SchemaExists > 0) || ($RowsDirCount == 1) ) {
	
		$k = $k + 1; 
			
		$QueryJV = $QueryJV.
					" Select Journal.Journal_Id As InvoiceId, JournalDt.JournalDt_Id As InvoiceDtId, JournalDt.Ledger_number As ClientCode, ledger.Ledger_name As ClientName, date_format(Journal.Journal_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Journal.Journal_refgovernment As SalesRefer, ".
					" ifNull(Journaldt_amount1,0) As SalesTotalBase1, ifNull(Journaldt_amount2,0) As SalesTotalBase2, ".
					" (ifNull(Journaldt_amount1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0))) As SalesRemBase1, ".
					" (ifNull(Journaldt_amount2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0))) As SalesRemBase2, ".
					" Journal.Journal_Date As OrderSalesDate, Journal.Journal_Type As JournalType, '$DirSchema' As DirSchema ".
					" From $DirSchema.JournalDt As JournalDt ".
					" Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink As Acclink on Acclink.Journal_Id = JournalDt.JournalDt_Id And Acclink.Journal_Type = Journal.Journal_Type ".
					" Inner Join $DirSchema.Ledger As Ledger on JournalDt.ledger_Number = Ledger.ledger_Number ".
					" Where JournalDt.Ledger_number between ifNull(".$fromledger.",JournalDt.Ledger_number) and ifNull(". $toledger.",JournalDt.Ledger_number) ".
					" And Date_format(Journal.Journal_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Journal.Journal_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Journal.Journal_Date,'%Y-%m-%d'))  ".
					" And Date_format(Journal.Journal_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Journal.Journal_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Journal.Journal_Date,'%Y-%m-%d'))  ".
					" And JournalDt.Journaldt_dbcd = 'C' ".
					" And Journal.Journal_Type Not In ('RV','CV','SI','SR','OP') ".
					" And IfNull(JournalDt.JournalDt_OldData,0) = 0 ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" Group By Journal.Journal_Id, JournalDt.JournalDt_Id  ".
					" Having Round(ifNull(SalesRemBase1,0),2) > 0 ".
					" Union ".
					" Select Journal.Journal_Id As InvoiceId, JournalDt.JournalDt_Id As InvoiceDtId, JournalDt.Ledger_number As ClientCode, ledger.Ledger_name As ClientName, date_format(Journal.Journal_Date,'%d/%m/%Y') As SalesDate, ".
					" date_format(JournalDt.Journaldt_ValueDate,'%d/%m/%Y') As SalesValueDate, Journal.Journal_refgovernment As SalesRefer, ".
					" ifNull(Journaldt_amount1,0) As SalesTotalBase1, ifNull(Journaldt_amount2,0) As SalesTotalBase2, ".
					" ifNull(Journaldt_amount1,0) As SalesRemBase1, ifNull(Journaldt_amount2,0) As SalesRemBase2, ".
					" Journal.Journal_Date As OrderSalesDate, Journal.Journal_Type As JournalType, '$DirSchema' As DirSchema ".
					" From $DirSchema.JournalDt As JournalDt ".
					" Inner join $DirSchema.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ".
					" Inner Join $DirSchema.Ledger As Ledger on JournalDt.ledger_Number = Ledger.ledger_Number ".
					" Where JournalDt.Ledger_number between ifNull(".$fromledger.",JournalDt.Ledger_number) and ifNull(". $toledger.",JournalDt.Ledger_number) ".
					" And Date_format(Journal.Journal_Date,'%Y-%m-%d') between ifNull('". $DirFromDate."',date_format(Journal.Journal_Date,'%Y-%m-%d')) and ifNull('". $DirToDate."',date_format(Journal.Journal_Date,'%Y-%m-%d'))  ".
					" And Date_format(Journal.Journal_Date,'%Y-%m-%d') between ifNull('".$fromdate."',date_format(Journal.Journal_Date,'%Y-%m-%d')) and ifNull('".$todate."',date_format(Journal.Journal_Date,'%Y-%m-%d'))  ".
					" And JournalDt.Journaldt_dbcd = 'C' ".
					" And Journal.Journal_Type Not In ('RV','CV','SI','SR','OP') ".
					" And IfNull(JournalDt.JournalDt_OldData,0) = 0 ".
					" And JournalDt.JournalDt_Id Not In (Select ifNull(Acclink.Journal_Id,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                          		 	 Where Acclink.Journal_Type Not In ('RV','CV','PV','DV') ".
					" 									 And upper(Acclink.DirYear) = upper('".$DirYear."') ".
					" 									 And upper(Acclink.CompanyName) = upper('".$DirCompany."')) ";
					
		if ($RowsDirCount > 1 && $j < $RowsDirCount)	
            $QueryJV = $QueryJV." Union ";	
			
	}					
}

$QueryJV = $QueryJV.
			" ) QDirDetail ".
			" Order by ClientCode, OrderSalesDate Asc, SalesRefer Asc  ";
			
//echo $QueryJV;
//exit;	

echo"<table cellpadding='0' cellspacing='0' border='0'  align='center' class='layout-width'>";
include_once("header.php");
echo" <tr><td  valign='top'>";

include_once("sidemenu.php");
echo"  </td></tr>";


echo" <tr style='height:26px;'>
		<td  valign='top' id='content-top'>
			<table border='0' cellpadding='0' cellspacing='0' style='table-layout:fixed; height:26px;' class='layout-width'>
			<tr style='height:26px;'>
				<td style='width:38px; height:26px;'>&nbsp;</td>
				<td valign='middle' style='width:300px; height:26px;'><span class='title'>INVOICES ALLOCATION</span></td>
				<td class='message' valign='middle' style='height:26px;'>".htmlspecialchars($message, ENT_QUOTES)."</td>
			</tr></table>
		</td>
	  </tr>";

echo"<tr>
		<td  height='34'  valign='top' id='content-top2'>
			<table border='0' cellpadding='0' cellspacing='0' class='layout-width'>
			<tr>
				<td width='30'  height='34'>&nbsp;</td>
				<td valign='middle' height='34' width='720px' align='left'>";
	
	echo"<button type='button' id='btnSearch' name='btnSearch' onclick='SearchForm(); return false;' title='Search'><span><span>Search</span></span></button>";
	echo"<button type='button' id='btnSubmit' name='btnSubmit' onclick='SubmitForm(); return false;' title='Allocate Invoice'><span><span>Allocate Invoice</span></span></button>";
	
	
echo"	</td></tr></table>";
echo"</td></tr>";
				
echo"<tr><td id='content-body'>
<table border='0'  align='center' valign='top' width=100% class='tablecontent'>
   <tr bgcolor='#F7F7F7'><td valign='top' align='left'>";	 

print <<<HERE
		
		
		<table border="0" style='table-layout:fixed'>
		  <col width=70>
		  <col width=200>
		  <col width=70>
		  <col width=655>

HERE;



echo" <tr>";	  
echo"   <td height='19' colspan='2' align='left' bgcolor='#F5F5F5'><span class='style1'>Date</span></td>";
echo"   <td height='19' colspan='2' align='left' bgcolor='#F5F5F5'><span class='style1'>Ledger No. / Name</span></td>";
echo" </tr>";

echo" <tr height='25'>";	  
echo"   <td valign='middle' bgcolor='#F5F5F5' ><span class='style1'>From</span></td>";
echo"   <td valign='middle' bgcolor='#F5F5F5' ><span class='style1'>";
echo"      <input type='text' name='fromdate' value='$dispfromdate'  onBlur='checkDateFormat(this)'  maxlength='10' size='10'>";
echo"      <A HREF=\"#\" onClick=\"displayCalendar(document.invoices.fromdate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><image src='./img/cal.gif' border=0 align=center></image></A></span></td>";
echo"   <td align='left' bgcolor='#F5F5F5' ><span class='style1'>From</span></td>";
echo"   <td valign='middle' bgcolor='#F5F5F5' ><span class='style1'>";
echo"   <input name='fromledger' type='text' id='fromledger' size='10' value='".$dispfromledger."' readonly />
        <input name='fromledgername' type='text' id='fromledgername' size='35' value='".$dispfromledgername."' readonly />
		</span>
		<label><span class='style1'><a href='javascript:void(0);' NAME='My Window Name' title=' Select Ledger From ' 
             onClick='showlistledger(3); '><img src='img/btnopen.jpg' width='15' height='20' border='0' /></a> </span></label>";
echo"	</td>";
				
echo" </tr>";

echo" <tr height='25'>";
echo"   <td valign='top' bgcolor='#F5F5F5'><span class='style1'>To</span></td>";
echo"   <td valign='top' bgcolor='#F5F5F5'><span class='style1'>";
echo"      <input type='text' name='todate' value='$disptodate'  onBlur='checkDateFormat(this)'   maxlength='10' size='10'>";
echo"      <A HREF=\"#\" onClick=\"displayCalendar(document.invoices.todate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><image src='./img/cal.gif' border=0 align=center></image></A></span></td>";
echo"   <td align='left' bgcolor='#F5F5F5' ><span class='style1'>To</span></td>";
echo"   <td valign='middle' bgcolor='#F5F5F5' ><span class='style1'>";
echo" 	 	<input name='toledger' type='text' id='toledger' size='10' value='".$disptoledger."' readonly />
			<input name='toledgername' type='text' id='toledgername' size='35' value='".$disptoledgername."' readonly />
		</span>";
//echo"	<label><span class='style1'><a href='javascript:void(0);' NAME='My Window Name' title=' Select Ledger To ' 
//             onClick='showlistledger(4); '><img src='img/btnopen.jpg' width='15' height='20' border='0' /></a> </span></label>";
echo"	</td>";
echo" </tr>";




//Display Invoices
echo" <tr>";
echo"   <td colspan='4' valign='top' bgcolor='#F5F5F5'>";

echo"   <div style='position:relative; float:left; overflow:none; border:1px solid #B5B5B5;' >
		<div style='overflow:none; height:20px; width:490px; margin-top:5px; text-align:center; font-weight:bold;' >INVOICES</div>
		<div style='overflow:auto; height:120px; width:490px;border:0px solid #000000;' ><table border='0' style='table-layout:fixed; width:630px;' id='grid_datatable' class='grid_data'>
		  <col width=20>
		  <col width=80>
		  <col width=40>
		  <col width=80>
		  <col width=100>
		  <col width=100>
		  <col width=100>
		  <col width=100>";
		  
echo"	<tr height='25'>";
echo"		<th align='center'>&nbsp;</th>";
echo"		<th align='center'><span class='style1'>Reference</span></th>";
echo"		<th align='center'><span class='style1'>Type</span></th>";
echo"		<th align='center'><span class='style1'>Date</span></th>";
//echo"		<th align='center'><span class='style1'>Client</span></th>";
//echo"		<th align='center'>&nbsp;</th>";
echo"		<th align='center'><span class='style1'>Amount $base1</span></th>";
echo"		<th align='center'><span class='style1'>Remain $base1</span></th>";
echo"		<th align='center'><span class='style1'>Amount $base2</span></th>";
echo"		<th align='center'><span class='style1'>Remain $base2</span></th>";
echo"	</tr>";		

if ($actionmode == 'Search') {

	$ct = 1;
	$resultSI=mysql_query($QuerySI,$connection) or die(mysql_error());
	while($rowsSI=mysql_fetch_row($resultSI)){
		$ct+=1;

		if($ct%2==0)
			$Color="style='background-color:".$grid_color1."'";
		else			
			$Color="style='background-color:".$grid_color2."'";	
									
		echo "<tr ".$Color." >";
		echo "	<td align='left'><span class='style15'><label>
					<input type='hidden' name='RemainAmountSI[]' id='RemainAmountSI[]' value='".$rowsSI[8]."' />
					<input type='hidden' name='JourTypeSI[]' id='JourTypeSI[]' value='".$rowsSI[11]."' />
					<input type='hidden' name='DirSchemaSI[]' id='DirSchemaSI[]' value='".$rowsSI[12]."' />
					<label><input type='checkbox' name='ChkSI[]' id='ChkSI[]' value='".$rowsSI[0]."' onclick=\"SelectInvoice(this.value,'SI');\"; /></label></span>
				</td>";
		echo "	<td align='left'><span class='style15'>".$rowsSI[5]."</span></td>";
		echo "	<td align='center'><span class='style15'>".$rowsSI[11]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$rowsSI[3]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsSI[1]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsSI[2]."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsSI[6],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsSI[8],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsSI[7],$DecimalBase2)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsSI[9],$DecimalBase2)."</span></td>";
		echo "</tr>";	
		
	}
	
}		
		
echo "	</table></div></div>"; 


echo"   <div style='position:relative; float:right; overflow:none; border:1px solid #B5B5B5;' >
		<div style='overflow:none; height:20px; width:490px; margin-top:5px; text-align:center; font-weight:bold;' >OTHER DEBITS</div>
		<div style='overflow:auto; height:120px; width:490px;border:0px solid #000000;' ><table border='0' style='table-layout:fixed; width:630px;' id='grid_datatable' class='grid_data'>
		  <col width=20>
		  <col width=80>
		  <col width=40>
		  <col width=80>
		  <col width=100>
		  <col width=100>
		  <col width=100>
		  <col width=100>";
		  
echo"	<tr height='25'>";
echo"		<th align='center'>&nbsp;</th>";
echo"		<th align='center'><span class='style1'>Reference</span></th>";
echo"		<th align='center'><span class='style1'>Type</span></th>";
echo"		<th align='center'><span class='style1'>Date</span></th>";
//echo"		<th align='center'><span class='style1'>Client</span></th>";
//echo"		<th align='center'>&nbsp;</th>";
echo"		<th align='center'><span class='style1'>Amount $base1</span></th>";
echo"		<th align='center'><span class='style1'>Remain $base1</span></th>";
echo"		<th align='center'><span class='style1'>Amount $base2</span></th>";
echo"		<th align='center'><span class='style1'>Remain $base2</span></th>";
echo"	</tr>";		

if ($actionmode == 'Search') {

	$ct = 1;
	$resultDB=mysql_query($QueryDB,$connection) or die(mysql_error());
	while($rowsDB=mysql_fetch_row($resultDB)){
		$ct+=1;

		if($ct%2==0)
			$Color="style='background-color:".$grid_color1."'";
		else			
			$Color="style='background-color:".$grid_color2."'";	
									
		echo "<tr ".$Color." >";
		echo "	<td align='left'><span class='style15'><label>
					<input type='hidden' name='RemainAmountDB[]' id='RemainAmountDB[]' value='".$rowsDB[8]."' />
					<input type='hidden' name='JourTypeDB[]' id='JourTypeDB[]' value='".$rowsDB[11]."' />
					<input type='hidden' name='DirSchemaDB[]' id='DirSchemaDB[]' value='".$rowsDB[12]."' />
					<label><input type='checkbox' name='ChkDB[]' id='ChkDB[]' value='".$rowsDB[0]."' onclick=\"SelectInvoice(this.value,'DB');\"; /></label></span>
				</td>";
		echo "	<td align='left'><span class='style15'>".$rowsDB[5]."</span></td>";
		echo "	<td align='center'><span class='style15'>".$rowsDB[11]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$rowsDB[3]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsDB[1]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsDB[2]."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsDB[6],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsDB[8],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsDB[7],$DecimalBase2)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsDB[9],$DecimalBase2)."</span></td>";
		echo "</tr>";	
		
	}
	
}		
		
echo "	</table></div></div>"; 

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



if ($actionmode == 'Search') {
	echo" <tr>";
	echo"   <td colspan='4' valign='top' bgcolor='#F5F5F5'>";
	
	//Display Receipts
	echo "	<div style='position:relative; float:left; overflow:none; border:1px solid #B5B5B5;' >
			<div style='overflow:none; height:20px; width:490px; margin-top:5px; text-align:center; font-weight:bold;' >RECEIPTS</div>
			<div style='overflow:auto; height:150px; width:490px; margin-top:5px;' >
			<table border='0' cellspacing=1 style='border:2px solid #FFFFFF; table-layout:fixed; width:610px;'>
			  <col width=20>
			  <col width=75>
			  <col width=75>
			  <col width=110>
			  <col width=110>
			  <col width=110>
			  <col width=110>";
			  
	echo"	<tr>";
	echo"		<td align='center'>&nbsp;</td>";
	echo"		<td align='center'><span class='style1'>Reference</span></td>";
	echo"		<td align='center'><span class='style1'>Date</span></td>";
	//echo"		<td align='center'><span class='style1'>Client</span></td>";
	//echo"		<td align='center'>&nbsp;</td>";
	echo"		<td align='center'><span class='style1'>Amount $base1</span></td>";
	echo"		<td align='center'><span class='style1'>Remain $base1</span></td>";
	echo"		<td align='center'><span class='style1'>Amount $base2</span></td>";
	echo"		<td align='center'><span class='style1'>Remain $base2</span></td>";
	echo"	</tr>";		

	$ct = 1;
	$resultRV=mysql_query($QueryRV,$connection) or die(mysql_error());
	while($rowsRV=mysql_fetch_row($resultRV)){
		$ct+=1;

		if($ct%2==0)
			$Color="style='background-color:".$grid_color1."'";
		else			
			$Color="style='background-color:".$grid_color2."'";	
									
		echo "<tr ".$Color." >";
		echo "	<td align='left'><span class='style15'>
					<input type='hidden' name='RemainAmountRV[]' id='RemainAmountRV[]' value='".$rowsRV[8]."' />
					<input type='hidden' name='DirSchemaRV[]' id='DirSchemaRV[]' value='".$rowsRV[11]."' />
					<label><input type='checkbox' name='ChkRV[]' id='ChkRV[]' value='".$rowsRV[12]."' /></label></span>
				</td>";
		echo "	<td align='left'><span class='style15'>".$rowsRV[5]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$rowsRV[3]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsRV[1]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsRV[2]."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsRV[6],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsRV[8],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsRV[7],$DecimalBase2)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsRV[9],$DecimalBase2)."</span></td>";
		echo "</tr>";	
		
	}
	
	echo "	</table></div></div>";
	
	//Display Credit Notes
	echo "	<div style='position:relative; float:right; overflow:none; border:1px solid #B5B5B5; margin-left:10px;' >
			<div style='overflow:none; height:20px; width:490px; margin-top:5px; text-align:center; font-weight:bold;' >CREDIT NOTES</div>
			<div style='overflow:auto; height:150px; width:490px; margin-top:5px;' >
			<table border='0' cellspacing=1 style='border:2px solid #FFFFFF; table-layout:fixed; width:610px;'>
			  <col width=20>
			  <col width=75>
			  <col width=75>
			  <col width=110>
			  <col width=110>
			  <col width=110>
			  <col width=110>";
			  
	echo"	<tr>";
	echo"		<td align='center'>&nbsp;</td>";
	echo"		<td align='center'><span class='style1'>Reference</span></td>";
	echo"		<td align='center'><span class='style1'>Date</span></td>";
	//echo"		<td align='center'><span class='style1'>Client</span></td>";
	//echo"		<td align='center'>&nbsp;</td>";
	echo"		<td align='center'><span class='style1'>Amount $base1</span></td>";
	echo"		<td align='center'><span class='style1'>Remain $base1</span></td>";
	echo"		<td align='center'><span class='style1'>Amount $base2</span></td>";
	echo"		<td align='center'><span class='style1'>Remain $base2</span></td>";
	echo"	</tr>";		

	$i  = 0;
	$ct = 1;
	$resultCV=mysql_query($QueryCV,$connection) or die(mysql_error());
	while($rowsCV=mysql_fetch_row($resultCV)){
		$ct+=1;

		if($ct%2==0)
			$Color="style='background-color:".$grid_color1."'";
		else			
			$Color="style='background-color:".$grid_color2."'";	
									
		echo "<tr ".$Color." >";
		echo "	<td align='left'><span class='style15'>
					<input type='hidden' name='RemainAmountCV[]' id='RemainAmountCV[]' value='".$rowsCV[8]."' />
					<input type='hidden' name='DirSchemaCV[]' id='DirSchemaCV[]' value='".$rowsCV[11]."' />
					<label><input type='checkbox' name='ChkCV[]' id='ChkCV[]' value='".$rowsCV[12]."' /></label></span>
				</td>";
		echo "	<td align='left'><span class='style15'>".$rowsCV[5]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$rowsCV[3]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsCV[1]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsCV[2]."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsCV[6],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsCV[8],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsCV[7],$DecimalBase2)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsCV[9],$DecimalBase2)."</span></td>";
		echo "</tr>";	
		
	}
	
	echo "	</table></div></div>";
	echo "	</td>"; 
	echo " </tr>";
	
	echo" <tr>";
	echo"   <td colspan='4' valign='top' bgcolor='#F5F5F5'>";
	
	//Display Return Invoices		
	echo"	<div style='position:relative; float:left; overflow:none; border:1px solid #B5B5B5;' >
			<div style='overflow:none; height:20px; width:490px; margin-top:5px; text-align:center; font-weight:bold;' >RETURN INVOICE</div>
			<div style='overflow:auto; height:150px; width:490px; margin-top:5px;' >
			<table border='0' cellspacing=1 style='border:2px solid #FFFFFF; table-layout:fixed; width:610px;'>
			  <col width=20>
			  <col width=75>
			  <col width=75>
			  <col width=110>
			  <col width=110>
			  <col width=110>
			  <col width=110>";
			  
	echo"	<tr>";
	echo"		<td align='center'>&nbsp;</td>";
	echo"		<td align='center'><span class='style1'>Reference</span></td>";
	echo"		<td align='center'><span class='style1'>Date</span></td>";
	//echo"		<td align='center'><span class='style1'>Client</span></td>";
	//echo"		<td align='center'>&nbsp;</td>";
	echo"		<td align='center'><span class='style1'>Amount $base1</span></td>";
	echo"		<td align='center'><span class='style1'>Remain $base1</span></td>";
	echo"		<td align='center'><span class='style1'>Amount $base2</span></td>";
	echo"		<td align='center'><span class='style1'>Remain $base2</span></td>";
	echo"	</tr>";		

	$ct = 1;
	$resultSR=mysql_query($QuerySR,$connection) or die(mysql_error());
	while($rowsSR=mysql_fetch_row($resultSR)){
		$ct+=1;

		if($ct%2==0)
			$Color="style='background-color:".$grid_color1."'";
		else			
			$Color="style='background-color:".$grid_color2."'";	
									
		echo "<tr ".$Color." >";
		echo "	<td align='left'><span class='style15'>
					<input type='hidden' name='RemainAmountSR[]' id='RemainAmountSR[]' value='".$rowsSR[8]."' />
					<input type='hidden' name='DirSchemaSR[]' id='DirSchemaSR[]' value='".$rowsSR[11]."' />
					<label><input type='checkbox' name='ChkSR[]' id='ChkSR[]' value='".$rowsSR[0]."' /></label></span>
				</td>";
		echo "	<td align='left'><span class='style15'>".$rowsSR[5]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$rowsSR[3]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsSR[1]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsSR[2]."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsSR[6],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsSR[8],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsSR[7],$DecimalBase2)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsSR[9],$DecimalBase2)."</span></td>";
		echo "</tr>";	
		
	}
	
	echo "	</table></div></div>";
	
	
	//Display Others
	echo "	<div style='position:relative; float:right; overflow:none; border:1px solid #B5B5B5; margin-left:10px;' >
			<div style='overflow:none; height:20px; width:490px; margin-top:5px; text-align:center; font-weight:bold;' >OTHERS</div>
			<div style='overflow:auto; height:150px; width:490px; margin-top:5px;' >
			<table border='0' cellspacing=1 style='border:2px solid #FFFFFF; table-layout:fixed; width:630px;'>
			  <col width=20>
			  <col width=75>
			  <col width=40>
			  <col width=75>
			  <col width=110>
			  <col width=110>
			  <col width=110>
			  <col width=110>";
			  
	echo"	<tr>";
	echo"		<td align='center'>&nbsp;</td>";
	echo"		<td align='center'><span class='style1'>Reference</span></td>";
	echo"		<td align='center'><span class='style1'>Type</span></td>";
	echo"		<td align='center'><span class='style1'>Date</span></td>";
	//echo"		<td align='center'><span class='style1'>Client</span></td>";
	//echo"		<td align='center'>&nbsp;</td>";
	echo"		<td align='center'><span class='style1'>Amount $base1</span></td>";
	echo"		<td align='center'><span class='style1'>Remain $base1</span></td>";
	echo"		<td align='center'><span class='style1'>Amount $base2</span></td>";
	echo"		<td align='center'><span class='style1'>Remain $base2</span></td>";
	echo"	</tr>";		

	$i  = 0;
	$ct = 1;
	$resultJV=mysql_query($QueryJV,$connection) or die(mysql_error());
	while($rowsJV=mysql_fetch_row($resultJV)){
	
		$ct+=1;

		if($ct%2==0)
			$Color="style='background-color:".$grid_color1."'";
		else			
			$Color="style='background-color:".$grid_color2."'";	
									
		echo "<tr ".$Color." >";
		echo "	<td align='left'><span class='style15'>
					<input type='hidden' name='RemainAmountJV[]' id='RemainAmountJV[]' value='".$rowsJV[8]."' />
					<input type='hidden' name='DirSchemaJV[]' id='DirSchemaJV[]' value='".$rowsJV[12]."' />
					<label><input type='checkbox' name='ChkJV[]' id='ChkJV[]' value='".$rowsJV[13]."' /></label></span>
				</td>";
		echo "	<td align='left'><span class='style15'>".$rowsJV[5]."</span></td>";
		echo "	<td align='center'><span class='style15'>".$rowsJV[11]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$rowsJV[3]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsJV[1]."</span></td>";
		//echo "	<td align='left'><span class='style15'>".$rowsJV[2]."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsJV[6],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsJV[8],$DecimalBase1)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsJV[7],$DecimalBase2)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($rowsJV[9],$DecimalBase2)."</span></td>";
		echo "</tr>";	
		
	}
	
	echo "	</table></div></div>";
	
	
	echo "	</td>"; 
	echo " </tr>";
	
}		
		


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

echo"   </table></td></tr><tr height='30'><td align='center' id='content-bottom' ></td></tr>";  
echo" </table>  ";//end of last table menu


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

function explodeword($date)
{

$trim = explode('/',$date);
$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
return $trim;
}
echo"  
</form>
</body>
</html>";

?>