<?php

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


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

set_time_limit(0);

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

$querysetup="select DecimalBase, DecimalBase1, DecimalBase2, Base1, Base2, grid_color1, grid_color2 from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}

$querylog=" select 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);
}

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


//Read From Module Table
$querymodule=" Select ifNull(Module_Delivery,0) As Module_Delivery, ".
			 " ifNull(Module_ProjectParent,0) As Module_ProjectParent, ifNull(Module_CostCenterParent,0) As Module_CostCenterParent ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$MainCompanyName=explode('_',$_SESSION['dbName']);

$queryperiod= " Select ifNull(LockViewPeriod,0) As LockViewPeriod, ViewPeriodDate, ifNull(ViewLockDaily,0) As ViewLockDaily, ViewNumberOfDays ".
              " From ".$_SESSION['dbLabel'].".ListUserDir  ".
			  " Where Usercode='".$_SESSION['useraccount']."' ".
			  " And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
			  " And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
			  
$resultperiod = mysql_query($queryperiod,$connection) or die(mysql_error());
$rowsperiod   = mysql_num_rows($resultperiod);

while($rows=mysql_fetch_array($resultperiod)){
	extract($rows);
}	
			  
//echo $queryperiod;	

$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['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='".$_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 (($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='".$_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);	  

$queryledger= " select distinct ledger_number, ledger_include ".
              " from ".$_SESSION['dbLabel'].".ledgerstk  ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " and (ledger_number is not null and ledger_number != '') ".
			  " order by ledger_number";
$ledgerresult = mysql_query($queryledger,$connection) or die(mysql_error());
$ledgerexist  = mysql_num_rows($ledgerresult);	
$rows=mysql_fetch_array($ledgerresult) ;
$ledgerinclude = $rows[1];

if($PTransType == 'RV') $trans_name = 'Receipts';
if($PTransType == 'CV') $trans_name = 'Credit Note';
if($PTransType == 'PV') $trans_name = 'Payments';
if($PTransType == 'DV') $trans_name = 'Debit Note';

$vMainCompanyName=explode('_',$_SESSION['dbName']);  
$DirCompany  = $vMainCompanyName[0];
preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
$DirYear =  $DirYears[0][0];  

$sub_query = "SELECT
					journal_id 
				FROM
					Temp_Trans AS TransDt 
					inner join transdt as tdt on TransDt.trans_id = tdt.trans_id 
				WHERE
					TransDt.Trans_ID = '".$PTransId."'
					AND EXISTS ( SELECT 1 FROM LedgerInvoice WHERE tdt.Ledger_Number LIKE concat( LedgerInvoice.Ledger_Number, '%' ) )";
			  
					      
//  echo $sub_query."<br><br>";
$sub_result = selectData($connection, $sub_query);

$TransJournalId    = $sub_result[0]; 

//Select Data From TransDt For Selected Record
//   echo "<BR>".
$sub_query = " Select TransDt.Ledger_Number, TransDt.Currency_Code, TransDt.Trans_Date, ifNull( Transdt_Amount, 0 ) as Transdt_Amount ".
			 " From Temp_TransDt As TransDt ".
			" Where TransDt.TransDt_ID = '".$PTransDtId."' 
			and exists (select 1 from LedgerInvoice where TransDt.Ledger_Number like concat(LedgerInvoice.Ledger_Number,'%'))";
			  
					      
// echo $sub_query."<br><br>";
$sub_result = selectData($connection, $sub_query);

$LedgerNumber    = $sub_result[0];
$TransDtCurr     = $sub_result[1];
$TransDtDate     = $sub_result[2];
$Transdt_Amount = $sub_result[3]; 


if($Transdt_Amount != '' && $Transdt_Amount > 0 ){ 
			 $sub_query2 = "	
							SELECT
							sum( amount ) 
							FROM
							".$_SESSION['dbLabel'].".temp_alloclink 
							WHERE
							IF
							( '$TransJournalId' <> '', journal_idC = '$TransJournalId' or  journal_idD = '$TransJournalId'  , ( trans_id = $PTransId AND transdt_id = $PTransDtId ) ) 
							AND AllocYear = '$DirYear' 
							AND AllocComp = '$DirCompany'";
 

	    // echo "<BR>".$sub_query2."<br>";
$sub_result2 = selectData($connection, $sub_query2); 
$InvoiceAmount =  $sub_result2[0];
	 
	
}

print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="default.css" type="text/css" />
<title>List of Invoices</title>
<script type="text/javascript" src="js/grid/UI_DataGrid.js"></script>
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>
<script type="text/javascript" language="javascript">

function RefreshPage()
{
	document.search.submit();
}
 
function SelectRecord(i) {
	var f = document.search;
	var TransType = f.PTransType.value;
	var SR_chk = document.getElementById('M'+i);
	var TransAmount = f.TransDtAmount_D.value;
	f.InvoiceAmount_D.value = f.InvoiceAmount_D.value;
	var RemainingTransAmount = f.RemainAmount_D.value;
	
	var SR_Max = document.getElementById('RM'+i).value;
	var SR_AmounttoPay = document.getElementById('amounttopay'+i).value; 

	if(SR_chk.checked){
		if(parseFloat(RemainingTransAmount) > 0){
			TransAmount = TransAmount.replace(',','');
			f.InvoiceAmount_D.value = f.InvoiceAmount_D.value.replace(',','');
			RemainingTransAmount = RemainingTransAmount.replace(',','');
			if(parseFloat(RemainingTransAmount) <= parseFloat(SR_Max) ){
				document.getElementById('amounttopay'+i).value = parseFloat(RemainingTransAmount);
				f.InvoiceAmount_D.value = parseFloat(f.InvoiceAmount_D.value) + (parseFloat(TransAmount) -parseFloat(f.InvoiceAmount_D.value));
				f.InvoiceAmount_D.value = f.InvoiceAmount_D.value;
				f.InvoiceAmount_D.value = f.InvoiceAmount_D.value.replace(',','');
				f.RemainAmount_D.value =  parseFloat(TransAmount) - parseFloat(f.InvoiceAmount_D.value);
			}else{
				document.getElementById('amounttopay'+i).value = parseFloat(SR_Max);
				f.InvoiceAmount_D.value = parseFloat(f.InvoiceAmount_D.value) + parseFloat(SR_Max);
				f.InvoiceAmount_D.value = f.InvoiceAmount_D.value;
				f.InvoiceAmount_D.value = f.InvoiceAmount_D.value.replace(',','');
				f.RemainAmount_D.value =  parseFloat(TransAmount) - parseFloat(f.InvoiceAmount_D.value);
			}
		}else{
			alert('amount fully Allocated');
			SR_chk.checked = false;
			return;
		}
		// fill the textbox with the value if the amount to be allocated is less or equal to the remaining amount to be allocated for this line
		// else fill the max amount
	}else{
		var oldpaidAmount = document.getElementById('amounttopay'+i).value.replace(',','');
		TransAmount = TransAmount.replace(',','');
		document.getElementById('amounttopay'+i).value = '0.00';
		f.InvoiceAmount_D.value = f.InvoiceAmount_D.value.replace(',','');
		f.InvoiceAmount_D.value = parseFloat(f.InvoiceAmount_D.value.replace(',','')) - parseFloat(oldpaidAmount);
		f.RemainAmount_D.value =  parseFloat(TransAmount) - parseFloat(f.InvoiceAmount_D.value);
	}
	 
  
}

function SetAmountPay(i){
	var f = document.search;
	var TransType = f.PTransType.value;
	var SR_chk = document.getElementById('M'+i);
	SR_chk.checked = true;
	var TransAmount = f.TransDtAmount_D.value;
	f.InvoiceAmount_D.value = f.InvoiceAmount_D.value;
	var RemainingTransAmount = f.RemainAmount_D.value;
	
	var SR_Max = document.getElementById('RM'+i).value;
	var SR_AmounttoPay = document.getElementById('amounttopay'+i).value; 

	if(SR_chk.checked){
		if(parseFloat(RemainingTransAmount) > 0){
			TransAmount = TransAmount.replace(',','');
			f.InvoiceAmount_D.value = f.InvoiceAmount_D.value.replace(',','');
			RemainingTransAmount = RemainingTransAmount.replace(',','');
			if(parseFloat(RemainingTransAmount) <= parseFloat(SR_Max) && parseFloat(document.getElementById('amounttopay'+i).value) == 0 ){
				document.getElementById('amounttopay'+i).value = parseFloat(RemainingTransAmount);
				f.InvoiceAmount_D.value = parseFloat(f.InvoiceAmount_D.value) + (parseFloat(TransAmount) -parseFloat(f.InvoiceAmount_D.value));
				f.InvoiceAmount_D.value = f.InvoiceAmount_D.value;
				f.InvoiceAmount_D.value = f.InvoiceAmount_D.value.replace(',','');
				f.RemainAmount_D.value =  parseFloat(TransAmount) - parseFloat(f.InvoiceAmount_D.value);
			}else{
				if(parseFloat(document.getElementById('amounttopay'+i).value) <= parseFloat(SR_Max) && parseFloat(f.InvoiceAmount_D.value) + parseFloat(document.getElementById('amounttopay'+i).value) <=  parseFloat(f.TransDtAmount_D.value.replace(',',''))){
 					f.InvoiceAmount_D.value = parseFloat(f.InvoiceAmount_D.value) + parseFloat(document.getElementById('amounttopay'+i).value);
					f.InvoiceAmount_D.value = f.InvoiceAmount_D.value;
					f.InvoiceAmount_D.value = f.InvoiceAmount_D.value.replace(',','');
					f.RemainAmount_D.value =  parseFloat(TransAmount) - parseFloat(f.InvoiceAmount_D.value);
				}else{
					if( parseFloat(SR_Max) <= parseFloat(f.RemainAmount_D.value.replace(',','') ) ){
						document.getElementById('amounttopay'+i).value = parseFloat(SR_Max);
						f.InvoiceAmount_D.value = parseFloat(f.InvoiceAmount_D.value) + parseFloat(SR_Max);
						f.InvoiceAmount_D.value = f.InvoiceAmount_D.value;
						f.InvoiceAmount_D.value = f.InvoiceAmount_D.value.replace(',','');
						f.RemainAmount_D.value =  parseFloat(TransAmount) - parseFloat(f.InvoiceAmount_D.value);
					}else{
						document.getElementById('amounttopay'+i).value = parseFloat(f.RemainAmount_D.value.replace(',','') );
						f.InvoiceAmount_D.value = parseFloat(f.InvoiceAmount_D.value) + parseFloat(f.RemainAmount_D.value.replace(',','') );
						f.InvoiceAmount_D.value = f.InvoiceAmount_D.value;
						f.InvoiceAmount_D.value = f.InvoiceAmount_D.value.replace(',','');
						f.RemainAmount_D.value =  parseFloat(TransAmount) - parseFloat(f.InvoiceAmount_D.value);
					}
					
				}
			}
		}else{
			alert('amount fully Allocated');
			SR_chk.checked = false;
			return;
		}
		// fill the textbox with the value if the amount to be allocated is less or equal to the remaining amount to be allocated for this line
		// else fill the max amount
	}else{
		var oldpaidAmount = document.getElementById('amounttopay'+i).value.replace(',','');
		TransAmount = TransAmount.replace(',','');
		document.getElementById('amounttopay'+i).value = '0.00';
		f.InvoiceAmount_D.value = f.InvoiceAmount_D.value.replace(',','');
		f.InvoiceAmount_D.value = parseFloat(f.InvoiceAmount_D.value.replace(',','')) - parseFloat(oldpaidAmount);
		f.RemainAmount_D.value =  parseFloat(TransAmount) - parseFloat(f.InvoiceAmount_D.value);
	}
	 
  
}


	
function LoadData(){
 
	let f = document.search;
	if(parseFloat(f.InvoiceAmount_D.value) == 0) {
		alert ("invalid Allocation");
		return;
	} 
	let TransType = f.PTransType.value;

	var x = document.search;
	var vSelectedRows ;
	vSelectedRows = '';
	
	for (var i=1; i <= document.search.i.value; i++)
	{
		MasterCheckName='M'+i; 
		b = document.getElementById(MasterCheckName);
		if (b.checked) vSelectedRows = vSelectedRows + ',' + b.value;	
	}
	vSelectedRows = vSelectedRows.substr(1);
	if (vSelectedRows != '') {
		var vTransId    = x.PTransId.value; 
		var vTransDtId  = x.PTransDtId.value;
		var vTransType  = x.PTransType.value;
		var vTransCurr  = x.CurrencyCode.value;
		
		var vMainMode = x.mainaction.value; 
		
	/*	if (vRemainAmountB1 != 0) {
			alert('Total Invoice(s) should be equal to receipt amount.');
		} else
		{*/
			x.PMode.value=1;	
			x.action="Form_Trans_Actions.php?mode=loadinvoices2&mainmode="+vMainMode+"&TransType="+vTransType+"&STransId="+vTransId+"&STransDtId="+vTransDtId+"&SSelectedRows="+vSelectedRows;
			opener.document.trans.submit();
			x.submit(); 
		/* 
		} */	
	} else
		alert ('Please Select an Invoice.');
	
}
 
</script>

<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;
}
.style11 {color: #999999; font-weight: bold; }
.style12 {
	font-size: 9px;
	color: #999999;
	font-weight: bold;
}
.style15 {color: #5151FF; }
.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: #000000 ;font-size: 10px;}

</style>

</head>
<body onLoad='LoadForm();'>
<form name='search' method='post' action=''>
<input type='hidden' name='SelectedRows' value='$SelectedRows'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type="hidden" name="PTransType" value ='$PTransType'>
<input type="hidden" name="PTransId" value ='$PTransId'>
<input type="hidden" name="PTransDtId" value ='$PTransDtId'>
<input type="hidden" name="CurrencyCode" value ='$TransDtCurr'>
<input type="hidden" name="TransJournalId" value ='$TransJournalId'>
<input type="hidden" name="vledgerNum" value ='$LedgerNumber'>
HERE;
echo "<input type='hidden' name='message' value='".htmlspecialchars($message, ENT_QUOTES)."'>";


echo"<table border='0' cellspacing='1'  align='center' width='1180px'>
	  <col width=20>
	  <col width=40>
	  <col width=60>
	  <col width=60>
	  <col width=80>
	  <col width=105>
	  <col width=105>
	  <col width=120>
	  <col width=140> 
	
		     
	  <tr bgcolor='#DDDDDD'>
	    <td align='center' colspan='10'><span class='style16'>$trans_name - List of Invoices</span></td></tr>
	  <tr bgcolor='#DDDDDD'>
	    <td align='left' colspan='4'><span class='style11'>Search by Reference</span></td>
		<td align='left' colspan='5'><span class='style11'><input type='text' name='PRef' id='PRef' value='$PRef' size='15' maxlength='30'/><input type='hidden' name='PMode' id='PMode' value='$PMode' size='15' maxlength='30'/></span>
		    <input type='submit' name='btnSubmit' value='Find' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'/>
			<input type='button' name='btnCancel' value='Cancel' onclick='ClearForm();'style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'/>
			<input type='button' name='btnLoad' value='Load' onclick='LoadData();'style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'/>
		</td>
		<td align='left' valign='center' ><span class='style11'>Result per page </span><span class='style11'><select name='perpage' id='perpage' value='$perpage' onchange='RefreshPage();'>";
              

        if ($perpage==20)
			$s20 = 'selected';
		else if ($perpage==30)
			$s30 = 'selected';
		else if ($perpage==40)
			$s40 = 'selected';
		else if ($perpage==50)
			$s50 = 'selected';
			
				
        echo'<option '.$s20.' value="20">20</option>
			 <option '.$s30.' value="30">30</option>
			 <option '.$s40.' value="40">40</option>
			 <option '.$s50.' value="50">50</option>
			 </select></span></td>';	
echo" </tr>";
echo" <tr bgcolor='#DDDDDD'><td colspan='10' align='left'>
		<span class='style11'>Total Receipt</span>
		<input type='text' name='TransDtAmount_D' id='TransDtAmount_D' value='".number_format($Transdt_Amount, $DecimalBase1)."' style='width:120px; text-align:right;' readonly/>	
		<span class='style11'>Total Invoice(s)</span>
		<input type='text' name='InvoiceAmount_D' id='InvoiceAmount_D' value='".number_format($InvoiceAmount, $DecimalBase1)."' style='width:120px; text-align:right;' readonly/>	
		<span class='style11'>Remain Amount</span>
		<input type='text' name='RemainAmount_D' id='RemainAmount_D' value='".number_format(($Transdt_Amount-$InvoiceAmount), $DecimalBase1)."' style='width:120px; text-align:right;' readonly/>	
	  </td></tr>"; 


//echo" <tr bgcolor='#DDDDDD'><td colspan='10' align='center'><input type='button' name='btnLoad' value='Load' onclick='LoadData();'style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'/></td></tr>";
echo" <tr bgcolor='#DDDDDD'>
		<td height='15' align='center' colspan='10'><font size='1' color='#FF0000' face='Verdana'><b>".$message."</b></font></td>
	  </tr>	
	  <tr bgcolor='#CCD8E6'>
		<td  height='25' align='center'><span class='style25'>&nbsp;</span></td>
		<td  height='25' align='left'><span class='style25'>Ref.</span></td>
		<td  height='25' align='left'><span class='style25'>Type</span></td>
		<td  height='25' align='left'><span class='style25'>Manual No.</span></td> 
		<td  height='25' align='center'><span class='style25'>Date </span></td>
		<td  height='25' align='center'><span class='style25'>Initial Amount $Base1</span></td>
		<td  height='25' align='center'><span class='style25'>NetTotal $Base1</span></td>
		<td  height='25' align='center'><span class='style25'>Amount to be paid $Base1</span></td>"; 
echo "<td  height='25' align='left' colspan='1'><span class='style25'>Description</span></td>";
echo "<td  height='25' align='left' colspan='1'><span class='style25'>Remark</span></td>";
echo" </tr>";
		



	
if (empty($PRef))   
   $PRef = 'Null';
else
   $PRef = "'".$PRef."'"; 

if (empty($ViewPeriodDate))
   $ViewPeriodDate = 'Null';
if (empty($ViewNumberOfDays))   
   $ViewNumberOfDays = 1;
    
$query = '';
$query = "
SELECT
	J.journal_id as JVID,
	J.journal_type,
	JDT.Currency_code,
	date_format(JDT.journal_date, '%d/%m/%Y') as jdtdate,
	ifnull( tempAllocatedC.AllocatedAmount, 0 ) as existsintemp,
	ifnull( tempAllocatedC.allocRemark, '' ) as existsintempRem,
	ifnull( J.Journal_refgovernment, '' ) cd_jvRef,
	concat ( ifnull( cd_transQuery.trans_reference, '' )   , ifnull( cd_purQuery.purchase_reference, '' )   , ifnull( cd_delQuery.delivery_reference, '' )  ) as REF,
	concat ( ifnull( J.manual_no, '' ) , ifnull( cd_transQuery.trans_manualno, '' ) ,  ifnull( cd_purQuery.purchase_InvoiceNo, '' ) ,ifnull( cd_delQuery.Delivery_ManualNo, '' ) ) as manual_no,
	concat ( ifnull( J.Journal_Remark, ''), ifnull( cd_transQuery.trans_reference, '' ), ifnull( cd_transQuery.trans_remark, '' ), ifnull( cd_purQuery.purchase_remark, '' ), ifnull( cd_delQuery.delivery_remark, '' ) ) as description ,
	ifnull( JDT.Journaldt_amount, 0 ) initialamnt1,
	ifnull( allALlocatedCredits.AllocatedAmount, 0 ) + ifnull( tempAllocatedC.AllocatedAmount, 0 )  AllocatedAmount,
	ifnull(
		round( ifnull( JDT.Journaldt_amount, 0 ) - ifnull( allALlocatedCredits.AllocatedAmount, 0 ), 2 ) - ifnull( tempAllocatedC.AllocatedAmount, 0 ),
		0 
	) remainingAmount,
	tempTransAllocated.AllocatedAmount as currTransAllocEIT,
	tempTransAllocated.allocRemark as currTransAllocEITrem 
FROM
	journal J
	Inner JOIN journaldt JDT ON J.journal_id = JDT.journal_id 
	LEFT JOIN (
		SELECT
			journal_idC,
			sum( amount ) AllocatedAmount,
			sum( amountbase1 ) AllocatedAmount1,
			sum( amountbase2 ) AllocatedAmount2,
			ifnull(allocRemark, '') as allocRemark,ledger_number
		FROM
		".$_SESSION['dbLabel'].".temp_alloclink 
		where 
		UPPER(alloccomp) = Upper('".$MainCompanyName[0]."') 
		and ledger_number = '$LedgerNumber'
		GROUP BY
			journal_idC ,ledger_number
		) tempAllocatedC ON J.journal_id = tempAllocatedC.journal_idC ";
		if($PTransType == "PV" || $PTransType == "DV"){
			$query.=" LEFT JOIN (
				select journal_idC, sum(amount) AllocatedAmount ,sum(amountbase1) AllocatedAmount1 ,sum(amountbase2) AllocatedAmount2 ,ledger_number
				from  ".$_SESSION['dbLabel'].".alloclink
				where 
				UPPER(alloccomp) = Upper('".$MainCompanyName[0]."') 
				and ledger_number = '$LedgerNumber'
				 group by journal_idC ,ledger_number
				
				) allALlocatedCredits on J.journal_id = allALlocatedCredits.journal_idC ";
		}else{
			$query.=" LEFT JOIN (
				select journal_idD, sum(amount) AllocatedAmount ,sum(amountbase1) AllocatedAmount1 ,sum(amountbase2) AllocatedAmount2,ledger_number
				 from  ".$_SESSION['dbLabel'].".alloclink
				 where 
				 UPPER(alloccomp) = Upper('".$MainCompanyName[0]."') 
				 and ledger_number = '$LedgerNumber'
				  group by journal_idD ,ledger_number
				
				) allALlocatedCredits on J.journal_id = allALlocatedCredits.journal_idD ";
			
		} 
$query.=" LEFT JOIN (
	
	select journal_idD, sum(amount) AllocatedAmount ,sum(amountbase1) AllocatedAmount1 ,sum(amountbase2) AllocatedAmount2 , transtype ,ledger_number
	from  ".$_SESSION['dbLabel'].".temp_alloclink 
	where 
		UPPER(alloccomp) = Upper('".$MainCompanyName[0]."') 
		and ledger_number = '$LedgerNumber'
	group by journal_idD ,ledger_number
	
	
	) tempAllocated on J.journal_id = tempAllocated.journal_idD 
	left join (
		SELECT
		journal_idD,
		sum( amount ) AllocatedAmount,
		sum( amountbase1 ) AllocatedAmount1,
		sum( amountbase2 ) AllocatedAmount2,
		ifnull(trans_id , '')  as trans_id,
		ifnull(transtype , '')  as transtype,
		ifnull(allocRemark, '') as allocRemark,ledger_number
	FROM
		".$_SESSION['dbLabel'].".temp_alloclink  
		where 
		UPPER(alloccomp) = Upper('".$MainCompanyName[0]."') 
		and ledger_number = '$LedgerNumber'
	GROUP BY
		journal_idD, trans_id, transtype,ledger_number
	) tempTransAllocated ON J.journal_id = tempTransAllocated.journal_idD and tempTransAllocated.transtype = '$PTransType' and tempTransAllocated.trans_id = $PTransId
	LEFT JOIN ( SELECT purchase_id, purchase_reference, purchase_remark, purchase_InvoiceNo, journal_type,journal_id  FROM purchases where supplier_code = '$LedgerNumber') AS cd_purQuery ON J.journal_id = cd_purQuery.journal_id
	LEFT JOIN ( SELECT delivery_id, delivery_reference, delivery_remark, Delivery_ManualNo, Journal_Type,journal_id FROM deliveries where client_code = '$LedgerNumber') AS cd_delQuery ON J.journal_id = cd_delQuery.journal_id  
	LEFT JOIN ( SELECT Sale_id, Sale_Reference, Sale_Remark, Sale_ManualNo, journal_type,journal_id  FROM .sales where client_code = '$LedgerNumber') AS cd_salQuery ON J.journal_id = cd_salQuery.journal_id  
	LEFT JOIN ( SELECT trans.trans_id, trans_reference, trans_remark, trans_manualno, trans_type,journal_id FROM trans,transdt where trans.trans_id = transdt.trans_id and transdt.ledger_number = '$LedgerNumber' ) AS cd_transQuery ON J.journal_id = cd_transQuery.journal_id  
 WHERE
	JDT.Ledger_Number = '$LedgerNumber'
	and JDT.journal_id not in (select ifnull(journal_id,0) from temp_trans where trans_id = $PTransId)
	and IF ( '$PTransType' = 'PV' or '$PTransType' = 'DV' , JDT.journaldt_dbcd = 'C' , if ( '$PTransType' = 'RV' or '$PTransType' = 'CV' , JDT.journaldt_dbcd = 'D' , 1=1) )   
	and J.Journal_BelongsToGroup = ifnull($FI_BelongsToGrp,5)
	And JDT.journal_date <= (select date_format(trans_date, '%Y-%m-%d 23:59:59') from temp_trans where trans_id = $PTransId)
	
	having remainingAmount > 0.1 
	
	order by  JDT.journal_date asc
	";
// if ($projectexist >	0) {
		// $query = $query." 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 on (($Module_ProjectParent=1 and headerlink.project_code like concat(Qp.project_code,'%')) or ($Module_ProjectParent=0 and headerlink.project_code = Qp.project_code )) ";
	// }
	// if ($costcentexist > 0) {
		// $query = $query." 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 on (($Module_CostCenterParent=1 and headerlink.Costcent_Code like concat(Qc.costcent_code,'%')) or ($Module_CostCenterParent=0 and headerlink.Costcent_Code = Qc.costcent_code )) ";							 
	// }							
//echo "<br>".$query."<br>";
//exit;   

if ($PMode != '1') {
$result=mysql_query($query,$connection) or die(mysql_error());
 
$i = 0;

while($rows=mysql_fetch_array($result)){
		
	extract($rows);
	$ct+=1;
	$i = $i + 1;

	if($ct%2==0)
		$Color="style='background-color:".$grid_color1."'";
	else			
		$Color="style='background-color:".$grid_color2."'";	
	
	
	echo'<tr '.$Color.'>';
			
    $SelMaster  = 'M'.$i;
	$$SelMaster = $i; 
	 
	echo"	<td align='center'><span class='style15'> "; 
	if($currTransAllocEIT > 0 ) $ischeked = "checked";
	else $ischeked = '';
	echo "	<input type='checkbox' name='$SelMaster' id='$SelMaster' value='".$$SelMaster."' $ischeked onclick=\"SelectRecord($i);\" /></span>
			</td>";
	if($REF == '') 
	$REF =    $cd_jvRef ; 
	echo'	<td align="left"><span class="style15">'.$REF .'</span></td>
			<td align="left"><span class="style15">'.$journal_type.'</span></td>
			<td align="left"><span class="style15">'.$manual_no.'</span></td> 
			<td align="right"><span class="style15">'.$jdtdate.'</span></td>
			<td align="right"><span class="style15">'.number_format($initialamnt1, $DecimalBase1).'</span></td>
			<td align="right">
				<span class="style15"  >'.number_format($remainingAmount, $DecimalBase1).'</span> 
				<input type="hidden" name="RM'.$i.'"  id="RM'.$i.'" value ="'.$remainingAmount.'">
				<input type="hidden" name="JVID'.$i.'"  id="JVID'.$i.'" value ="'.$JVID.'">
			</td>'; 
 
	if($currTransAllocEIT > 0 ) $amounttop = $currTransAllocEIT;
	else $amounttop = '0.00';
	echo "<td align='center'><span class='style15'>
		<input type='text' name='amounttopay$i' id='amounttopay$i' value='$amounttop' style='width:120px;text-align:right;' onchange=\"SetAmountPay('$i');\"></span></td>";
	echo "<td align='center' ><span class='style15'>$description</span></td>";
	
	if($currTransAllocEITrem != '' ) $CurrRemRem = $currTransAllocEITrem;
	else $CurrRemRem = ' ';
	echo "<td align='center' ><span class='style15'>
		<input type='text' name='remark$i' id='remark$i' value='$CurrRemRem' style='width:200px;text-align:left;font-size:12;'></span></td>";
	echo'</tr>';
		

}
echo"<input type='hidden' value = '$i' id='i' name= 'i' >";
if (!empty($LedgerNumber)) {
	echo"   <tr bgcolor='#DDDDDD'><td colspan='10' align='center'><input type='button' name='btnLoad' value='Load' onclick='LoadData();'style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'/></td></tr>";
}			
echo"   <tr><td colspan='9'>&nbsp;</td></tr>
		<tr><td colspan='9'><table width='100%' border=0><tr><td width='230'>&nbsp;</td><td width='150' align='center'>";
		
			echo "&nbsp;"; 
		echo"</td><td width='150' align='center'>";
			echo "&nbsp;"; 
		echo"</td><td width='230'>&nbsp;</td></tr>";
		echo"</table>";
		
}		

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

print <<<HERE

</form>
</body>

HERE;

?>