<?php

session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

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

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

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
set_time_limit(0);

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, Ledger_ValidateProject from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}


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


 $querylog=" select ifNull(FA_ChangeBelongToGroup,0) As FA_ChangeBelongToGroup ".
		  " from ".$_SESSION['dbLabel'].".listuserdir where Usercode = '".$_SESSION['useraccount']."' and upper(concat(CompanyName,'_',Diryear)) = Upper('".$_SESSION['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}
//Read From Module Table
$querymodule=" Select ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ".
			 " ifNull(Module_AcctrxPostPV,0) As Module_AcctrxPostPV, ifNull(Module_AcctrxPostRV,0) As Module_AcctrxPostRV, ifNull(Module_AcctrxPostDV,0) As Module_AcctrxPostDV, ".
			 " ifNull(Module_AcctrxPostCV,0) As Module_AcctrxPostCV, ifNull(Module_AcctrxPostCT,0) As Module_AcctrxPostCT, ifNull(Module_AcctrxPost,0) As Module_AcctrxPost, ".
			 " ifNull(Module_Delivery,0) As Module_Delivery, ifNull(Module_UniqueManualNo,0) As Module_UniqueManualNo, ifNull(Module_Project,0) As Module_Project, ".
			 " ifNull(Module_Costcenter,0) As Module_CostCenter, ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_InvoiceGrid,0) As Module_InvoiceGrid, ifNull(Module_ProjectParent,0) As Module_ProjectParent, ifNull(Module_CostCenterParent,0) As Module_CostCenterParent, ".
			 " ifnull(Module_RestrictProjCost,0) as Module_RestrictProjCost, ifnull(Module_RestrictCost,0) as Module_RestrictCost, ifnull(Module_ReferenceByBelongsToGroup,0) as Module_ReferenceByBelongsToGroup, ".
			 " ifnull(Module_InvoiceGridPV,0) as Module_InvoiceGridPV, ifnull(Module_InvoiceGridRV,0) as Module_InvoiceGridRV,  ifnull(Module_InvoiceGridCV,0) as Module_InvoiceGridCV ,".
			 " ifnull(Module_InvoiceGridDV,0) as Module_InvoiceGridDV, ifnull(Module_InvoiceGridCT,0) as Module_InvoiceGridCT ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

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

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


$querymodule=" Select ifNull(paymentrqstNoDt,0) As paymentrqstNoDt ".
			 " From paymentsetup";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


$vMainCompanyName=explode('_',$_SESSION['dbName']);  
$DirCompany  = $vMainCompanyName[0];
$DirYear	 = $vMainCompanyName[1]; 
	
	
$mode 		    = $_GET['mode']; if ($mode == ""){$mode = $_POST["mode"];}
$mainmode       = $_GET['mainmode'];if ($mainmode == ""){$mainmode = $_POST["mainmode"];}
$STransId       = $_GET['STransId'];if ($STransId == ""){$STransId = $_POST["STransId"];}
$STransDtId     = $_GET['STransDtId'];if ($STransDtId == ""){$STransDtId = $_POST["STransDtId"];}
$TransType      = $_GET['TransType'];if ($TransType == ""){$TransType = $_POST["TransType"];}
$CashBank       = $_GET['CashBank'];if ($CashBank == ""){$CashBank = $_POST["CashBank"];}
$SDetailSide    = $_GET['SDetailSide'];if ($SDetailSide == ""){$SDetailSide = $_POST["SDetailSide"];}
$SAccountType   = $_GET['SAccountType'];if ($SAccountType == ""){$SAccountType = $_POST["SAccountType"];}
$SChkJourDtId   = $_GET['SChkJourDtId'];if ($SChkJourDtId == ""){$SChkJourDtId = $_POST["SChkJourDtId"];}
$SBillJourDtId  = $_GET['SBillJourDtId'];if ($SBillJourDtId == ""){$SBillJourDtId = $_POST["SBillJourDtId"];}
$SCstJourDtId   = $_GET['SCstJourDtId'];if ($SCstJourDtId == ""){$SCstJourDtId = $_POST["SCstJourDtId"];}
$SAccLinkId     = $_GET['SAccLinkId'];if ($SAccLinkId == ""){$SAccLinkId = $_POST["SAccLinkId"];}
$SPaymentRqstId = $_GET['SPaymentRqstId'];if ($SPaymentRqstId == ""){$SPaymentRqstId = $_POST["SPaymentRqstId"];}
$SSorderId      = $_GET['SSorderId'];if ($SSorderId == ""){$SSorderId = $_POST["SSorderId"];}
$blgGrpNo      	= $_GET['blgGrpNo'];if ($blgGrpNo == ""){$blgGrpNo = $_POST["blgGrpNo"];}

if($TransType=='') $TransType=$PTransType;
if ($TransType == 'PV') 	 {$ModulePostTrx = $Module_AcctrxPostPV; $ModuleInvoiceGrid = $Module_InvoiceGridPV;}
else if ($TransType == 'RV') {$ModulePostTrx = $Module_AcctrxPostRV; $ModuleInvoiceGrid = $Module_InvoiceGridRV;}
else if ($TransType == 'DV') {$ModulePostTrx = $Module_AcctrxPostDV; $ModuleInvoiceGrid = $Module_InvoiceGridDV;}
else if ($TransType == 'CV') {$ModulePostTrx = $Module_AcctrxPostCV; $ModuleInvoiceGrid = $Module_InvoiceGridCV;}
else if ($TransType == 'CT') {$ModulePostTrx = $Module_AcctrxPostCT; $ModuleInvoiceGrid = $Module_InvoiceGridCT;}

if($FA_ChangeBelongToGroup == 1) $FI_BelongsToGrp = $blgGrpNo;

$queryjourtype="select Type_Cash, Type_dbcd as Type_dbcd1 from JourType where Type_Name = '".$TransType."'";
$resultjourtype=mysql_query($queryjourtype,$connection) or die(mysql_error());
while($rowjourtype=mysql_fetch_array($resultjourtype)){
	extract($rowjourtype);
}
/*	
print <<<HERE
<body>
<form name='inserttrans' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='STransId' value='$STransId'>
<input type='text' name='STransDtId' value='$STransDtId'>
<input type='text' name='TransType' value='$TransType' >
<input type='text' name='SDetailSide' value='$SDetailSide' >
<input type='hidden' name='SAccountType' value='$SAccountType'>
<input type='text' name='SCstJourDtId' value='$SCstJourDtId' >
<input type='text' name='SChkJourDtId' value='$SChkJourDtId' >
<input type='text' name='SAccLinkId' value='$SAccLinkId' >
<input type='text' name='SPaymentRqstId' value='$SPaymentRqstId' >

HERE;
*/
$message='';

$PTransDate			= $_POST["PTransDate"]; if ($PTransDate == ""){$PTransDate = $_GET["PTransDate"];}
$PTransId			= $_POST["PTransId"]; if ($PTransId == ""){$PTransId = $_GET["PTransId"];}
$PTransDtId 		= $_POST["PTransDtId"]; if ($PTransDtId == ""){$PTransDtId = $_GET["PTransDtId"];}
$PTransType			= $_POST["PTransType"]; if ($PTransType == ""){$PTransType = $_GET["PTransType"];}
$PTransCurr			= $_POST["PTransCurr"]; if ($PTransCurr == ""){$PTransCurr = $_GET["PTransCurr"];}
$PTransCashType		= $_POST["PTransCashType"]; if ($PTransCashType == ""){$PTransCashType = $_GET["PTransCashType"];}
$PTransRepresent	= $_POST["PTransRepresent"]; if ($PTransRepresent == ""){$PTransRepresent = $_GET["PTransRepresent"];}
$PTransRemark		= $_POST["PTransRemark"]; if ($PTransRemark == ""){$PTransRemark = $_GET["PTransRemark"];}
$PTransManualNo		= $_POST["PTransManualNo"]; if ($PTransManualNo == ""){$PTransManualNo = $_GET["PTransManualNo"];}
$PTransProjectCode	= $_POST["PTransProjectCode"]; if ($PTransProjectCode == ""){$PTransProjectCode = $_GET["PTransProjectCode"];}
$PTransCostCentCode	= $_POST["PTransCostCentCode"]; if ($PTransCostCentCode == ""){$PTransCostCentCode = $_GET["PTransCostCentCode"];}

$txtDate			= $_POST["txtDate"]; if ($txtDate == ""){$txtDate = $_GET["txtDate"];}
$txtCurr			= $_POST["txtCurr"]; if ($txtCurr == ""){$txtCurr = $_GET["txtCurr"];}
$txtCashType		= $_POST["txtCashType"]; if ($txtCashType == ""){$txtCashType = $_GET["txtCashType"];}
$txtRemark			= $_POST["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_GET["txtRemark"];}
$txtRepresent		= $_POST["txtRepresent"]; if ($txtRepresent == ""){$txtRepresent = $_GET["txtRepresent"];}
$txtManualNo		= $_POST["txtManualNo"]; if ($txtManualNo == ""){$txtManualNo = $_GET["txtManualNo"];}
$txtProjectCode		= $_POST["txtProjectCode"]; if ($txtProjectCode == ""){$txtProjectCode = $_GET["txtProjectCode"];}
$txtCostCentCode	= $_POST["txtCostCentCode"]; if ($txtCostCentCode == ""){$txtCostCentCode = $_GET["txtCostCentCode"];}

	
$txtLedgerId		= $_POST["txtLedgerId"]; if ($txtLedgerId == ""){$txtLedgerId = $_GET["txtLedgerId"];}
$txtLedgerNo		= $_POST["txtLedgerNo"]; if ($txtLedgerNo == ""){$txtLedgerNo = $_GET["txtLedgerNo"];}
$txtTransDtCurr		= $_POST["txtTransDtCurr"]; if ($txtTransDtCurr == ""){$txtTransDtCurr = $_GET["txtTransDtCurr"];}
$txtTransDtdbcd		= $_POST["txtTransDtdbcd"]; if ($txtTransDtdbcd == ""){$txtTransDtdbcd = $_GET["txtTransDtdbcd"];}
$txtTransDtDesc		= $_POST["txtTransDtDesc"]; if ($txtTransDtDesc == ""){$txtTransDtDesc = $_GET["txtTransDtDesc"];}
$txtTransDtDesc1	= $_POST["txtTransDtDesc1"]; if ($txtTransDtDesc1 == ""){$txtTransDtDesc1 = $_GET["txtTransDtDesc1"];}
$txtTransDtValueDate= $_POST["txtTransDtValueDate"]; if ($txtTransDtValueDate == ""){$txtTransDtValueDate = $_GET["txtTransDtValueDate"];}
$txtTransDtManualNo = $_POST["txtTransDtManualNo"]; if ($txtTransDtManualNo == ""){$txtTransDtManualNo = $_GET["txtTransDtManualNo"];}
$txtClientDtCode	= $_POST["txtClientDtCode"]; if ($txtClientDtCode == ""){$txtClientDtCode = $_GET["txtClientDtCode"];}
$txtTransDtAmount	= $_POST["txtTransDtAmount"]; if ($txtTransDtAmount == ""){$txtTransDtAmount = $_GET["txtTransDtAmount"];}
$txtTransDtAmountB1	= $_POST["txtTransDtAmountB1"]; if ($txtTransDtAmountB1 == ""){$txtTransDtAmountB1 = $_GET["txtTransDtAmountB1"];}
$txtTransDtAmountB2	= $_POST["txtTransDtAmountB2"]; if ($txtTransDtAmountB2 == ""){$txtTransDtAmountB2 = $_GET["txtTransDtAmountB2"];}
$txtTransDtCheckNo	= $_POST["txtTransDtCheckNo"]; if ($txtTransDtCheckNo == ""){$txtTransDtCheckNo = $_GET["txtTransDtCheckNo"];}

$txtChkJourDtLedger	= $_POST["txtChkJourDtLedger"]; if ($txtChkJourDtLedger == ""){$txtChkJourDtLedger = $_GET["txtChkJourDtLedger"];}
$txtCurrCode		= $_POST["txtCurrCode"]; if ($txtCurrCode == ""){$txtCurrCode = $_GET["txtCurrCode"];}
$txtChkJourDtType	= $_POST["txtChkJourDtType"]; if ($txtChkJourDtType == ""){$txtChkJourDtType = $_GET["txtChkJourDtType"];}
$txtCheckNo			= $_POST["txtCheckNo"]; if ($txtCheckNo == ""){$txtCheckNo = $_GET["txtCheckNo"];}
$txtBank			= $_POST["txtBank"]; if ($txtBank == ""){$txtBank = $_GET["txtBank"];}
$txtValueDate		= $_POST["txtValueDate"]; if ($txtValueDate == ""){$txtValueDate = $_GET["txtValueDate"];}
$txtChkJourDtAmt	= $_POST["txtChkJourDtAmt"]; if ($txtChkJourDtAmt == ""){$txtChkJourDtAmt = $_GET["txtChkJourDtAmt"];}
$txtChkJourDtAmt1	= $_POST["txtChkJourDtAmt1"]; if ($txtChkJourDtAmt1 == ""){$txtChkJourDtAmt1 = $_GET["txtChkJourDtAmt1"];}
$txtChkJourDtAmt2	= $_POST["txtChkJourDtAmt2"]; if ($txtChkJourDtAmt2 == ""){$txtChkJourDtAmt2 = $_GET["txtChkJourDtAmt2"];}

$txtBillJourDtLedger= $_POST["txtBillJourDtLedger"]; if ($txtBillJourDtLedger == ""){$txtBillJourDtLedger = $_GET["txtBillJourDtLedger"];}
$txtCurrCode		= $_POST["txtCurrCode"]; if ($txtCurrCode == ""){$txtCurrCode = $_GET["txtCurrCode"];}
$txtBillJourDtType	= $_POST["txtBillJourDtType"]; if ($txtBillJourDtType == ""){$txtBillJourDtType = $_GET["txtBillJourDtType"];}
$txtBillNo			= $_POST["txtBillNo"]; if ($txtBillNo == ""){$txtBillNo = $_GET["txtBillNo"];}
$txtBank			= $_POST["txtBank"]; if ($txtBank == ""){$txtBank = $_GET["txtBank"];}
$txtValueDate		= $_POST["txtValueDate"]; if ($txtValueDate == ""){$txtValueDate = $_GET["txtValueDate"];}
$txtBillJourDtAmt	= $_POST["txtBillJourDtAmt"]; if ($txtBillJourDtAmt == ""){$txtBillJourDtAmt = $_GET["txtBillJourDtAmt"];}
$txtBillJourDtAmt1	= $_POST["txtBillJourDtAmt1"]; if ($txtBillJourDtAmt1 == ""){$txtBillJourDtAmt1 = $_GET["txtBillJourDtAmt1"];}
$txtBillJourDtAmt2	= $_POST["txtBillJourDtAmt2"]; if ($txtBillJourDtAmt2 == ""){$txtBillJourDtAmt2 = $_GET["txtBillJourDtAmt2"];}

$txtProjectCodeDt	= $_POST["txtProjectCodeDt"]; if ($txtProjectCodeDt == ""){$txtProjectCodeDt = $_GET["txtProjectCodeDt"];}
$txtCostCentCodeDt	= $_POST["txtCostCentCodeDt"]; if ($txtCostCentCodeDt == ""){$txtCostCentCodeDt = $_GET["txtCostCentCodeDt"];}
$txtCstJourDtPer	= $_POST["txtCstJourDtPer"]; if ($txtCstJourDtPer == ""){$txtCstJourDtPer = $_GET["txtCstJourDtPer"];}
$txtCstJourDtAmt	= $_POST["txtCstJourDtAmt"]; if ($txtCstJourDtAmt == ""){$txtCstJourDtAmt = $_GET["txtCstJourDtAmt"];}
$txtCstJourDtAmt1	= $_POST["txtCstJourDtAmt1"]; if ($txtCstJourDtAmt1 == ""){$txtCstJourDtAmt1 = $_GET["txtCstJourDtAmt1"];}
$txtCstJourDtAmt2	= $_POST["txtCstJourDtAmt2"]; if ($txtCstJourDtAmt2 == ""){$txtCstJourDtAmt2 = $_GET["txtCstJourDtAmt2"];}

$txtRatedt			= $_POST["txtRatedt"]; if ($txtRatedt == ""){$txtRatedt = $_GET["txtRatedt"];}

if ($mode == "checkjour"){
	$vRemark = $_GET['vRemark']; 
	$querysetup= " select count(*)  from trans where trans_remark = '$vRemark'  ";
	$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
	$rowsetup=mysql_fetch_array($resultsetup);
	$countchk = $rowsetup[0];
	
	if($countchk > 0){
		echo "[BRK]";
		echo $countchk;
		echo "[BRK]";
    }else{
		echo "[BRK]";
		echo 0;
		echo "[BRK]";
    } 
}
 
if ($mode == "submitrecord" || $mode == "submitrecord-ajax"){
	
	$ErrorExists = 0;
	
	if (!isset($PTransCurr))   $PTransCurr = $base1;
	   
	if (empty($PTransCashType))	$CashTypeCode = 'Null';
	else		$CashTypeCode = "'".$PTransCashType."'";	
	
	if($txtAdvancePayment == '') $txtAdvancePayment=0;
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PTransCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PTransCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
	
	
	//Check For Manual No To Be Unique
	if ($Module_UniqueManualNo == 1 && $PTransManualNo != "") {
		$sub_query = " Select Count(*) From ( Select Trans_ID From Trans Where Trans_Type = '".$PTransType."' and upper(Trans_ManualNo) = '".$PTransManualNo."' and Trans_Id != $STransId ".
					 "                 Union  Select Trans_ID From Temp_Trans Where Trans_Type = '".$PTransType."' and upper(Trans_ManualNo) = '".$PTransManualNo."' and Trans_Id != $STransId) Q1 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 1 ) {
			$ErrorExists = 1;
			$message = 'Manual No should be unique.';
		}	
	}	
	
	$PTransCostCentCode = "".$PTransCostCentCode;	
	if ($PTransCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PTransCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	$PTransProjectCode = "".$PTransProjectCode;
	if ($PTransProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PTransProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}	
	}
	if ($txtLedgerNo != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$txtLedgerNo."' and ifNull(Ledger_grpdet,0) = 0";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Ledger Number.';
		}	
	}
	
	//Insert Master Table
	if ($STransId == "" && $ErrorExists == 0){
	
			
				
		fbegin();	
		$vTransId = get_nextsequence('trans_id','',$connection);	
		fcommit();
		
		//$PTransRemark    = iconv('utf-8','windows-1256', $PTransRemark);
		//$PTransRepresent = iconv('utf-8','windows-1256', $PTransRepresent);
		
		fbegin();
		$query = " INSERT INTO temp_trans (Trans_ID, Trans_Reference, Trans_Date, Trans_SysDate, Trans_Remark, Trans_Type, Trans_Representative, ".
				 " Trans_ManualNo, Currency_Code, Trans_CashReference, CashType_code, Project_Code, Costcent_code, Trans_Posted, Journal_Id, ".
				 " Trans_AmountDb1, Trans_AmountDb2, Trans_Amountcd1, Trans_Amountcd2, Trans_BelongsToGroup, Synchronized, User_Account, Logged_Code,AdvancePayment ) ".
				 " VALUES ( ".GetSQLValueString($vTransId,'double').", Null, ".GetSQLValueString(insertMySQLDate($PTransDate),'date').", now(), ".
				 "          ".GetSQLValueString($PTransRemark,'text').", ".GetSQLValueString($PTransType,'text').", ".GetSQLValueString($PTransRepresent,'text').", ".
				 "          ".GetSQLValueString($PTransManualNo,'text').", ".GetSQLValueString($PTransCurr,'text').", Null, ".GetSQLValueString($PTransCashType,'text').", ".
				 "          ".GetSQLValueString($PTransProjectCode,'text').", ".GetSQLValueString($PTransCostCentCode,'text').", 0, Null, 0, 0, 0, 0,  ".
				 "          ".GetSQLValueString($FI_BelongsToGrp,'double').", 0, ".GetSQLValueString($_SESSION['useraccount'],'text').", ".
				 "          ".GetSQLValueString($_SESSION['useraccount'],'text').",$txtAdvancePayment )";
				 
			 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$STransId = $vTransId;
			fcommit();
		if($Module_InvoiceGrid == 2){
					$vMainCompanyName=explode('_',$_SESSION['dbName']);  
					$DirCompany  = $vMainCompanyName[0];
					preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
					$DirYear =  $DirYears[0][0];  
					
					$query_detailLink = "insert into ".$_SESSION['dbLabel'].".temp_detaillink(Detaillink_id,Detaillink_date, year, id, company, journal_type, ".
										" form_id, ledger_number, project_code, costcent_code, saleman_number, amount, amountbase1, ".
										" amountbase2,currency_code, remark, related_journalType,relation_id,reference,link_belongToGoup)".
										" select Detaillink_id,Detaillink_date, year, id, company, journal_type,".
										" form_id, ledger_number, project_code, costcent_code, saleman_number, amount, amountbase1,".
										" amountbase2,currency_code, remark, related_journalType,relation_id,reference,link_belongToGoup ".
										" from ".$_SESSION['dbLabel'].".detaillink as  detaillink ".
										" where if('$PTransType' = 'PV' or '$PTransType' = 'DV',related_journalType in ('PI','PR','JP','JV','OP'), ".
										" if( ('$PTransType' = 'RV' or '$PTransType' = 'CV') and $Module_Delivery = 0,related_journalType in ('DI','DR','JS','JV','OP','SO'),
										if( ('$PTransType' = 'RV' or '$PTransType' = 'CV') and $Module_Delivery = 1,related_journalType in ('SI','SR','JS','JV','OP','SO'),
										related_journalType = '')) )".	
										" And upper(company) = upper('".$DirCompany."') ".
										" And upper(year) = upper('".$DirYear."') "; 
					$res_detailLink = mysql_query($query_detailLink,$connection);
					// $message = $message."<br>".$query_headerLink; 
					//$message  =$message."<br>". mysql_error($connection); 	
				}
		}else{
			$STransId = "";
			$message  = mysql_error($connection); 
			frollback();
		}
	
	}
	
	//Insert Detail Tables
	if ($STransId != "" && $STransDtId == "" && $ErrorExists == 0){
	
		if (empty($txtTransDtAmount))	$txtTransDtAmount = 0;
		if (empty($txtTransDtAmountB1))	$txtTransDtAmountB1 = 0;
		if (empty($txtTransDtAmountB2))	$txtTransDtAmountB2 = 0;
			
			
		$vTransDtdbcd = '';
		$vLedgerNo    = '';
		$vDetailCode  = '';
		$vTransDtDesc = '';
		$vTransDtCurr = '';
		$vTransDtAmount    = 0;
		$vTransDtAmountB1  = 0;
		$vTransDtAmountB2  = 0;
		$vTransDtValueDate = '';
		$vTransDtManualNo  = '';
		$vTransDtCheckNo   = '';
		
		$vTransAmountDb1 = 0;
		$vTransAmountDb2 = 0;
		$vTransAmountcd1 = 0;
		$vTransAmountcd2 = 0;
			
			
		$vTransDtdbcd = $txtTransDtdbcd;
		$vLedgerNo    = $txtLedgerNo;
		$vTransDtDesc = $txtTransDtDesc;
		$vTransDtCurr = $txtTransDtCurr;
		$vTransDtAmount    = $txtTransDtAmount;
		$vTransDtAmountB1  = $txtTransDtAmountB1;
		$vTransDtAmountB2  = $txtTransDtAmountB2;
		$vTransDtValueDate = $txtTransDtValueDate;
		$vRatedt		   = $txtRatedt;
		$vTransDtCheckNo   = $txtTransDtCheckNo;
		
		if($vRatedt == '') $vRatedt = "NULL";
		
		if (empty($txtClientDtCode)) $vDetailCode = 'Null';
		else	$vDetailCode = "'".$txtClientDtCode."'";	
		
		if (empty($txtTransDtManualNo)) $vTransDtManualNo = 'Null';
		else	$vTransDtManualNo = "'".$txtTransDtManualNo."'";	
					
					
		//Check For Manual No To Be Unique
		if ($Module_UniqueManualNo == 1 && $txtTransDtManualNo != "") {
			$sub_query = " Select Count(*) From ( Select TransDt_ID From TransDt Inner Join Trans on TransDt.Trans_Id = Trans.Trans_Id ".
						 "                        Where Trans.Trans_Type = '".$PTransType."' and upper(TransDt.TransDt_ManualNo) = '".$txtTransDtManualNo."' and TransDt.TransDt_ID != $STransDtId ".
						 "                 Union  Select TransDt_ID From Temp_TransDt Inner Join Temp_Trans on Temp_TransDt.Trans_Id = Temp_Trans.Trans_Id ".
						 "                        Where Temp_Trans.Trans_Type = '".$PTransType."' and upper(Temp_TransDt.TransDt_ManualNo) = '".$txtTransDtManualNo."' and Temp_TransDt.TransDt_ID != $STransDtId) Q1 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] > 1 ) {
				$ErrorExists = 1;
				$message = 'Manual No should be unique.';
			}	
		}
					
			
		if ($ErrorExists == 0){
		
			fbegin();
			$vTransDtId = get_nextsequence('transdt_id','',$connection);	
			fcommit();
			$STransDtId=$vTransDtId;
			$vTransDtDesc = iconv('utf-8','windows-1256', $vTransDtDesc);
			
			fbegin();
			$query = " INSERT INTO temp_transdt (TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ". 
					 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, TransDt_ManualNo, Detail_Code, Synchronized,transdt_rate, ".
					 " User_Account, Logged_Code, transdt_checkNo )  ".
					 " VALUES ( ".$vTransDtId.", ".$STransId.", '".$vTransDtCurr."', '".insertMySQLDate($PTransDate)."', ".
					 "          '".$vLedgerNo."', '".ereg_replace("'", "\'", trim($vTransDtDesc))."', Null, '".insertMySQLDate($vTransDtValueDate)."' , ".
					 "          $vTransDtAmount, $vTransDtAmountB1, $vTransDtAmountB2, '".$vTransDtdbcd."', '+', $vTransDtManualNo, $vDetailCode, 0, $vRatedt, ".
					 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', '".$vTransDtCheckNo."'	) ";
				 
			//echo $query."<br>";exit;				
			$result=mysql_query($query,$connection);
			
			if ($result){
			
				if ($Module_Project == 1 || $Module_CostCenter == 1 || $Module_ProjectDt == 1 || $Module_CostCenterDt == 1) {
					$vCstJourDtPer   = 100;
					$vCstJourDtAmt   = $vTransDtAmount;
					$vCstJourDtAmt1  = $vTransDtAmountB1;
					$vCstJourDtAmt2  = $vTransDtAmountB2;
					
					if ($Ledger_ValidateProject == 1) {
						$sub_query = " Select Project_Code, CostCenter_code From Ledger Where Ledger_Number = '".$vLedgerNo."'";
						$sub_result = selectData($connection, $sub_query);
						
						if ($sub_result[0] != '') $PTransProjectCode = $sub_result[0];
						if ($sub_result[1] != '') $PTransCostCentCode = $sub_result[1];
					} 
					
					$vProjectCodeDt	 = GetSQLValueString($PTransProjectCode,'text');
					$vCostCentCodeDt = GetSQLValueString($PTransCostCentCode,'text');
					
					//Case Header Project or Costcenter Is Not Empty Automatically Insert Into CstjourDt	
					if ($PTransProjectCode != '' || $PTransCostCentCode != '' ) {
					
						$query = " INSERT INTO temp_cstjourdt (TransDt_Id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, CstJourDt_Amount1, CstJourDt_Amount2, ".
								 " Synchronized, User_Account, Logged_Code ) ". 
								 " VALUES ( ".$vTransDtId.", $vProjectCodeDt, $vCostCentCodeDt, $vCstJourDtPer, $vCstJourDtAmt, $vCstJourDtAmt1, $vCstJourDtAmt2, ".
								 "          0, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."'	) ";
						//$message = $query;		 
						//echo $query."<br>";exit;				
						$result=mysql_query($query,$connection);
					}
				}
				
				
				
				$sub_query = " Select Sum(if(TransDt_dbcd='D', ifNull(Transdt_Amount1,0), 0)) As TotalDebitAmount1, Sum(if(TransDt_dbcd='D', ifNull(Transdt_Amount2,0), 0)) As TotalDebitAmount2, ".
							 " Sum(if(TransDt_dbcd='C', ifNull(Transdt_Amount1,0), 0)) As TotalCreditAmount1, Sum(if(TransDt_dbcd='C', ifNull(Transdt_Amount2,0), 0)) As TotalCreditAmount2 ".
							 " From Temp_TransDt ".
							 " Where Trans_ID = ".$STransId;
				$sub_result = selectData($connection, $sub_query);
				
				$vTransAmountDb1 = $sub_result[0];
				$vTransAmountDb2 = $sub_result[1];
				$vTransAmountcd1 = $sub_result[2];
				$vTransAmountcd2 = $sub_result[3];
				
					 
				$sub_query1 = " UPDATE temp_trans SET ".
							  " Trans_AmountDb1 = $vTransAmountDb1, Trans_AmountDb2 = $vTransAmountDb2, ".
							  " Trans_Amountcd1 = $vTransAmountcd1, Trans_Amountcd2 = $vTransAmountcd2, ".
							  " Currency_Code = '".$PTransCurr."', Trans_Date = '".insertMySQLDate($PTransDate)."', ".
							  " Trans_Remark = '".ereg_replace("'", "\'", trim($PTransRemark))."', ".
							  " Trans_Representative = '".ereg_replace("'", "\'", trim($PTransRepresent))."',  ".
							  " Trans_ManualNo = '".ereg_replace("'", "\'", trim($PTransManualNo))."',  ".
							  " CashType_code = $CashTypeCode  ".
							  //" Project_Code = ".GetSQLValueString($PTransProjectCode,'text').", Costcent_code = ".GetSQLValueString($PTransCostCentCode,'text')." ".
							  " WHERE Trans_ID = ".$STransId;
					 
				$sub_result1=mysql_query($sub_query1,$connection);
				//echo $sub_query1."<br>";exit;

					
							 
				fcommit();
			} else{
				$message  = mysql_error($connection); 
				frollback();
			}	
		}
		
	} // End Case Insert In Detail Tables
	

} 
	
//Delete Detail Mode
else if ($mode == "deletedt" ){

	$AllowDelete = 0;
	$ErrorExists = 0;
	$message  = '';
	
	$vTransAmountDb1 = 0;
	$vTransAmountDb2 = 0;
	$vTransAmountcd1 = 0;
	$vTransAmountcd2 = 0;
	
	$sub_query = " Select Journal_Id From Trans Where Trans_id = ".$STransId;
	$sub_result = selectData($connection, $sub_query);
	$vTransJournalID = $sub_result[0];
	if(empty($vTransJournalID)) $vTransJournalID = -1;
	
	if ($AllowDelete == 0) {
		//Check Each JournalDt If Has Related Checks Used
		$query = " Select Count(*) ".
				 " From Checks Inner Join JournalDt on Checks.Journaldt_Id1 = JournalDt.JournalDt_Id ".
				 " Inner Join ChkJourDt on Checks.Chk_Number = ChkJourDt.Chk_Number and Checks.Ledger_Number = ChkJourDt.Ledger_Number  ".
				 " Where JournalDt.Journal_Id = '".$vTransJournalID."' ".
				 " And ChkJourDt.TransDt_Id In (Select TransDt_Id From TransDt where Trans_Id = '".$STransId."') ".
				 " And (ifNull(Checks.Journaldt_id2,0) != 0 and Checks.Journaldt_id2 != '') ";

		$result = selectData($connection, $query);
		$ChecksExists = $result[0];
		
		if ($ChecksExists > 0 ){
			$message  = 'Delete not allowed, Cheques been used.';
			$AllowDelete = 1;
		}
	}	
	
	if ($AllowDelete == 0) {
		//Check Each JournalDt If Has Related Checks Used
		$query = " Select Count(*) ".
				 " From Bills Inner Join JournalDt on Bills.Journaldt_Id1 = JournalDt.JournalDt_Id ".
				 " Inner Join BillJourDt on Bills.Bill_Number = BillJourDt.Bill_Number and Bills.Ledger_Number = BillJourDt.Ledger_Number  ".
				 " Where JournalDt.Journal_Id = '".$vTransJournalID."' ".
				 " And BillJourDt.TransDt_Id In (Select TransDt_Id From TransDt where Trans_Id = '".$STransId."') ".
				 " And (ifNull(Bills.Journaldt_id2,0) != 0 and Bills.Journaldt_id2 != '') ";

		$result = selectData($connection, $query);
		$BillsExists = $result[0];
			
		if ($BillsExists > 0 ){
			$message  = 'Delete not allowed, Bills been used.';
			$AllowDelete = 1;
		}
	}
	
	if ($AllowDelete == 0) {

		
		fbegin();
		
		// Delete From TempCstJourDt For Selected Record
		$query = " DELETE FROM Temp_CstJourDt ".
				 " WHERE TransDt_id In (Select TransDt_Id From temp_TransDt where Trans_Id = '".$STransId."');";
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$AllowDelete = 1;
			frollback();
		}  
		else {
			fcommit();
		}
			
	
	}
	 
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {
		  
		fbegin();
		
		// Delete From TempTransDt For Selected Record
		$query = " DELETE FROM Temp_TransDt ".
				 " WHERE TransDt_id = ".$STransDtId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
			
			
	
			
		if ( $ErrorExists == 0 ){ 
			
			$sub_query = " Select ifNull(Sum(if(TransDt_dbcd='D', ifNull(Transdt_Amount1,0), 0)),0) As TotalDebitAmount1, ifNull(Sum(if(TransDt_dbcd='D', ifNull(Transdt_Amount2,0), 0)),0) As TotalDebitAmount2, ".
						 " ifNull(Sum(if(TransDt_dbcd='C', ifNull(Transdt_Amount1,0), 0)),0) As TotalCreditAmount1, ifNull(Sum(if(TransDt_dbcd='C', ifNull(Transdt_Amount2,0), 0)),0) As TotalCreditAmount2 ".
						 " From Temp_TransDt ".
						 " Where Trans_ID = ".$STransId;
			$sub_result = selectData($connection, $sub_query);
			
			$vTransAmountDb1 = $sub_result[0];
			$vTransAmountDb2 = $sub_result[1];
			$vTransAmountcd1 = $sub_result[2];
			$vTransAmountcd2 = $sub_result[3];
			
			if(empty($vTransAmountDb1)) $vTransAmountDb1 = 0;
			if(empty($vTransAmountDb2)) $vTransAmountDb2 = 0;
			if(empty($vTransAmountcd1)) $vTransAmountcd1 = 0;
			if(empty($vTransAmountcd2)) $vTransAmountcd2 = 0;
			
			fbegin();
			$sub_query1 = " UPDATE temp_trans SET ".
						  " Trans_AmountDb1 = $vTransAmountDb1, Trans_AmountDb2 = $vTransAmountDb2, ".
						  " Trans_Amountcd1 = $vTransAmountcd1, Trans_Amountcd2 = $vTransAmountcd2 ".
						  " WHERE Trans_ID = ".$STransId;
				 
			$sub_result1=mysql_query($sub_query1,$connection);
			//echo $sub_query1."<br>";exit;
				
			if ( $sub_result1 ){ 
				fcommit();
			} else
			{
			   $message  = mysql_error($connection); 
			   frollback();
			} 
		} // End If No Error Exists 
			
			
	
	} // End If No Constraints Found On Delete
	
	
}

//Edit Detail Tables
else if (($mode == "editdt" || $mode == "editdt-ajax") && $STransId != "" && $STransDtId != ""){

	if (empty($txtTransDtAmount))
		$txtTransDtAmount = 0;
	if (empty($txtTransDtAmountB1))
		$txtTransDtAmountB1 = 0;
	if (empty($txtTransDtAmountB2))
		$txtTransDtAmountB2 = 0;
			
			
	$vTransDtdbcd = '';
	$vLedgerNo    = '';
	$vDetailCode  = '';
	$vTransDtDesc = '';
	$vTransDtCurr = '';
	$vTransDtAmount    = 0;
	$vTransDtAmountB1  = 0;
	$vTransDtAmountB2  = 0;
	$vTransDtValueDate = '';
	$vTransDtManualNo  = '';
	$vTransDtCheckNo   = '';
		
	$vTransAmountDb1 = 0;
	$vTransAmountDb2 = 0;
	$vTransAmountcd1 = 0;
	$vTransAmountcd2 = 0;
	
	$ErrorExists = 0;
					
	$vTransDtdbcd = $txtTransDtdbcd;
	$vLedgerNo    = $txtLedgerNo;
	$vTransDtDesc = $txtTransDtDesc;
	//$vTransDtDesc1 = $txtTransDtDesc1;
	$vTransDtCurr = $txtTransDtCurr;
	$vTransDtAmount    = $txtTransDtAmount;
	$vTransDtAmountB1  = $txtTransDtAmountB1;
	$vTransDtAmountB2  = $txtTransDtAmountB2;
	$vTransDtValueDate = $txtTransDtValueDate;
	$vTransDtCheckNo   = $txtTransDtCheckNo;
	
	$vRatedt		   = $txtRatedt;
	if($vRatedt == '') $vRatedt = "NULL";
	
	if (empty($txtClientDtCode)) $vDetailCode = 'Null';
	else	$vDetailCode = "'".$txtClientDtCode."'";	

	if (empty($txtTransDtManualNo)) $vTransDtManualNo = 'Null';
	else	$vTransDtManualNo = "'".$txtTransDtManualNo."'";
	
	//Check For Manual No To Be Unique
	if ($Module_UniqueManualNo == 1 && $txtTransDtManualNo != "") {
		$sub_query = " Select Count(*) From ( Select TransDt_ID From TransDt Inner Join Trans on TransDt.Trans_Id = Trans.Trans_Id ".
					 "                        Where Trans.Trans_Type = '".$PTransType."' and upper(TransDt.TransDt_ManualNo) = '".$txtTransDtManualNo."' and TransDt.TransDt_ID != $STransDtId ".
					 "                 Union  Select TransDt_ID From Temp_TransDt Inner Join Temp_Trans on Temp_TransDt.Trans_Id = Temp_Trans.Trans_Id ".
					 "                        Where Temp_Trans.Trans_Type = '".$PTransType."' and upper(Temp_TransDt.TransDt_ManualNo) = '".$txtTransDtManualNo."' and Temp_TransDt.TransDt_ID != $STransDtId) Q1 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 1 ) {
			$ErrorExists = 1;
			$message = 'Manual No should be unique.';
		}	
	}
					
			
	if ($ErrorExists == 0){
	
		$vTransDtDesc = iconv('utf-8','windows-1256', $vTransDtDesc);
		//$vTransDtDesc1 = iconv('utf-8','windows-1256', $vTransDtDesc1); 	
		fbegin();
		$query = " UPDATE temp_transdt SET ".
				 " Currency_Code = '".$vTransDtCurr."', Ledger_number = '".$vLedgerNo."', TransDt_Description = '".ereg_replace("'", "\'", trim($vTransDtDesc))."', ". 
				 " TransDt_ValueDate = '".insertMySQLDate($vTransDtValueDate)."', Transdt_Amount = $vTransDtAmount, Transdt_Amount1 = $vTransDtAmountB1, Transdt_Amount2 = $vTransDtAmountB2,  ".
				 " Detail_Code = $vDetailCode, TransDt_ManualNo = $vTransDtManualNo, transdt_rate = $vRatedt, ".//, TransDt_Description2 =  '".ereg_replace("'", "\'", trim($vTransDtDesc1))."' ".
				 " transdt_checkNo = '".$vTransDtCheckNo."' ".
				 " WHERE TransDt_ID = '".$STransDtId."'";

	//	echo $query."<br>";exit;		

		$result=mysql_query($query,$connection);
			
		if ($result){
			$sub_query = " Select Sum(if(TransDt_dbcd='D', ifNull(Transdt_Amount1,0), 0)) As TotalDebitAmount1, Sum(if(TransDt_dbcd='D', ifNull(Transdt_Amount2,0), 0)) As TotalDebitAmount2, ".
						 " Sum(if(TransDt_dbcd='C', ifNull(Transdt_Amount1,0), 0)) As TotalCreditAmount1, Sum(if(TransDt_dbcd='C', ifNull(Transdt_Amount2,0), 0)) As TotalCreditAmount2 ".
						 " From Temp_TransDt ".
						 " Where Trans_ID = ".$STransId;
			$sub_result = selectData($connection, $sub_query);
				
			$vTransAmountDb1 = $sub_result[0];
			$vTransAmountDb2 = $sub_result[1];
			$vTransAmountcd1 = $sub_result[2];
			$vTransAmountcd2 = $sub_result[3];
				
			$sub_query1 = " UPDATE temp_trans SET ".
						  " Trans_AmountDb1 = $vTransAmountDb1, Trans_AmountDb2 = $vTransAmountDb2, ".
						  " Trans_Amountcd1 = $vTransAmountcd1, Trans_Amountcd2 = $vTransAmountcd2 ".
						  " WHERE Trans_ID = ".$STransId;
					 
			$sub_result1=mysql_query($sub_query1,$connection);
			//echo $sub_query1."<br>";exit;
			
			$sub_query2 = " UPDATE temp_cstjourdt SET ".
						  " CstJourDt_Amount  = ((ifNull(CstjourDt_Per,0) * $vTransDtAmount)/100), ".
						  " CstJourDt_Amount1 = ((ifNull(CstjourDt_Per,0) * $vTransDtAmountB1)/100), ".
						  " CstJourDt_Amount2 = ((ifNull(CstjourDt_Per,0) * $vTransDtAmountB2)/100) ".
						  " WHERE TransDt_ID = '".$STransDtId."'";
					 
			$sub_result2=mysql_query($sub_query2,$connection);
			//echo $sub_query2."<br>";exit;

			
				
			fcommit();
		} else{
			$message  = mysql_error(); 
			frollback();
		}
	}
	
} 

else if ($mode == "insertcstjour" && $STransId != "" && $STransDtId != ""){
	
	$vCstJourDtId     = '';
	$vCostCentCodeDt  = '';
	$vProjectCodeDt   = '';
	$vCstJourDtPer    = 0;
	$vCstJourDtAmt    = 0;
	$vCstJourDtAmt1   = 0;
	$vCstJourDtAmt2   = 0;
	
	   
	$txtCostCentCodeDt = "".$txtCostCentCodeDt;   
	if ($txtCostCentCodeDt == '')
		$vCostCentCodeDt = 'Null';
	else
		$vCostCentCodeDt = "'".$txtCostCentCodeDt."'";
			
	$txtProjectCodeDt = "".$txtProjectCodeDt;	
	if ($txtProjectCodeDt == '')
		$vProjectCodeDt = 'Null';
	else
		$vProjectCodeDt = "'".$txtProjectCodeDt."'";   

	
	if (empty($txtCstJourDtPer))
		$txtCstJourDtPer = 0;
	if (empty($txtCstJourDtAmt))
		$txtCstJourDtAmt = 0;
	if (empty($txtCstJourDtAmt1))
		$txtCstJourDtAmt1 = 0;
	if (empty($txtCstJourDtAmt2))
		$txtCstJourDtAmt2 = 0;
			
			
	
	
	$vCstJourDtPer   = $txtCstJourDtPer;
	$vCstJourDtAmt   = $txtCstJourDtAmt;
	$vCstJourDtAmt1  = $txtCstJourDtAmt1;
	$vCstJourDtAmt2  = $txtCstJourDtAmt2;	
		
			
	if($txtCostCentCodeDt != '' || $txtProjectCodeDt != ''){
	fbegin();
	$query = " INSERT INTO temp_cstjourdt (TransDt_Id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, CstJourDt_Amount1, CstJourDt_Amount2, ".
			 " Synchronized, User_Account, Logged_Code ) ". 
			 " VALUES ( ".$STransDtId.", $vProjectCodeDt, $vCostCentCodeDt, $vCstJourDtPer, $vCstJourDtAmt, $vCstJourDtAmt1, $vCstJourDtAmt2, ".
			 "          0, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."'	) ";
			 
	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
		
	if ($result){
		fcommit();
	} else{
		$message  = mysql_error($connection); 
		frollback();
	}	
	
	}

} 


//Delete CstJourDt
else if ($mode == "deletecstjour" && $SCstJourDtId != ""){

	$AllowDelete = 0;
	$ErrorExists = 0;
	$message  = '';
	
	
		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {

		
		fbegin();
		
		// Delete From TempCstJourDt For Selected Record
		$query = " DELETE FROM Temp_CstJourDt ".
				 " WHERE CstJourDt_id = '".$SCstJourDtId."'";
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
			
	
	} // End If No Constraints Found On Delete
	
	
}

//Edit CstJoutDt Table
else if ($mode == "editcstjour" && $SCstJourDtId != ""){

	$vCstJourDtId     = '';
	$vCostCentCodeDt  = '';
	$vProjectCodeDt   = '';
	$vCstJourDtPer    = 0;
	$vCstJourDtAmt    = 0;
	$vCstJourDtAmt1   = 0;
	$vCstJourDtAmt2   = 0;
	
	   
	$txtCostCentCodeDt = "".$txtCostCentCodeDt;   
	if ($txtCostCentCodeDt == '')
		$vCostCentCodeDt = 'Null';
	else
		$vCostCentCodeDt = "'".$txtCostCentCodeDt."'";
			
	$txtProjectCodeDt = "".$txtProjectCodeDt;	
	if ($txtProjectCodeDt == '')
		$vProjectCodeDt = 'Null';
	else
		$vProjectCodeDt = "'".$txtProjectCodeDt."'";   

	
	if (empty($txtCstJourDtPer))
		$txtCstJourDtPer = 0;
	if (empty($txtCstJourDtAmt))
		$txtCstJourDtAmt = 0;
	if (empty($txtCstJourDtAmt1))
		$txtCstJourDtAmt1 = 0;
	if (empty($txtCstJourDtAmt2))
		$txtCstJourDtAmt2 = 0;
			
			
	
	
	$vCstJourDtPer   = $txtCstJourDtPer;
	$vCstJourDtAmt   = $txtCstJourDtAmt;
	$vCstJourDtAmt1  = $txtCstJourDtAmt1;
	$vCstJourDtAmt2  = $txtCstJourDtAmt2;	

					
			
	fbegin();
	$query = " UPDATE temp_cstjourdt SET ".
			 " Project_code = $vProjectCodeDt, Costcenter_Code = $vCostCentCodeDt, CstjourDt_Per = $vCstJourDtPer, ". 
			 " CstJourDt_Amount = $vCstJourDtAmt, CstJourDt_Amount1 = $vCstJourDtAmt1, CstJourDt_Amount2 = $vCstJourDtAmt2  ".
			 " WHERE CstJourDt_ID = '".$SCstJourDtId."'";

	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
		
	if ($result){
		
		fcommit();
	} else{
		$message  = mysql_error($connection); 
		frollback();
	}

	
} 


// Insert ChkJourDt
else if ($mode == "insertchkjour" && $STransId != "" && $STransDtId != ""){
	
	$vChkJourDtId = '';
	$vCheckNo     = '';
	$vBank        = '';
	$vValueDate   = '';
	$vCurrCode    = '';
	$vChkJourDtLedger = '';
	$vChkJourDtType   = '';
	$vChkJourDtAmt    = 0;
	$vChkJourDtAmt1   = 0;
	$vChkJourDtAmt2   = 0;
	
	$vCheckExists = 0;
	


	if (empty($txtChkJourDtAmt))
		$txtChkJourDtAmt = 0;
	if (empty($txtChkJourDtAmt1))
		$txtChkJourDtAmt1 = 0;
	if (empty($txtChkJourDtAmt2))
		$txtChkJourDtAmt2 = 0;
			
			

	$vCheckNo     = $txtCheckNo;
	$vBank        = $txtBank;
	$vValueDate   = $txtValueDate;
	$vCurrCode    = $txtCurrCode;
	$vChkJourDtLedger = $txtChkJourDtLedger;
	$vChkJourDtType   = $txtChkJourDtType;
	$vChkJourDtAmt    = $txtChkJourDtAmt;
	$vChkJourDtAmt1   = $txtChkJourDtAmt1;
	$vChkJourDtAmt2   = $txtChkJourDtAmt2;	
		
	
	if ($vChkJourDtType == 'A') {
		$sub_query=" select count(*) from checks ".
				   " where ledger_number = '".$vChkJourDtLedger."' ". 
				   " and chk_number = '".$vCheckNo."' ";
				   
		//echo $sub_query;exit;
		$sub_result = selectData($connection, $sub_query);
		$vCheckExists = $sub_result[0];
	}
	
	if ($vChkJourDtType == 'A' && $vCheckExists == 0) {
		$sub_query= " select count(*) from temp_chkjourdt ".
		            " where ledger_number = '".$vChkJourDtLedger."' ". 
					" and chk_number = '".$vCheckNo."'";
					
		//echo $sub_query;exit;
		$sub_result = selectData($connection, $sub_query);
		$vCheckExists = $sub_result[0];
	}
	

	//if ($vCheckExists == 0)
	{	
		fbegin();
		$query = " INSERT INTO temp_chkjourdt (TransDt_Id, Chk_number, Chk_bank, Chk_ValueDate, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2, ".
				 " Ledger_Number, Chk_Type, Synchronized, User_Account, Logged_Code ) ". 
				 " VALUES ( ".$STransDtId.", '".ereg_replace("'", "\'", trim($vCheckNo))."', '".ereg_replace("'", "\'", trim($vBank))."', '".insertMySQLDate($vValueDate)."', ".
				 "          '".$vCurrCode."', $vChkJourDtAmt, $vChkJourDtAmt1, $vChkJourDtAmt2, '".$vChkJourDtLedger."', '".$vChkJourDtType."', 0, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."'	) ";
				 
		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ($result){
			fcommit();
		} else{
			$message  = mysql_error(); 
			frollback();
		}	
	} /*else
		$message  = 'Insert not allowed. Check No. already exists.'; */
	

} 

//Edit ChkJoutDt Table
else if ($mode == "editchkjour" && $SChkJourDtId != ""){

	$vChkJourDtId = '';
	$vCheckNo     = '';
	$vBank        = '';
	$vValueDate   = '';
	$vCurrCode    = '';
	$vChkJourDtLedger = '';
	$vChkJourDtType   = '';
	$vChkJourDtAmt    = 0;
	$vChkJourDtAmt1   = 0;
	$vChkJourDtAmt2   = 0;
	


	if (empty($txtChkJourDtAmt))
		$txtChkJourDtAmt = 0;
	if (empty($txtChkJourDtAmt1))
		$txtChkJourDtAmt1 = 0;
	if (empty($txtChkJourDtAmt2))
		$txtChkJourDtAmt2 = 0;
			
			

	$vCheckNo     = $txtCheckNo;
	$vBank        = $txtBank;
	$vValueDate   = $txtValueDate;
	$vCurrCode    = $txtCurrCode;
	$vChkJourDtLedger = $txtChkJourDtLedger;
	$vChkJourDtType   = $txtChkJourDtType;
	$vChkJourDtAmt    = $txtChkJourDtAmt;
	$vChkJourDtAmt1   = $txtChkJourDtAmt1;
	$vChkJourDtAmt2   = $txtChkJourDtAmt2;	
			
			
	fbegin();
	$query = " UPDATE temp_chkjourdt SET ".
			 " Chk_bank = '".ereg_replace("'", "\'", trim($vBank))."', Chk_ValueDate = '".insertMySQLDate($vValueDate)."', ". 
			 " Chk_Amount = $vChkJourDtAmt, Chk_Amount1 = $vChkJourDtAmt1, Chk_Amount2 = $vChkJourDtAmt2  ".
			 " WHERE ChkJourDt_ID = '".$SChkJourDtId."'";

	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
		
	if ($result){
		
		fcommit();
	} else{
		$message  = mysql_error(); 
		frollback();
	}

	
} 
//Delete ChkJourDt
else if ($mode == "deletechkjour" && $SChkJourDtId != ""){

	$AllowDelete = 0;
	$ErrorExists = 0;
	$message  = '';
	
	
		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {

		
		fbegin();
		
		// Delete From TempChkJourDt For Selected Record
		$query = " DELETE FROM Temp_ChkJourDt ".
				 " WHERE ChkJourDt_id = '".$SChkJourDtId."'";
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
			
	
	} // End If No Constraints Found On Delete
	
	
}


// Insert BillJourDt
else if ($mode == "insertbilljour" && $STransId != "" && $STransDtId != ""){
	
	$vBillJourDtId = '';
	$vBillNo      = '';
	$vBank        = '';
	$vValueDate   = '';
	$vCurrCode    = '';
	$vBillJourDtLedger = '';
	$vBillJourDtType   = '';
	$vBillJourDtAmt    = 0;
	$vBillJourDtAmt1   = 0;
	$vBillJourDtAmt2   = 0;
	
	$vBillExists = 0;
	


	if (empty($txtBillJourDtAmt))
		$txtBillJourDtAmt = 0;
	if (empty($txtBillJourDtAmt1))
		$txtBillJourDtAmt1 = 0;
	if (empty($txtBillJourDtAmt2))
		$txtBillJourDtAmt2 = 0;
			
			

	$vBillNo      = $txtBillNo;
	$vBank        = $txtBank;
	$vValueDate   = $txtValueDate;
	$vCurrCode    = $txtCurrCode;
	$vBillJourDtLedger = $txtBillJourDtLedger;
	$vBillJourDtType   = $txtBillJourDtType;
	$vBillJourDtAmt    = $txtBillJourDtAmt;
	$vBillJourDtAmt1   = $txtBillJourDtAmt1;
	$vBillJourDtAmt2   = $txtBillJourDtAmt2;	
		
	
	if ($vBillJourDtType == 'A') {
		$sub_query=" select count(*) from bills ".
				   " where ledger_number = '".$vBillJourDtLedger."' ". 
				   " and bill_number = '".$vBillNo."' ";
				   
		//echo $sub_query;exit;
		$sub_result = selectData($connection, $sub_query);
		$vBillExists = $sub_result[0];
	}
	
	if ($vBillExists == 0) {
		$sub_query= " select count(*) from temp_billjourdt ".
		            " where ledger_number = '".$vBillJourDtLedger."' ". 
					" and Bill_number = '".$vBillNo."'";
					
		//echo $sub_query;exit;
		$sub_result = selectData($connection, $sub_query);
		$vBillExists = $sub_result[0];
	}
	

	if ($vBillExists == 0) {	
		fbegin();
		$query = " INSERT INTO temp_billjourdt (TransDt_Id, Bill_number, Bill_bank, Bill_ValueDate, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2, ".
				 " Ledger_Number, Bill_Type, Synchronized, Logged_Code ) ". 
				 " VALUES ( ".$STransDtId.", '".ereg_replace("'", "\'", trim($vBillNo))."', '".ereg_replace("'", "\'", trim($vBank))."', '".insertMySQLDate($vValueDate)."', ".
				 "          '".$vCurrCode."', $vBillJourDtAmt, $vBillJourDtAmt1, $vBillJourDtAmt2, '".$vBillJourDtLedger."', '".$vBillJourDtType."', 0, '".$_SESSION['useraccount']."'	) ";
				 
		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ($result){
			fcommit();
		} else{
			$message  = mysql_error(); 
			frollback();
		}	
	} else
		$message  = 'Insert not allowed. Bill No. already exists.'; 
	

} 

//Edit BillJoutDt Table
else if ($mode == "editbilljour" && $SBillJourDtId != ""){

	$vBillJourDtId = '';
	$vBillNo       = '';
	$vBank         = '';
	$vValueDate    = '';
	$vCurrCode     = '';
	$vBillJourDtLedger = '';
	$vBillJourDtType   = '';
	$vBillJourDtAmt    = 0;
	$vBillJourDtAmt1   = 0;
	$vBillJourDtAmt2   = 0;
	


	if (empty($txtBillJourDtAmt))
		$txtBillJourDtAmt = 0;
	if (empty($txtBillJourDtAmt1))
		$txtBillJourDtAmt1 = 0;
	if (empty($txtBillJourDtAmt2))
		$txtBillJourDtAmt2 = 0;
			
			

	$vBillNo      = $txtBillNo;
	$vBank        = $txtBank;
	$vValueDate   = $txtValueDate;
	$vCurrCode    = $txtCurrCode;
	$vBillJourDtLedger = $txtBillJourDtLedger;
	$vBillJourDtType   = $txtBillJourDtType;
	$vBillJourDtAmt    = $txtBillJourDtAmt;
	$vBillJourDtAmt1   = $txtBillJourDtAmt1;
	$vBillJourDtAmt2   = $txtBillJourDtAmt2;	
			
			
	fbegin();
	$query = " UPDATE temp_billjourdt SET ".
			 " Bill_bank = '".ereg_replace("'", "\'", trim($vBank))."', Bill_ValueDate = '".insertMySQLDate($vValueDate)."', ". 
			 " Bill_Amount = $vBillJourDtAmt, Bill_Amount1 = $vBillJourDtAmt1, Bill_Amount2 = $vBillJourDtAmt2  ".
			 " WHERE BillJourDt_ID = '".$SBillJourDtId."'";

	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
		
	if ($result){
		
		fcommit();
	} else{
		$message  = mysql_error(); 
		frollback();
	}

	
} 
//Delete BillJourDt
else if ($mode == "deletebilljour" && $SBillJourDtId != ""){

	$AllowDelete = 0;
	$ErrorExists = 0;
	$message  = '';
	
	
		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {

		
		fbegin();
		
		// Delete From TempBillJourDt For Selected Record
		$query = " DELETE FROM Temp_BillJourDt ".
				 " WHERE BillJourDt_id = '".$SBillJourDtId."'";
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
			
	
	} // End If No Constraints Found On Delete
	
	
}
// Insert AccLink
else if ($mode == "insertinvoice" && $STransId != "" && $STransDtId != ""){
	
	$vLinkRef      = '';
	$vLinkType     = '';
	$vJournalType  = '';
	$vSaleNetTotal         = 0;
	$vSaleNetTotalBase1    = 0;
	$vSaleNetTotalBase2    = 0;
	$vSalePaidAmnt         = 0;
	$vSalePaidAmntBase1    = 0;
	$vSalePaidAmntBase2    = 0;
	$vSaleRemainAmnt       = 0;
	$vSaleRemainAmntBase1  = 0;
	$vSaleRemainAmntBase2  = 0;
	
	
	if (empty($txtAccLinkNetTotAmt))   $txtAccLinkNetTotAmt = 0;
	if (empty($txtAccLinkNetTotAmt1))  $txtAccLinkNetTotAmt1 = 0;
	if (empty($txtAccLinkNetTotAmt2))  $txtAccLinkNetTotAmt2 = 0;
	if (empty($txtAccLinkPaidAmt))	   $txtAccLinkPaidAmt = 0;
	if (empty($txtAccLinkPaidAmt1))	   $txtAccLinkPaidAmt1 = 0;
	if (empty($txtAccLinkPaidAmt2))	   $txtAccLinkPaidAmt2 = 0;
	if (empty($txtAccLinkRemainAmt))   $txtAccLinkRemainAmt = 0;
	if (empty($txtAccLinkRemainAmt1))  $txtAccLinkRemainAmt1 = 0;
	if (empty($txtAccLinkRemainAmt2))  $txtAccLinkRemainAmt2 = 0;
			
	$vLinkID       = $txtLinkID;
	$vLinkRef      = $txtLinkRef;
	$vLinkType     = $txtLinkType;
	$vJournalType  = $TransType;
	$vSaleNetTotal         = $txtAccLinkNetTotAmt;
	$vSaleNetTotalBase1    = $txtAccLinkNetTotAmt1;
	$vSaleNetTotalBase2    = $txtAccLinkNetTotAmt2;
	$vSalePaidAmnt         = $txtAccLinkPaidAmt;
	$vSalePaidAmntBase1    = $txtAccLinkPaidAmt1;
	$vSalePaidAmntBase2    = $txtAccLinkPaidAmt2;
	$vSaleRemainAmnt       = $txtAccLinkRemainAmt;
	$vSaleRemainAmntBase1  = $txtAccLinkRemainAmt1;
	$vSaleRemainAmntBase2  = $txtAccLinkRemainAmt2;	

	$sub_query1 = " Select TransDt.Trans_Reference, TransDt.Trans_Date, TransDt.TransDt_ValueDate, TransDt.TransDt_Description ".
				  " From Temp_TransDt As TransDt ".
				  " Inner Join Temp_Trans As Trans on Trans.Trans_Id = TransDt.Trans_Id ".	
				  " Where TransDt.TransDt_ID = '".$STransDtId."' ";
	//echo $sub_query1;
	$sub_result1 = selectData($connection, $sub_query1);
		
	$vTransRef       = $sub_result1[0];
	$vTransDate      = $sub_result1[1];	
	$vTransValueDate = $sub_result1[2];	
	$vTransDesc      = $sub_result1[3];	
	
	fbegin();
	$query = " INSERT INTO ".$_SESSION['dbLabel'].".Temp_AccLink (Journal_Id, Link_ID, Link_Ref,Link_Type, Journal_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_PaidAmnt, Sale_PaidAmntbase1, Sale_PaidAmntbase2, ".
			 " Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, Trans_Date, Trans_ValueDate, Trans_Description, CompanyName, DirYear, Link_DirYear, User_Account ) ".
			 " VALUES ( ".$STransDtId.", '".$vLinkID."', '".ereg_replace("'", "\'", trim($vLinkRef))."', '".$vLinkType."', '".$vJournalType."', $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, ".
			 "          $vSalePaidAmnt, $vSalePaidAmntBase1, $vSalePaidAmntBase2, $vSaleRemainAmnt, $vSaleRemainAmntBase1, $vSaleRemainAmntBase2, $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, ".
			 "          ".$STransDtId.", '".$vTransRef."', '".$vTransDate."', '".$vTransValueDate."', '".$vTransDesc."', '".$DirCompany."', '".$DirYear."', '".$DirYear."', '".$_SESSION['useraccount']."') ";
				 
	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
			
	if ($result){
		fcommit();
	} else{
		$message  = mysql_error(); 
		frollback();
	}	

} 

//Edit AccLink Table
else if ($mode == "editinvoice" && $SAccLinkId != ""){

	$vLinkRef      = '';
	$vLinkType     = '';
	$vJournalType  = '';
	$vSaleNetTotal         = 0;
	$vSaleNetTotalBase1    = 0;
	$vSaleNetTotalBase2    = 0;
	$vSaleNetToPay         = 0;
	$vSaleNetToPayBase1    = 0;
	$vSaleNetToPayBase2    = 0;
	$vSalePaidAmnt         = 0;
	$vSalePaidAmntBase1    = 0;
	$vSalePaidAmntBase2    = 0;
	$vSaleRemainAmnt       = 0;
	$vSaleRemainAmntBase1  = 0;
	$vSaleRemainAmntBase2  = 0;
	
	
	if (empty($txtAccLinkNetTotAmt))   $txtAccLinkNetTotAmt  = 0;
	if (empty($txtAccLinkNetTotAmt1))  $txtAccLinkNetTotAmt1 = 0;
	if (empty($txtAccLinkNetTotAmt2))  $txtAccLinkNetTotAmt2 = 0;
	if (empty($txtAccLinkNetToPay))    $txtAccLinkNetToPay  = 0;
	if (empty($txtAccLinkNetToPay1))   $txtAccLinkNetToPay1 = 0;
	if (empty($txtAccLinkNetToPay2))   $txtAccLinkNetToPay2 = 0;
	if (empty($txtAccLinkPaidAmt))	   $txtAccLinkPaidAmt  = 0;
	if (empty($txtAccLinkPaidAmt1))	   $txtAccLinkPaidAmt1 = 0;
	if (empty($txtAccLinkPaidAmt2))	   $txtAccLinkPaidAmt2 = 0;
	if (empty($txtAccLinkRemainAmt))   $txtAccLinkRemainAmt  = 0;
	if (empty($txtAccLinkRemainAmt1))  $txtAccLinkRemainAmt1 = 0;
	if (empty($txtAccLinkRemainAmt2))  $txtAccLinkRemainAmt2 = 0;
	if (empty($txtAccLinkPaidAmt_D))   $txtAccLinkPaidAmt_D  = 0;
	if (empty($txtAccLinkRemainAmt_D)) $txtAccLinkRemainAmt_D  = 0;
	
	$sub_query1 = " Select TransDt.TransDt_ID, TransDt.Currency_Code, TransDt.Trans_Date ".
				  " From Temp_TransDt As TransDt ".
				  " Where TransDt.TransDt_ID = '".$STransDtId."' ";
							  
	//echo $sub_query1;
	$sub_result1 = selectData($connection, $sub_query1);
		
	$vAccLinkCurr     = $sub_result1[1];
	$vAccLinkDate     = $sub_result1[2];
			
	$vLinkID       = $txtLinkID;
	$vLinkRef      = $txtLinkRef;
	$vLinkType     = $txtLinkType;
	$vJournalType  = $TransType;
	$vSaleNetTotal         = $txtAccLinkNetTotAmt;
	$vSaleNetTotalBase1    = $txtAccLinkNetTotAmt1;
	$vSaleNetTotalBase2    = $txtAccLinkNetTotAmt2;
	$vSaleNetToPay         = $txtAccLinkNetToPay;
	$vSaleNetToPayBase1    = $txtAccLinkNetToPay1;
	$vSaleNetToPayBase2    = $txtAccLinkNetToPay2;
	$vSalePaidAmnt         = $txtAccLinkPaidAmt_D;
	$vSalePaidAmntBase1    = ConvertCurrency($vAccLinkCurr, $base1, $vAccLinkDate, $vSalePaidAmnt, $connection); 
	$vSalePaidAmntBase2    = ConvertCurrency($vAccLinkCurr, $base2, $vAccLinkDate, $vSalePaidAmnt, $connection); 
	$vSaleRemainAmnt       = $txtAccLinkRemainAmt_D;
	$vSaleRemainAmntBase1  = ConvertCurrency($vAccLinkCurr, $base1, $vAccLinkDate, $vSaleRemainAmnt, $connection); 
	$vSaleRemainAmntBase2  = ConvertCurrency($vAccLinkCurr, $base2, $vAccLinkDate, $vSaleRemainAmnt, $connection); 
	
		
	
	fbegin();
	$query = " UPDATE ".$_SESSION['dbLabel'].".Temp_AccLink SET ".
			// " Link_ID = '".$vLinkID."', Link_Ref = '".ereg_replace("'", "\'", trim($vLinkRef))."', ". 
			 //" Sale_NetTotal = $vSaleNetTotal, Sale_NetTotalBase1 = $vSaleNetTotalBase1, Sale_NetTotalBase2 = $vSaleNetTotalBase2,  ".
			 //" Sale_NetToPay = $vSaleNetToPay, Sale_NetToPayBase1 = $vSaleNetToPayBase1, Sale_NetToPayBase2 = $vSaleNetToPayBase2,  ".
			 " Sale_PaidAmnt = $vSalePaidAmnt, Sale_PaidAmntbase1 = $vSalePaidAmntBase1, Sale_PaidAmntbase2 = $vSalePaidAmntBase2,  ".
			 " Sale_RemainAmnt = $vSaleRemainAmnt, Sale_RemainAmntBase1 = $vSaleRemainAmntBase1, Sale_RemainAmntBase2 = $vSaleRemainAmntBase2 ".
			 " WHERE Acc_ID = '".$SAccLinkId."'";

	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
		
	if ($result){
		
		fcommit();
	} else{
		$message  = mysql_error(); 
		frollback();
	}

	
} 
//Delete AccLink
else if ($mode == "deleteinvoice" && $SAccLinkId != ""){

	$AllowDelete = 0;
	$ErrorExists = 0;
	$message  = '';
	
	
		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {

		
		fbegin();
		
		// Delete From TempAccLink For Selected Record
		$query = " DELETE FROM ".$_SESSION['dbLabel'].".Temp_AccLink ".
				 " WHERE Acc_ID = '".$SAccLinkId."'";
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
			
	
	} // End If No Constraints Found On Delete
	
	
}
 
else if ($mode == "deleteinvoice2" && $STransDtId != ""){
	$AllowDelete = 0;
	$ErrorExists = 0;
	$message  = '';
	$query = "delete from  ".$_SESSION['dbLabel'].".temp_AllocLink where AllocLink_id=$SDetailLinkId  ";
	$res = mysql_query($query,$connection);
}
else if ($mode == "deleteinvoice2Direct" && $AllocLink != ""){
		$AllowDelete = 0;
		$ErrorExists = 0;
		$message  = '';
		
		// echo"<BR>".
		$queryAlldetails = "select count(*) from  ".$_SESSION['dbLabel'].".Alloclink where AllocLink_id=$AllocLink and upper(AllocComp) =upper('$DirCompany') ";
		 
		$rescount = mysql_query($queryAlldetails,$connection);
		$ct = mysql_fetch_array($rescount);
		if($ct>0){
			// echo"<BR>".
			$query = "delete from  ".$_SESSION['dbLabel'].".Alloclink where  AllocLink_id=$AllocLink and upper(AllocComp) =upper('$DirCompany') ";
			$res = mysql_query($query,$connection); 
		}
		  
		// exit;
	}
	else if ($mode == "deleteinvoice2DirectClient" && $STransDtId != ""){  
		$AllowDelete = 0;
		$ErrorExists = 0;
		$message  = '';
		
		$queryAlldetails = "select count(*) from  ".$_SESSION['dbLabel'].".detaillink where relation_id=$STransDtId";
		 
		$rescount = mysql_query($queryAlldetails,$connection);
		 $ct = mysql_fetch_array($rescount);
		  
		if($ct[0] > 1){
			// 7ott the transdt diff inside the detaillink_id where form_id is null
		
			$queryAlldetails2 = "select count(*) from  ".$_SESSION['dbLabel'].".detaillink where relation_id= $STransDtId AND FORM_ID IS NULL"; 
			$rescount2 = mysql_query($queryAlldetails2,$connection);
			$ct2 = mysql_fetch_array($rescount2);
			if ($ct2[0] > 0) {
				$query = " delete from ".$_SESSION['dbLabel'].".detaillink where relation_id= $STransDtId and form_id is null";
				$res = mysql_query($query,$connection)or die(mysql_error());
				
				$queryAlldetails = "select transdt_amount as tramnt,transdt_amount1 as tramnt1,transdt_amount2 as tramnt2 from transdt where transdt_id = $STransDtId limit 1";
				$rescount = mysql_query($queryAlldetails,$connection);
				$amounts = mysql_fetch_array($rescount);
				extract($amounts);
				$tramnt = $tramnt;
				$tramnt1  = $tramnt1 ;
				$tramnt2 = $tramnt2;
				
				$remAmountDetail = "insert into ".$_SESSION['dbLabel'].".Detaillink (
					Detaillink_date,year,id,company,journal_type,form_id,ledger_number,project_code,costcent_code,amount,amountbase1,amountbase2,currency_code,remark,related_journalType,saleman_number,relation_id,reference,trans_reference,description,value_date,manual_no,link_belongToGoup)
					select Detaillink_date,year,id,company,journal_type,null,ledger_number,project_code,costcent_code,$tramnt,$tramnt1,$tramnt2,currency_code,remark,null,saleman_number,relation_id,null,trans_reference,description,
					value_date,manual_no,link_belongToGoup   from ".$_SESSION['dbLabel'].".detaillink where   detaillink_id = $SDetailLinkId";
					
				$resultx = mysql_query($remAmountDetail,$connection) or die(mysql_error());
	
				$query = "delete from  ".$_SESSION['dbLabel'].".detaillink where relation_id=$STransDtId and Detaillink_id=$SDetailLinkId  ";
				$res = mysql_query($query,$connection)or die(mysql_error());
				
			}else{ 
				// select the journal_type
				$queryType = "select journal_type from  ".$_SESSION['dbLabel'].".detaillink where relation_id= $STransDtId limit 1";
				$resType = mysql_query($queryType,$connection);
				$CurrentType = mysql_fetch_array($resType);
	
				$query = "delete from  ".$_SESSION['dbLabel'].".detaillink where relation_id=$STransDtId and Detaillink_id=$SDetailLinkId  ";
				$res = mysql_query($query,$connection)or die(mysql_error());
	
				// if type  is SR or PR
				if($CurrentType[0] == 'SR'){ 
					$queryAlldetails = "select Amnt1_db as tramnt,Amnt1_db as tramnt1,amnt2_db as tramnt2 from journal  where journal_relatedid  = $STransDtId limit 1";
					$rescount = mysql_query($queryAlldetails,$connection)or die(mysql_error());
					$amounts = mysql_fetch_array($rescount);
					extract($amounts);
					$tramnt = $tramnt;
					$tramnt1  = $tramnt1 ;
					$tramnt2 = $tramnt2; 
				}else{ 
					$queryAlldetails = "select transdt_amount as tramnt,transdt_amount1 as tramnt1,transdt_amount2 as tramnt2 from transdt where transdt_id = $STransDtId limit 1";
					$rescount = mysql_query($queryAlldetails,$connection)or die(mysql_error());
					$amounts = mysql_fetch_array($rescount);
					extract($amounts);
					$tramnt = $tramnt;
					$tramnt1  = $tramnt1 ;
					$tramnt2 = $tramnt2;
				}
				
				
				$queryAlldetails = "select sum(amount) as dtAmnt,sum(amountbase1) as dtAmnt1,sum(amountbase2) as dtAmnt2  from ".$_SESSION['dbLabel'].".detaillink  where  relation_id =  $STransDtId and form_id is not null ";
				$rescount = mysql_query($queryAlldetails,$connection)or die(mysql_error());
				$amounts = mysql_fetch_array($rescount);
				extract($amounts);
				$dtAmnt = $dtAmnt;
				$dtAmnt1  = $dtAmnt1 ;
				$dtAmnt2 = $dtAmnt2;
				
				$amnt =  $tramnt - $dtAmnt;
				$amnt1 =   $tramnt1 - $dtAmnt1;
				$amnt2 =   $tramnt2 - $dtAmnt2;
		
		
				$query = " delete from ".$_SESSION['dbLabel'].".detaillink where relation_id= $STransDtId and form_id is null";
				$res = mysql_query($query,$connection)or die(mysql_error());
		
				$remAmountDetail = "insert into ".$_SESSION['dbLabel'].".Detaillink (
					Detaillink_date,year,id,company,journal_type,form_id,ledger_number,project_code,costcent_code,amount,amountbase1,amountbase2,currency_code,remark,related_journalType,saleman_number,relation_id,reference,trans_reference,description,value_date,manual_no,link_belongToGoup)
					select Detaillink_date,year,id,company,journal_type,null,ledger_number,project_code,costcent_code,$amnt,$amnt1,$amnt2,currency_code,remark,null,saleman_number,relation_id,null,trans_reference,description,
					value_date,manual_no,link_belongToGoup   from ".$_SESSION['dbLabel'].".detaillink where   relation_id =  $STransDtId and form_id is not null limit 1 ";
					
				$resultx = mysql_query($remAmountDetail,$connection) or die(mysql_error());
	
			} 
		}else{
			$queryType = "select journal_type from  ".$_SESSION['dbLabel'].".detaillink where relation_id= $STransDtId limit 1";
			$resType = mysql_query($queryType,$connection);
			$CurrentType = mysql_fetch_array($resType);
	
			// if type  is SR or PR
			if($CurrentType[0] == 'PR'){ 
				$queryAlldetails = "select Amnt1_db as tramnt,Amnt1_db as tramnt1,amnt2_db as tramnt2 from journal where journal_relatedid  = $STransDtId limit 1";
				$rescount = mysql_query($queryAlldetails,$connection)or die(mysql_error());
				$amounts = mysql_fetch_array($rescount);
				extract($amounts);
				$tramnt =  $tramnt;
				$tramnt1  =  $tramnt1 ;
				$tramnt2 =  $tramnt2; 
			}else if($CurrentType[0] == 'SR'){ 
				$queryAlldetails = "select round(Amnt1_db,2) as tramnt,round(Amnt1_db,2) as tramnt1,round(Amnt2_db,2) as tramnt2 from journal where journal_relatedid  = $STransDtId limit 1";
				$rescount = mysql_query($queryAlldetails,$connection)or die(mysql_error());
				$amounts = mysql_fetch_array($rescount);
				extract($amounts);
				$tramnt =  $tramnt;
				$tramnt1  =  $tramnt1 ;
				$tramnt2 =  $tramnt2; 
			}else{ 
				$queryAlldetails = "select transdt_amount as tramnt,transdt_amount1 as tramnt1,transdt_amount2 as tramnt2 from transdt where transdt_id = $STransDtId limit 1";
				$rescount = mysql_query($queryAlldetails,$connection)or die(mysql_error());
				$amounts = mysql_fetch_array($rescount);
				extract($amounts);
				$tramnt = $tramnt;
				$tramnt1  = $tramnt1 ;
				$tramnt2 = $tramnt2;
			}
			$query = " update ".$_SESSION['dbLabel'].".detaillink set 
					form_id = null,
					reference = null,
					related_journaltype = null ,
					amount = $tramnt,
					amountbase1  = $tramnt1 ,
					amountbase2 = $tramnt2
					where relation_id=$STransDtId and Detaillink_id=$SDetailLinkId  ";
			$res = mysql_query($query,$connection);
		}  
		
	}
//Load Invoices
else if ($mode == "loadinvoices" && $STransDtId != '' && $SAccLinkId != ""){
	
	$vLinkRef      = '';
	$vLinkType     = '';
	$vJournalType  = '';
	$vSaleNetTotal         = 0;
	$vSaleNetTotalBase1    = 0;
	$vSaleNetTotalBase2    = 0;
	$vSaleNetToPay         = 0;
	$vSaleNetToPayBase1    = 0;
	$vSaleNetToPayBase2    = 0;
	$vSalePaidAmnt         = 0;
	$vSalePaidAmntBase1    = 0;
	$vSalePaidAmntBase2    = 0;
	$vSaleRemainAmnt       = 0;
	$vSaleRemainAmntBase1  = 0;
	$vSaleRemainAmntBase2  = 0;
	
	$vInvoicePaidAmt1    = 0;
	$vInvoicePaidAmt2    = 0;
	$vInvoiceRemainAmt1  = 0;
	$vInvoiceRemainAmt2  = 0;
	
	$vAccLinkBalAmt   = 0;
	$vAccLinkBalAmt1  = 0;
	$vAccLinkBalAmt2  = 0;
	$vAccLinkTotAmt   = 0;
	$vAccLinkTotAmt1  = 0;
	$vAccLinkTotAmt2  = 0;
	
	
	$sub_query1 = '';
	$sub_query1 = $sub_query1." Select InvoiceID, InvoiceDate, InvoiceRefer, InvoiceType, InvoiceTotalBase1, InvoiceTotalBase2, ".
							  " TransPaidBase1, TransPaidBase2, TransRemBase1, TransRemBase2 ";
		
	$sub_query1 = $sub_query1." From ( ";

	if(($TransType == 'RV' || $TransType == 'CV') && $Module_Delivery == 0 ) {
		$sub_query1 = $sub_query1." Select Deliveries.Delivery_ID As InvoiceID, Deliveries.Delivery_Date As InvoiceDate, Deliveries.Delivery_Reference As InvoiceRefer, 'SI' As InvoiceType, ".
								  " ifNull(AccLink.Sale_NetTotalBase1,0) As InvoiceTotalBase1, ifNull(AccLink.Sale_NetTotalBase2,0) As InvoiceTotalBase2, ".
								  " Sum(ifNull(AccLink.Sale_PaidAmntBase1,0)) As TransPaidBase1, Sum(ifNull(AccLink.Sale_PaidAmntBase2,0)) As TransPaidBase2, ".
								  " (ifNull(AccLink.Sale_NetTotalBase1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As TransRemBase1, ".
								  " (ifNull(AccLink.Sale_NetTotalBase2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As TransRemBase2 ".
								  " From Deliveries ".
								  " Inner Join ".$_SESSION['dbLabel'].".Acclink on Deliveries.Delivery_ID = Acclink.Link_ID ".
								  //" Inner Join TransDt on Acclink.Journal_Id = TransDt.Transdt_Id And Acclink.Journal_Type = '".$TransType."' ".
								  //" Inner Join Trans on TransDt.Trans_Id = Trans.Trans_Id ".
								  " Where Deliveries.Delivery_ID In (".$SAccLinkId.") ".
								  " And Deliveries.Journal_Type = 'DI' ".
								  " And IfNull(Deliveries.Delivery_OldData,0) = 0 ".
								  //" And Trans.Trans_Type In ('RV','CV') ".
								  " And Acclink.Journal_Type In ('RV','CV') ".
								  " And Acclink.Link_Type In ('DI','SI') ".
								  " And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
								  " And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
								  " And ifNull(AccLink.Sale_RemainAmntBase1,0) > 0 ".
								  " Group By InvoiceID, InvoiceDate, InvoiceRefer, InvoiceType ".
								  " Union ".
								  " Select Deliveries.Delivery_ID As InvoiceID, Deliveries.Delivery_Date As InvoiceDate, Deliveries.Delivery_Reference As InvoiceRefer, 'SI' As InvoiceType, ".
								  " (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As InvoiceTotalBase1, ".
								  " (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As InvoiceTotalBase2, ".
								  " 0 As TransPaidBase1, 0 As TransPaidBase2, ".
								  " (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As TransRemBase1, ".
								  " (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As TransRemBase2 ".
								  " From Deliveries ".
								  " Where Deliveries.Delivery_ID In (".$SAccLinkId.") ".
								  " And Deliveries.Journal_Type = 'DI' ".
								  " And IfNull(Deliveries.Delivery_OldData,0) = 0 ".
								  " And Deliveries.Delivery_ID Not In (Select ifNull(Link_ID,-1) From ".$_SESSION['dbLabel'].".Acclink  ".
								  "                          	   	   Where Acclink.Link_Type In ('DI','SI') ".
								  " 							  	   And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
								  "                               	   And upper(Acclink.CompanyName) = upper('".$DirCompany."') ) ";
						
	} 
	else if(($TransType == 'RV' || $TransType == 'CV') && $Module_Delivery == 1 ) {
		$sub_query1 = $sub_query1." Select Sales.Sale_ID As InvoiceID, Sales.Sale_Date As InvoiceDate, Sales.Sale_Reference As InvoiceRefer, 'SI' As InvoiceType, ".
								" ifNull(AccLink.Sale_NetTotalBase1,0) As InvoiceTotalBase1, ifNull(AccLink.Sale_NetTotalBase2,0) As InvoiceTotalBase2, ".
								" Sum(ifNull(AccLink.Sale_PaidAmntBase1,0)) As TransPaidBase1, Sum(ifNull(AccLink.Sale_PaidAmntBase2,0)) As TransPaidBase2, ".
								" (ifNull(AccLink.Sale_NetTotalBase1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As TransRemBase1, ".
								" (ifNull(AccLink.Sale_NetTotalBase2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As TransRemBase2 ".
								" From Sales ".
								" Inner Join ".$_SESSION['dbLabel'].".Acclink on Sales.Sale_ID = Acclink.Link_ID ".
								//" Inner Join TransDt on Acclink.Journal_Id = TransDt.Transdt_Id And Acclink.Journal_Type = '".$TransType."' ".
								//" Inner Join Trans on TransDt.Trans_Id = Trans.Trans_Id ".
								" Where Sales.Sale_ID In (".$SAccLinkId.") ".
								" And Sales.Journal_Type = 'SI' ".
								" And IfNull(Sales.Sale_OldData,0) = 0 ".
								//" And Trans.Trans_Type In ('RV','CV') ".
								" And Acclink.Journal_Type In ('RV','CV') ".
								" And Acclink.Link_Type In ('DI','SI') ".
								" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
								" And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
								" And ifNull(AccLink.Sale_RemainAmntBase1,0) > 0 ".
								" Group By InvoiceID, InvoiceDate, InvoiceRefer, InvoiceType ".
								" Union ".
								" Select Sales.Sale_ID As InvoiceID, Sales.Sale_Date As InvoiceDate, Sales.Sale_Reference As InvoiceRefer, 'SI' As InvoiceType, ".
								" (ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) As InvoiceTotalBase1, ".
								" (ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) As InvoiceTotalBase2, ".
								" 0 As TransPaidBase1, 0 As TransPaidBase2, ".
								" (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 ".
								" From Sales ".
								" Where Sales.Sale_ID In (".$SAccLinkId.")  ".
								" And Sales.Journal_Type = 'SI' ".
								" And IfNull(Sales.Sale_OldData,0) = 0 ".
								" And Sales.Sale_ID Not In ( Select ifNull(Link_ID,-1) From ".$_SESSION['dbLabel'].".Acclink  ".
								"                            Where Acclink.Link_Type In ('DI','SI') ".
								" 							 And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
								"                            And upper(Acclink.CompanyName) = upper('".$DirCompany."') ) ";

	}
	else if ($TransType == 'PV' || $TransType == 'DV') {
		$sub_query1 = $sub_query1." Select Purchases.Purchase_ID As InvoiceID, Purchases.Purchase_Date As InvoiceDate, Purchases.Purchase_Reference As InvoiceRefer, 'PI' As InvoiceType, ".
								" ifNull(AccLink.Sale_NetTotalBase1,0) As InvoiceTotalBase1, ifNull(AccLink.Sale_NetTotalBase2,0) As InvoiceTotalBase2, ".
								" Sum(ifNull(AccLink.Sale_PaidAmntBase1,0)) As TransPaidBase1, Sum(ifNull(AccLink.Sale_PaidAmntBase2,0)) As TransPaidBase2, ".
								" (ifNull(AccLink.Sale_NetTotalBase1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As TransRemBase1, ".
								" (ifNull(AccLink.Sale_NetTotalBase2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As TransRemBase2 ".
								" From Purchases ".
								" Inner Join ".$_SESSION['dbLabel'].".Acclink on Purchases.Purchase_ID = Acclink.Link_ID ".
								//" Inner Join TransDt on Acclink.Journal_Id = TransDt.Transdt_Id And Acclink.Journal_Type = '".$TransType."' ".
								//" Inner Join Trans on TransDt.Trans_Id = Trans.Trans_Id ".
								" Where Purchases.Purchase_ID In (".$SAccLinkId.") ".
								" And Purchases.Journal_Type = 'PI' ".
								" And IfNull(Purchases.Purchase_OldData,0) = 0 ".
								//" And Trans.Trans_Type In ('PV','DV') ".
								" And Acclink.Journal_Type In ('PV','DV') ".
								" And Acclink.Link_Type = 'PI' ".
								" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
								" And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
								" And ifNull(AccLink.Sale_RemainAmntBase1,0) > 0 ".
								" Group By InvoiceID, InvoiceDate, InvoiceRefer, InvoiceType ".
								" Union ".
								" Select Purchases.Purchase_ID As InvoiceID, Purchases.Purchase_Date As InvoiceDate, Purchases.Purchase_Reference As InvoiceRefer, 'PI' As InvoiceType, ".
								" (ifNull(Purchases.Purchase_TotalBase1,0) - ifNull(Purchases.Purchase_DiscountBase1,0) + ifNull(Purchases.Purchase_VATBase1,0)) As InvoiceTotalBase1, ".
								" (ifNull(Purchases.Purchase_TotalBase2,0) - ifNull(Purchases.Purchase_DiscountBase2,0) + ifNull(Purchases.Purchase_VATBase2,0)) As InvoiceTotalBase2, ".
								" 0 As TransPaidBase1, 0 As TransPaidBase2, ".
								" (ifNull(Purchases.Purchase_TotalBase1,0) - ifNull(Purchases.Purchase_DiscountBase1,0) + ifNull(Purchases.Purchase_VATBase1,0)) As TransRemBase1, ".
								" (ifNull(Purchases.Purchase_TotalBase2,0) - ifNull(Purchases.Purchase_DiscountBase2,0) + ifNull(Purchases.Purchase_VATBase2,0)) As TransRemBase2 ".
								" From Purchases ".
								" Where Purchases.Purchase_ID In (".$SAccLinkId.") ".
								" And Purchases.Journal_Type = 'PI' ".
								" And IfNull(Purchases.Purchase_OldData,0) = 0 ".
								" And Purchases.Purchase_ID Not In (Select ifNull(Link_ID,-1) From ".$_SESSION['dbLabel'].".Acclink  ".
								"  		                            Where Acclink.Link_Type = 'PI' ".
								" 							    	And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
								"                               	And upper(Acclink.CompanyName) = upper('".$DirCompany."') ) ";
								
	}
					
	$sub_query1 = $sub_query1." ) As Q1 ";
	//echo $sub_query1; exit;   
	
	$sub_result1=mysql_query($sub_query1,$connection) or die(mysql_error());	
	while($sub_rows1=mysql_fetch_array($sub_result1)){
		$vLinkID       = $sub_rows1[0];
		$vLinkRef      = $sub_rows1[2];
		$vLinkType     = $sub_rows1[3];
		$vJournalType  = $TransType;
		
		
		$sub_query2 = " Select TransDt.TransDt_ID, TransDt.Currency_Code, TransDt.Trans_Date, ".
					  " ifNull(Transdt_Amount,0), ifNull(Transdt_Amount1,0), ifNull(Transdt_Amount2,0), ".
					  " (ifNull(Transdt_Amount,0) - Round(Sum(ifNull(Sale_PaidAmnt,0)),9) ) As PaidAmnt, ".
					  " (ifNull(Transdt_Amount1,0) - Round(Sum(ifNull(Sale_PaidAmntBase1,0)),9) ) As PaidAmnt1, ".
					  " (ifNull(Transdt_Amount2,0) - Round(Sum(ifNull(Sale_PaidAmntBase2,0)),9) ) As PaidAmnt2, ".
					  " Trans.Trans_Reference, TransDt.TransDt_ValueDate, TransDt.TransDt_Description  ". 
					  " From Temp_TransDt As TransDt ".
					  " Inner Join Temp_Trans As Trans on Trans.Trans_Id = TransDt.Trans_Id ".
					  " Left Join ".$_SESSION['dbLabel'].".Temp_AccLink on TransDt.TransDt_ID = Temp_AccLink.Journal_ID ".
					  "   	And Temp_AccLink.Journal_Type = '".$TransType."' ".
					  " 	And upper(Temp_AccLink.CompanyName) = upper('".$DirCompany."') ".
					  "	 	And upper(Temp_AccLink.DirYear) = upper('".$DirYear."') ".
					  " Where TransDt.TransDt_ID = '".$STransDtId."' ".
					  " Group By TransDt.TransDt_ID, Transdt_Amount, Transdt_Amount1, Transdt_Amount2 ";
							  
		//echo $sub_query2; exit;
		$sub_result2 = selectData($connection, $sub_query2);
		
		$vAccLinkCurr     = $sub_result2[1];
		$vAccLinkDate     = $sub_result2[2];
		$vAccLinkTotAmt   = $sub_result2[3];
		$vAccLinkTotAmt1  = $sub_result2[4];
		$vAccLinkTotAmt2  = $sub_result2[5];

		$vAccLinkBalAmt   = $sub_result2[6];
		$vAccLinkBalAmt1  = $sub_result2[7];
		$vAccLinkBalAmt2  = $sub_result2[8];
		
		$vAccLinkRef       = $sub_result2[9];
		$vAccLinkValueDate = $sub_result2[10];
		$vAccLinkDesc      = $sub_result2[11];
		
		$vSaleNetTotalBase1  = $sub_rows1[4];
		$vSaleNetTotalBase2  = $sub_rows1[5];
		
		$vInvoicePaidAmt1    = $sub_rows1[6];
		$vInvoicePaidAmt2    = $sub_rows1[7];
		$vInvoiceRemainAmt1  = $sub_rows1[8];
		$vInvoiceRemainAmt2  = $sub_rows1[9];
	
		if ($vAccLinkBalAmt1 > 0) {
			$vSaleNetToPayBase1    = $vSaleNetTotalBase1 - $vInvoicePaidAmt1;
			$vSaleNetToPayBase2    = $vSaleNetTotalBase2 - $vInvoicePaidAmt2;
			
			if ($vInvoiceRemainAmt1 > 0) {
				if ($vInvoiceRemainAmt1 >= $vAccLinkBalAmt1) {
					$vSalePaidAmntBase1    = $vAccLinkBalAmt1;
					$vSalePaidAmntBase2    = $vAccLinkBalAmt2;
				} else {
					$vSalePaidAmntBase1    = $vInvoiceRemainAmt1;
					$vSalePaidAmntBase2    = $vInvoiceRemainAmt2;
				}
			}
			else {
				if ($vSaleNetTotalBase1 <= $vAccLinkBalAmt1) {
					$vSalePaidAmntBase1    = $vSaleNetTotalBase1;
					$vSalePaidAmntBase2    = $vSaleNetTotalBase2;
				} else {
					$vSalePaidAmntBase1    = $vAccLinkBalAmt1;
					$vSalePaidAmntBase2    = $vAccLinkBalAmt2;
				}
			}
			
			$vSaleRemainAmntBase1  = $vSaleNetTotalBase1 - $vSalePaidAmntBase1 - $vInvoicePaidAmt1;
			$vSaleRemainAmntBase2  = $vSaleNetTotalBase2 - $vSalePaidAmntBase2 - $vInvoicePaidAmt2;
			
			$vSaleNetTotal         = ConvertCurrency($base1, $vAccLinkCurr, $vAccLinkDate, $vSaleNetTotalBase1, $connection); 
			$vSaleNetToPay         = ConvertCurrency($base1, $vAccLinkCurr, $vAccLinkDate, $vSaleNetToPayBase1, $connection); 
			$vSalePaidAmnt         = ConvertCurrency($base1, $vAccLinkCurr, $vAccLinkDate, $vSalePaidAmntBase1, $connection); 
			$vSaleRemainAmnt       = ConvertCurrency($base1, $vAccLinkCurr, $vAccLinkDate, $vSaleRemainAmntBase1, $connection); 
			
			fbegin();
			$query = " INSERT INTO ".$_SESSION['dbLabel'].".Temp_AccLink (Journal_Id, Link_ID, Link_Ref, Link_Type, Journal_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_PaidAmnt, Sale_PaidAmntbase1, Sale_PaidAmntbase2, ".
					 " Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, Trans_Date, Trans_ValueDate, Trans_Description, CompanyName, DirYear, Link_DirYear, User_Account ) ".
					 " VALUES ( ".$STransDtId.", '".$vLinkID."', '".$vLinkRef."', '".$vLinkType."', '".$vJournalType."', $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, ".
					 "          $vSalePaidAmnt, $vSalePaidAmntBase1, $vSalePaidAmntBase2, $vSaleRemainAmnt, $vSaleRemainAmntBase1, $vSaleRemainAmntBase2, $vSaleNetToPay, $vSaleNetToPayBase1, $vSaleNetToPayBase2, ".
					 "          ".$STransDtId.", '".$vAccLinkRef."', '".$vAccLinkDate."', '".$vAccLinkValueDate."', '".$vAccLinkDesc."', '".$DirCompany."', '".$DirYear."', '".$DirYear."', '".$_SESSION['useraccount']."') ";

			//echo $query."<br>";exit;				
			$result=mysql_query($query,$connection);
					
			if ($result){
				fcommit();
			} else{
				$message  = mysql_error(); 
				frollback();
			}
		}
		else {
			$message  = 'Paid amount exceeds ('.number_format($vAccLinkTotAmt, $DecimalBase).') '.$vAccLinkCurr;
		}
		
		
	}
	
	
}

else if ($mode == "AllocateInvoices" && $PInvoicesID != '' && $PReceiptsID != ""){
	// var_dump($_GET);
	// echo"<BR>";
	preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
	$DirCompany  = $vMainCompanyName[0];
	$DirYear =  $DirYears[0][0];
	if ($referer == 'SR'){

		// get amount to allocate from delivery 
		// echo"<BR>".
		$queryDel = "select journal_id , Currency_Code , Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2 from deliveries where delivery_id = $PReceiptsID";
		$resDel = mysql_query($queryDel,$connection);
		$rowDel = mysql_fetch_array($resDel);
		extract($rowDel);
			
		
		// echo "<br>".
		$removeoldAllocs = "delete from ".$_SESSION['dbLabel'].".`alloclink` where   journal_idC = '$journal_id' and UPPER(AllocComp)=UPPER('$DirCompany')  and TransType = 'SR';";
		$resDel = mysql_query($removeoldAllocs,$connection);





	}else if ($referer == 'PR'  ) {

		
		// get amount to allocate from purchase 
		// echo"<BR>".
		$queryDel = "select ifnull(journal_id,0) , Currency_Code , purchase_Total, purchase_TotalBase1, purchase_TotalBase2 from purchases where purchase_id = $PReceiptsID";
		$resDel = mysql_query($queryDel,$connection);
		$rowDel = mysql_fetch_array($resDel);
		extract($rowDel);

		// echo "<br>".
		$removeoldAllocs = "delete from ".$_SESSION['dbLabel'].".`alloclink` where trans_id = '$PReceiptsID' and transtype = 'PR' and UPPER(AllocComp)=UPPER('$DirCompany') ;";
		$resDel = mysql_query($removeoldAllocs,$connection);

		// echo "<br>".
		$querySupCode = "select Supplier_code from purchases where purchase_id = $PReceiptsID";
		$resSupCode = mysql_query($querySupCode,$connection);
		$rowSupCode = mysql_fetch_array($resSupCode);
		echo "<br>".
		$vLedger_code = $rowSupCode[0];
		
	}

	if ($referer == 'SR' ){
		// echo "<br> ".
		$queryins = "INSERT INTO ".$_SESSION['dbLabel'].".`alloclink`(`AllocLink_id`, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`,TransType) VALUES 
		(null, now(), '$PInvoicesID', '". $journal_id ."', '$Currency_Code',  $Delivery_Total , $Delivery_TotalBase1, $Delivery_TotalBase2, '$DirCompany', '$DirYear', 'direct sales return Alloc', '$PReceiptsID', '', 'SR');";
	}else{
		if($journal_id == '') $journal_id = 'null';
		 echo "<br> ".
		$queryins = "INSERT INTO ".$_SESSION['dbLabel'].".`alloclink`(`AllocLink_id`, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`,TransType,ledger_number) VALUES 
		(null, now(), ifnull($journal_id,0) , '". $PInvoicesID ."', '$Currency_Code',  $purchase_Total , $purchase_TotalBase1, $purchase_TotalBase2, '$DirCompany', '$DirYear', 'direct Pur. return Alloc', '$PReceiptsID', '$STransDtId', 'PR' , $vLedger_code);";
	}
		
	$sub_result	= mysql_query($queryins,$connection);	
	 

	// exit;


	if ($referer == 'SR' ){
		header ("Location: ./Form_ReturnDelivery.php");
	}else	if ($referer == 'PR' ){
		header ("Location: ./Form_ReturnPurchase.php");

	}

}
		 

else if ($mode == "loadinvoices2" && $STransDtId != '' && $SSelectedRows != ""){

// echo"<h1>GET</h1>";
// var_dump($_GET);
// echo"<h1>POST</h1>";
// var_dump($_POST);	
	
if(empty($TransJournalId)) $TransJournalId = 'null';

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

	$CurrTransType = $_GET['TransType'];
	 
	if ($CurrTransType == 'PV' || $CurrTransType == 'DV' ){
		// echo "<br>".
		$removeoldAllocs = "delete from ".$_SESSION['dbLabel'].".`temp_alloclink` where if( '$TransJournalId' <> '' , journal_idC = '$TransJournalId' ,   trans_id = $STransId and TransType = '$CurrTransType' ) and AllocYear='$DirYear' and AllocComp='$DirCompany' ;"; 
	   }else if ($CurrTransType == 'RV' || $CurrTransType == 'CV' ) {
		$removeoldAllocs = "delete from ".$_SESSION['dbLabel'].".`temp_alloclink` where if( '$TransJournalId' <> '' , journal_idD = '$TransJournalId' ,   trans_id = $STransId and TransType = '$CurrTransType' ) and AllocYear='$DirYear' and AllocComp='$DirCompany' ;";
	   } 
	//  echo " --- TransType : ". $CurrTransType ;
	
	$sub_result	= mysql_query($queryins,$connection);
	$SelectedRows = explode(',',$SSelectedRows);
	
	foreach ($SelectedRows as $value){
		$JVID = 'JVID'.$value;
		$amounttopay = 'amounttopay'.$value;  
		$remark = 'remark'.$value;  
		$CurrJVID = $$JVID;
		$Curramount = $$amounttopay;
		$AllocationDate =  date("Y-m-d  H:i:s");
		$STransId =  $STransId;
		$STransDtId =  $STransDtId; 
		$Currremark =  $$remark;
		
		$CurramountB1  = ConvertCurrency($CurrencyCode, $base1, $AllocationDate, $Curramount, $connection); 
		$CurramountB2  = ConvertCurrency($CurrencyCode, $base2, $AllocationDate, $Curramount, $connection);
		if ($CurrTransType == 'PV' || $CurrTransType == 'DV' ){
		//  echo "<br> ".
		$queryins = "INSERT INTO ".$_SESSION['dbLabel'].".`temp_alloclink`(`AllocLink_id`, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`,TransType,ledger_number) VALUES 
		(null, now(), ".$TransJournalId.", ". $CurrJVID .", '$CurrencyCode',  $Curramount , $CurramountB1, $CurramountB2, '$DirCompany', $DirYear, '$Currremark', '$STransId', '$STransDtId', '$CurrTransType', '$vledgerNum');
		"; 
		}else{
			// echo "<br> ".
			$queryins = "INSERT INTO ".$_SESSION['dbLabel'].".`temp_alloclink`(`AllocLink_id`, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`,TransType,ledger_number) VALUES 
		(null, now(), $CurrJVID, ". $TransJournalId .", '$CurrencyCode',  $Curramount , $CurramountB1, $CurramountB2, '$DirCompany', $DirYear, '$Currremark', '$STransId', '$STransDtId', '$CurrTransType', '$vledgerNum');
		";
		}
		$sub_result	= mysql_query($queryins,$connection);	
	} 
	//  exit;
	
}

else if ( $mode == "unallocateSup"  && $SendLedger_number != ''){
	$queryAllJvs = "delete from ".$_SESSION['dbLabel'].".`alloclink` where ledger_number = $SendLedger_number and upper(AllocComp) =upper('$DirCompany')  ";
	$sub_result	= mysql_query($queryAllJvs,$connection) or die(mysql_error());	

}

else if ( $mode == "unallocateSupRep"   && $SendLedger_number != ''){
	$queryAllJvs = "delete from ".$_SESSION['dbLabel'].".`alloclink` where ledger_number = $SendLedger_number and upper(AllocComp) =upper('$DirCompany')  ";
	$sub_result	= mysql_query($queryAllJvs,$connection) or die(mysql_error());	
	if($sub_result)
		echo "[BRK]Done";
	else	
		echo "[BRK]Failed err: ".mysql_error();
	
	exit;
}

else if ($mode == "loadinvoices3" && ( $STransId != '' || $STransJVId    != ''  ) && $SSelectedRows != ""){
//echo"GET<BR>";
	//var_dump($_GET);
	// echo"<HR>";
 	//echo"POST<BR>";
	 //var_dump($_POST);
	 //echo"<HR>";
	$vMainCompanyName=explode('_',$_SESSION['dbName']);  
	preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
	$DirCompany  = $vMainCompanyName[0];
	$DirYear =  $DirYears[0][0];

	$CurrTransType = $_GET['TransType'];
	// Live Allocation we only allocate Remaining Balances
	// if ($CurrTransType == 'PV' || $CurrTransType == 'DV' ){
	// 	// echo "<br>".
	// 	$removeoldAllocs = "delete from ".$_SESSION['dbLabel'].".`alloclink` where if( '$TransJournalId' <> '' , journal_idC = '$TransJournalId' ,   trans_id = $STransId and TransType = '$CurrTransType' ) and AllocYear='$DirYear' and AllocComp='$DirCompany' ;"; 
	// 	}else if ($CurrTransType == 'RV' || $CurrTransType == 'CV' ) {
	// 	$removeoldAllocs = "delete from ".$_SESSION['dbLabel'].".`alloclink` where if( '$TransJournalId' <> '' , journal_idD = '$TransJournalId' ,   trans_id = $STransId and TransType = '$CurrTransType' ) and AllocYear='$DirYear' and AllocComp='$DirCompany' ;";
	// 	} 
	//  echo " --- TransType : ". $CurrTransType ;
	
	
	
	
	
	
	$sub_result	= mysql_query($queryins,$connection);
	$SelectedRows = explode(',',$SSelectedRows);
	//   echo"<BR> CurrencyCode : ".
	$CurrencyCode = $_POST['CurrencyCode'];
	foreach ($SelectedRows as $value){
		// echo"<HR>";
		// echo"<BR> JVID : ".
		$JVID = 'JVID'.$value;
		// echo"<BR> amounttopay : ".
		$amounttopay = 'amounttopay'.$value;  
		// echo"<BR> remark : ".
		$remark = 'remark'.$value;  
		
		// echo"<BR> CurrJVID : ".
		$CurrJVID = $$JVID;
		// echo"<BR> Curramount : ".
		$Curramount = $$amounttopay;
		// echo"<BR> AllocationDate : ".
		$AllocationDate =  date("Y-m-d  H:i:s");
		// echo"<BR> TransJournalId : ".
		$TransJournalId =  $STransJVId;	
		// echo"<BR> STransId : ".
		$currSTransId =  $_GET['STransId'];
		// echo"<BR> STransDTId : ".
		$currSTransDTId = $_GET['STransDTId'];
		// echo"<BR> STransDtId : ".
		// $STransDtId =  $STransDtId; 
		// echo"<BR> Currremark : ".
		$Currremark =  $$remark; 
		// echo"<BR> CurramountB1 : ".
		$CurramountB1  = ConvertCurrency($CurrencyCode, $base1, $AllocationDate, $Curramount, $connection); 
		// echo"<BR> CurramountB2 : ".
		$CurramountB2  = ConvertCurrency($CurrencyCode, $base2, $AllocationDate, $Curramount, $connection);


		$querySide = "select journaldt_dbcd from journaldt where journal_id = '$TransJournalId' and Ledger_number = '$vLedgerNumber'";
		 
		$resultSide= mysql_query($querySide,$connection) or die("<BR>$query<BR> ERR2060 - ".mysql_error());
		$CurrSideRow = mysql_fetch_array($resultSide); 
		$CurrSide = $CurrSideRow[0]; 
	
		if ($CurrSide == 'D'  ){
			//   echo "<br> D: ".
			$queryins = "INSERT INTO ".$_SESSION['dbLabel'].".`alloclink`(`AllocLink_id`, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`,TransType,ledger_number)
			VALUES 
			(null, now(), '$TransJournalId', '". $CurrJVID ."', '$CurrencyCode',  $Curramount , $CurramountB1, $CurramountB2, '$DirCompany', $DirYear, '$Currremark', '$currSTransId', '$currSTransDTId', '$CurrTransType',$vLedgerNumber);";
			// exit; 
		}else{
			//  echo "<br> C: ".
			$queryins = "INSERT INTO ".$_SESSION['dbLabel'].".`alloclink`(`AllocLink_id`, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`,TransType,ledger_number)
			 VALUES 
			 (null, now(), '$CurrJVID', '". $TransJournalId ."', '$CurrencyCode',  $Curramount , $CurramountB1, $CurramountB2, '$DirCompany', $DirYear, '$Currremark', '$currSTransId', '$currSTransDTId', '$CurrTransType',$vLedgerNumber);";
			//  exit;
		}
		 $sub_result	= mysql_query($queryins,$connection) or die(mysql_error());	
	}

	// exit;
}
 
else if($mode == "checkInvoices" && $mainmode == ""){
	if($STransId != ''){
		$checkInv = 0;
		$vMainCompanyName=explode('_',$_SESSION['dbName']);  
		$DirCompany  = $vMainCompanyName[0];
		preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
		$DirYear =  $DirYears[0][0];  

		$queryDebit = "select ifnull(sum(ifnull(Transdt_Amount1,0)),0)-ifnull(sum(ifnull(amountbase1,0)),0),
						ifnull(sum(ifnull(Transdt_Amount2,0)),0) - ifnull(sum(ifnull(amountbase2,0)),0),count(*)
						from ".$_SESSION['dbLabel'].".temp_detaillink as temp_detaillink
						left join temp_TransDt on TransDt_ID = relation_id
						where Trans_ID = $STransId and TransDt_dbcd='D' 
						and temp_detaillink.journal_type='$PTransType' and year='$DirYear' and company='$DirCompany' 
						group by TransDt_ID ;";
		$res = mysql_query($queryDebit,$connection);
		$numrow1 = mysql_num_rows($res);
		$rwDebit = mysql_fetch_row($res);
		if($numrow1 = 0) $checkInv1 = 0;
		else $checkInv1 = 1;
		/*else 
		{
			if($rwDebit[0] == 0 && $rwDebit[1] == 0 && $rwDebit[2] > 0) $checkInv = 1;
			else $checkInv = 0;
		}*/
		
		$queryCredit = "select ifnull(sum(ifnull(Transdt_Amount1,0)),0)-ifnull(sum(ifnull(amountbase1,0)),0),
						ifnull(sum(ifnull(Transdt_Amount2,0)),0) - ifnull(sum(ifnull(amountbase2,0)),0),count(*)
						from ".$_SESSION['dbLabel'].".temp_detaillink as temp_detaillink
						left join temp_TransDt on TransDt_ID = relation_id
						where Trans_ID = $STransId and TransDt_dbcd='C' 
						and temp_detaillink.journal_type='$PTransType' and year='$DirYear' and company='$DirCompany' 
						group by TransDt_ID ;";
		$res = mysql_query($queryCredit,$connection);
		$numrow1 = mysql_num_rows($res);
		$rwCredit = mysql_fetch_row($res);
		if($numrow1 = 0) $checkInv2 = 0;
		else $checkInv2 = 1;
		/*{
		if($rwCredit[0] == 0 && $rwCredit[1] == 0 && $rwCredit[2] > 0) $checkInv = 1;
		else $checkInv = 0;
		}*/
		
		if($checkInv1 == 1 && $checkInv2 == 1) $checkInv=1;
		else $checkInv=0;
		
	}
	echo $checkInv;
	exit;
}
//Delete Record Mode From Main Tables
else if ($mode == "" && $mainmode == "delete" && $STransId != ''){

	$AllowDelete = 0;
	$message  = '';
	
	$sub_query = " Select Journal_Id From Trans Where Trans_id = ".$STransId;
	$sub_result = selectData($connection, $sub_query);
	$vTransJournalID = $sub_result[0];
	if(empty($vTransJournalID)) $vTransJournalID = -1;
	
	//Check If Trans Is Posted
	$query = "SELECT ifNull(Trans_Posted,0) As TransPosted FROM Trans WHERE Trans_id = ".$STransId;
	$result = selectData($connection, $query);
	$TransPosted = $result[0];
	
	if ($TransPosted == 1 ){
		$message  = 'Delete not allowed, Transaction posted.';
		$AllowDelete = 1;
	}
	
	
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);
	
	 $sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
				  
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		$query = "SELECT date_format(Trans_Date,'%d/%m/%Y') FROM Trans WHERE Trans_id = ".$STransId;
		$result = selectData($connection, $query);
		$txtDate  = $result[0];
 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $AllowDelete = 1;
		if ($LockedPeriodDays != '' && dateDiff(GetSQLValueString(insertMySQLDate(displayToday()),'date'),GetSQLValueString(insertMySQLDate($txtDate),'date')) >= $LockedPeriodDays) $AllowDelete = 1; 

		//if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $AllowDelete = 1;
		if($AllowDelete==1) $message  = 'Delete not allowed, Exceed Lock Period.';
	}
 
	
	
	
	if ($AllowDelete == 0) {
		//Check Each JournalDt If Has Related Checks Used
		$query = " Select Count(*) ".
				 " From Checks Inner Join JournalDt on Checks.Journaldt_Id1 = JournalDt.JournalDt_Id ".
				 " Inner Join ChkJourDt on Checks.Chk_Number = ChkJourDt.Chk_Number and Checks.Ledger_Number = ChkJourDt.Ledger_Number  ".
				 " Where JournalDt.Journal_Id = '".$vTransJournalID."' ".
				 " And ChkJourDt.TransDt_Id In (Select TransDt_Id From TransDt where Trans_Id = '".$STransId."') ".
				 " And (ifNull(Checks.Journaldt_id2,0) != 0 and Checks.Journaldt_id2 != '') ";

		$result = selectData($connection, $query);
		$ChecksExists = $result[0];
			
		if ($ChecksExists > 0 ){
			$message  = 'Delete not allowed, Cheques been used.';
			$AllowDelete = 1;
		}
	}	
	
	if ($AllowDelete == 0) {
		//Check Each JournalDt If Has Related Checks Used
		$query = " Select Count(*) ".
				 " From Bills Inner Join JournalDt on Bills.Journaldt_Id1 = JournalDt.JournalDt_Id ".
				 " Inner Join BillJourDt on Bills.Bill_Number = BillJourDt.Bill_Number and Bills.Ledger_Number = BillJourDt.Ledger_Number  ".
				 " Where JournalDt.Journal_Id = '".$vTransJournalID."' ".
				 " And BillJourDt.TransDt_Id In (Select TransDt_Id From TransDt where Trans_Id = '".$STransId."') ".
				 " And (ifNull(Bills.Journaldt_id2,0) != 0 and Bills.Journaldt_id2 != '') ";

		$result = selectData($connection, $query);
		$BillsExists = $result[0];
			
		if ($BillsExists > 0 ){
			$message  = 'Delete not allowed, Bills been used.';
			$AllowDelete = 1;
		}
	}
	
	/*if ($AllowDelete == 0) {
		$queryPrqst = "select PaymentRqst_id from trans where trans_id = $STransId and Trans_Type = 'PV'";
		$resPrqst = mysql_query($queryPrqst,$connection);
		$rwPrqst = mysql_fetch_row($resPrqst);
		$prqst_id = $rwPrqst[0];
		if ($prqst_id != '' ){
			$message  = 'Delete not allowed, Payment exists in Payment Request.';
			$AllowDelete = 1;
		}
		
	}*/
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {
		
		$vMainCompanyName=explode('_',$_SESSION['dbName']);  
		$DirCompany  = $vMainCompanyName[0];
		preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
		$DirYear =  $DirYears[0][0];  
		//delete detaillink
		// $query = " DELETE FROM ".$_SESSION['dbLabel'].".detaillink  ".
				 // " WHERE relation_id in (select TransDt_Id from TransDt where Trans_Id = $STransId) 
				  // and year='$DirYear' and company='$DirCompany'";
		
		// if (!updateData($connection, $query, true))		 
			// $message  = mysql_error(); 
		if($config['log_file'] == 1){
			$company = explode("_", $_SESSION['dbName']);
			$currCompany = strtoupper($company[0]);
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$STransId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'trans', '$currCompany')";
					//echo $query_insertToHistory;exit;
					// $result_insertToHistory = 
					if(!mysql_query($query_insertToHistory, $connection))
						die(mysql_error());
		}
	    // Delete From CstjourDt For Selected Record
		$query = " DELETE FROM CstjourDt ".
				 " WHERE CstjourDt.TransDt_id In (Select TransDt_Id From TransDt Where Trans_Id = '".$STransId."') ";
				 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
			
		// Delete From ChkjourDt For Selected Record
		$query = " DELETE FROM ChkjourDt ".
				 " WHERE ChkjourDt.TransDt_id In (Select TransDt_Id From TransDt Where Trans_Id = '".$STransId."') ";
				 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 	
			
		// Delete From BilljourDt For Selected Record
		$query = " DELETE FROM BilljourDt ".
				 " WHERE BilljourDt.TransDt_id In (Select TransDt_Id From TransDt Where Trans_Id = '".$STransId."') ";
				 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 	

		// Delete From AccLink For Selected Record
		// $query = " DELETE FROM ".$_SESSION['dbLabel'].".AccLink ".
				 // " WHERE AccLink.Journal_Id In (Select TransDt_Id From TransDt Where Trans_Id = '".$STransId."') And AccLink.Journal_Type = '".$TransType."' ";
				 
		// if (!updateData($connection, $query, true))		 
			// $message  = mysql_error(); 	
				
		// Delete From TransDt For Selected Record
		// $query = " DELETE FROM TransDt ".
				 // " WHERE Trans_id = ".$STransId;
					 
		if (updateData($connection, $query, true)) {
			$queryprqst = "select PaymentRqst_Id From Trans WHERE Trans_id = $STransId;";
			$resprqst = mysql_query($queryprqst,$connection);
			$rowprqst = mysql_fetch_row($resprqst);
			$PaymentRqst_Id = $rowprqst[0];
			
			// Delete From Trans For Selected Record
			$query = " DELETE FROM Trans ".
					 " WHERE Trans_id = ".$STransId;
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
			else {
				if($PaymentRqst_Id != ''){
					$queryup = "update paymentrqst set PaymentRqst_Used = 0 where PaymentRqst_id = $PaymentRqst_Id;";
					$resup = mysql_query($queryup,$connection);
				}
			}			
			if ($vTransJournalID != -1) {
				
				$query = " DELETE FROM Journal ".
						 " WHERE Journal_Id = ".$vTransJournalID;
				
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 	
					
				
				// Manage Checks After Delete
				$sub_query1 = " Select ChkJourDt_Id, Chk_Number, Chk_Type, Ledger_Number ".
							  " From ChkJourDt ".
							  " WHERE ChkjourDt.TransDt_id In (Select TransDt_Id From TransDt Where Trans_Id = '".$STransId."') ";
							  
				$sub_result1=mysql_query($sub_query1,$connection);
				while($sub_row1=mysql_fetch_row($sub_result1)){	
					$sub_query2  = " Select Count(*), ifNull(journaldt_id2,0) From Checks Where Chk_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' Group By journaldt_id2 ";
					$sub_result2 = selectData($connection, $sub_query2);
					$vChkCount     = $sub_result2[0];
					$vJournalDtId2  = $sub_result2[1];
					
					if (empty($vChkCount)) $vChkCount = 0;
					
					if ($vChkCount > 0) {
						if ($sub_row1[2] == 'C') {
							$sub_query3  = " UPDATE checks set journaldt_id2 = Null Where Chk_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
						} else if ($vJournalDtId2 == 0) {
							$sub_query3  = " DELETE From Checks Where Chk_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
						}
						
						if (!updateData($connection, $sub_query3, true))		 
							$message  = mysql_error();
					
					}
				
				}
				
				
				// Manage Bills After Delete
				$sub_query1 = " Select BillJourDt_Id, Bill_Number, Bill_Type, Ledger_Number ".
							  " From BillJourDt ".
							  " WHERE BilljourDt.TransDt_id In (Select TransDt_Id From TransDt Where Trans_Id = '".$STransId."') ";
							  
				$sub_result1=mysql_query($sub_query1,$connection);
				while($sub_row1=mysql_fetch_row($sub_result1)){	
					$sub_query2  = " Select Count(*), ifNull(journaldt_id2,0) From Bills Where Bill_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' Group By journaldt_id2 ";
					$sub_result2 = selectData($connection, $sub_query2);
					$vBillCount     = $sub_result2[0];
					$vJournalDtId2  = $sub_result2[1];
					
					if (empty($vBillCount)) $vBillCount = 0;
					
					if ($vBillCount > 0) {
						if ($sub_row1[2] == 'C') {
							$sub_query3  = " UPDATE Bills set journaldt_id2 = Null Where Bill_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
						} else if ($vJournalDtId2 == 0) {
							$sub_query3  = " DELETE From Bills Where Bill_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
						}
						
						if (!updateData($connection, $sub_query3, true))		 
							$message  = mysql_error();
					
					}
				
				}

				
			
			}	
		}
		else
			$message  = mysql_error(); 	
		
	}
	
	
}

//Delete Record Mode From Temp Tables
else if (($mode == "cancel" || $mainmode == "deletepending") && $STransId != ''){

	// Delete From Temp_CstjourDt For Selected Record
	$query = " DELETE FROM Temp_CstjourDt ".
			 " WHERE Temp_CstjourDt.TransDt_id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 
			
	// Delete From Temp_ChkjourDt For Selected Record
	$query = " DELETE FROM Temp_ChkjourDt ".
			 " WHERE Temp_ChkjourDt.TransDt_id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 	
			
	// Delete From Temp_BilljourDt For Selected Record
	$query = " DELETE FROM Temp_BilljourDt ".
			 " WHERE Temp_BilljourDt.TransDt_id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 	

	  
	//Delete DetailLink
	if($Module_InvoiceGrid == 2){
		preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
		$DirYear =  $DirYears[0][0];
	$query = " DELETE FROM ".$_SESSION['dbLabel'].".temp_alloclink  where Trans_id = '".$STransId."'   AND upper( AllocComp ) = upper('$DirCompany') and AllocYear =  '$DirYear' and transtype = '$TransType'";
	// echo "<BR>".$query ; exit;	
	$res = mysql_query($query); 
	}	
	// Delete From Temp_TransDt For Selected Record
	$query = " DELETE FROM Temp_TransDt ".
			 " WHERE Trans_id = ".$STransId;
			 
		 
	if (updateData($connection, $query, true)) {
		// Delete From TempTrans For Selected Record
		$query = " DELETE FROM Temp_Trans ".
				 " WHERE Trans_id = ".$STransId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
		
	}
	else
		$message  = mysql_error(); 	
	

}

//Search Mode	
else if(($mainmode == "search" || $mainmode == "searchunposted") && $STransId != ''){

	$ErrorExists = 0;
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO temp_trans (Trans_ID, Trans_Reference, Trans_Date, Trans_SysDate, Trans_Remark, Trans_Type, Trans_Representative, ".
	         " Trans_ManualNo, Currency_Code, Trans_CashReference, CashType_code, Project_Code, Costcent_code, Trans_Posted, Journal_Id, ".
			 " Trans_AmountDb1, Trans_AmountDb2, Trans_Amountcd1, Trans_Amountcd2, Trans_BelongsToGroup, PaymentRqst_Id, Trans_UserConfirmed, ".
			 " Synchronized, User_Account, Logged_Code,AdvancePayment ) ".
			 " SELECT Trans_ID, Trans_Reference, Trans_Date, Trans_SysDate, Trans_Remark, Trans_Type, Trans_Representative, ".
	         " Trans_ManualNo, Currency_Code, Trans_CashReference, CashType_code, Project_Code, Costcent_code, Trans_Posted, Journal_Id, ".
			 " Trans_AmountDb1, Trans_AmountDb2, Trans_Amountcd1, Trans_Amountcd2, Trans_BelongsToGroup, PaymentRqst_Id, Trans_UserConfirmed, ".
			 " Synchronized, User_Account, '".$_SESSION['useraccount']."',AdvancePayment ".
			 " FROM Trans ".
			 " WHERE Trans_id = ".$STransId;
	
	if (!updateData($connection, $query, true)) {
	  $ErrorExists = 1;
      $message  = mysql_error(); 	
	}  

	if ($ErrorExists == 0) {
		//echo $message.$query; exit;				 
		$query = " INSERT INTO temp_transdt (TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ". 
				 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, TransDt_ManualNo, Detail_Code, Synchronized,transdt_rate, ".
				 " User_Account, Logged_Code, transdt_checkNo )  ".
				 " SELECT TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ". 
				 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, TransDt_ManualNo, Detail_Code, Synchronized,transdt_rate, ".
				 " User_Account, '".$_SESSION['useraccount']."', transdt_checkNo ".
				 " FROM Transdt ".
				 " WHERE Trans_id = ".$STransId;
		
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 			


		$query = " INSERT INTO temp_cstjourdt (TransDt_id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, CstJourDt_Amount1, CstJourDt_Amount2, Synchronized, User_Account, Logged_Code ) ".
				 " SELECT TransDt_id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, CstJourDt_Amount1, CstJourDt_Amount2, Synchronized, User_Account, '".$_SESSION['useraccount']."' ".
				 " FROM CstjourDt ".
				 " WHERE CstjourDt.TransDt_id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 
		  
		  
		$query = " INSERT INTO temp_chkjourdt (TransDt_id, Chk_number, Chk_bank, Chk_ValueDate, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2, Ledger_Number, Chk_Type, Synchronized, User_Account, Logged_Code ) ".
				 " SELECT TransDt_id, Chk_number, Chk_bank, Chk_ValueDate, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2, Ledger_Number, Chk_Type, Synchronized, User_Account, '".$_SESSION['useraccount']."' ".
				 " FROM ChkjourDt ".
				 " WHERE ChkjourDt.TransDt_id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error();   
		  
		  
		$query = " INSERT INTO temp_billjourdt (TransDt_id, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2, Ledger_Number, Bill_type, Synchronized, Logged_Code ) ".
				 " SELECT TransDt_id, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2, Ledger_Number, Bill_type, Synchronized, '".$_SESSION['useraccount']."' ".
				 " FROM BilljourDt ".
				 " WHERE BilljourDt.TransDt_id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error();    

		// $query = " INSERT INTO ".$_SESSION['dbLabel'].".temp_AccLink (Journal_Id, Link_ID, Link_Ref, Link_Type, Journal_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_PaidAmnt, Sale_PaidAmntbase1, Sale_PaidAmntbase2, ".
		// 		 " Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, Trans_Date, Trans_ValueDate, Trans_Description, CompanyName, DirYear, Link_DirYear, User_Account ) ".
		// 		 " SELECT Journal_Id, Link_ID, Link_Ref, Link_Type, Journal_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_PaidAmnt, Sale_PaidAmntbase1, Sale_PaidAmntbase2, ".
		// 		 " Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, Trans_Date, Trans_ValueDate, Trans_Description, CompanyName, DirYear, Link_DirYear, User_Account ".
		// 		 " FROM ".$_SESSION['dbLabel'].".AccLink ".
		// 		 " WHERE AccLink.Journal_Id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ".
		// 		 " And AccLink.Journal_Type = '".$TransType."' ".
		// 		 " And upper(AccLink.CompanyName) = upper('".$DirCompany."') ".
		// 		 " And upper(AccLink.DirYear) = upper('".$DirYear."') ";
		// //echo $query; exit;		 
		// if (!updateData($connection, $query, true))
		//   $message  = mysql_error();  
		
		
		 
			if($Module_InvoiceGrid == 2){
					$vMainCompanyName=explode('_',$_SESSION['dbName']);  
					$DirCompany  = $vMainCompanyName[0];
					preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
					$DirYear =  $DirYears[0][0];  

					$query_detailLink = "INSERT INTO ".$_SESSION['dbLabel'].".`temp_alloclink`(`AllocLink_id`, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`, `transtype`) 
					select null, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`, `transtype`
					from ".$_SESSION['dbLabel'].".`alloclink`
					where 
 					( trans_id = '".$STransId."' OR if((select IFNULL(TransDt_dbcd,'C') from transdt inner join suppliers on transdt.ledger_number = suppliers.ledger_number and trans_id = '".$STransId."') = 'D' , journal_idD = ( SELECT journal_id FROM trans WHERE trans_id = '".$STransId."' ) , journal_idC = ( SELECT journal_id FROM trans WHERE trans_id = '".$STransId."' ) ) )
					AND upper(AllocComp) = upper('".$DirCompany."')
					AND AllocYear = '".$DirYear."'
					AND transtype = '$TransType'
					 ";
					// 
					$res_detailLink = mysql_query($query_detailLink,$connection);
					//  echo mysql_error($connection); 	
					//  echo $query_detailLink; exit;
			}
					
				
	}
}
else if($mainmode == "editfromreport"){
$STransId = $_GET['STransId'];
	$ErrorExists = 0;
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO temp_trans (Trans_ID, Trans_Reference, Trans_Date, Trans_SysDate, Trans_Remark, Trans_Type, Trans_Representative, ".
	         " Trans_ManualNo, Currency_Code, Trans_CashReference, CashType_code, Project_Code, Costcent_code, Trans_Posted, Journal_Id, ".
			 " Trans_AmountDb1, Trans_AmountDb2, Trans_Amountcd1, Trans_Amountcd2, Trans_BelongsToGroup, PaymentRqst_Id, Trans_UserConfirmed, ".
			 " Synchronized, User_Account, Logged_Code ) ".
			 " SELECT Trans_ID, Trans_Reference, Trans_Date, Trans_SysDate, Trans_Remark, Trans_Type, Trans_Representative, ".
	         " Trans_ManualNo, Currency_Code, Trans_CashReference, CashType_code, Project_Code, Costcent_code, Trans_Posted, Journal_Id, ".
			 " Trans_AmountDb1, Trans_AmountDb2, Trans_Amountcd1, Trans_Amountcd2, Trans_BelongsToGroup, PaymentRqst_Id, Trans_UserConfirmed, ".
			 " Synchronized, User_Account, '".$_SESSION['useraccount']."' ".
			 " FROM Trans ".
			 " WHERE Trans_id = ".$STransId;
	
	if (!updateData($connection, $query, true)) {
	  $ErrorExists = 1;
      $message  = mysql_error(); 
//$message = $query;	  
	}  

	if ($ErrorExists == 0) {
		//echo $message.$query; exit;				 
		$query = " INSERT INTO temp_transdt (TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ". 
				 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, TransDt_ManualNo, Detail_Code, Synchronized, ".
				 " User_Account, Logged_Code, transdt_checkNo )  ".
				 " SELECT TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ". 
				 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, TransDt_ManualNo, Detail_Code, Synchronized, ".
				 " User_Account, '".$_SESSION['useraccount']."', transdt_checkNo  ".
				 " FROM Transdt ".
				 " WHERE Trans_id = ".$STransId;
		
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 			


		$query = " INSERT INTO temp_cstjourdt (TransDt_id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, CstJourDt_Amount1, CstJourDt_Amount2, Synchronized, User_Account, Logged_Code ) ".
				 " SELECT TransDt_id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, CstJourDt_Amount1, CstJourDt_Amount2, Synchronized, User_Account, '".$_SESSION['useraccount']."' ".
				 " FROM CstjourDt ".
				 " WHERE CstjourDt.TransDt_id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 
		  
		  
		$query = " INSERT INTO temp_chkjourdt (TransDt_id, Chk_number, Chk_bank, Chk_ValueDate, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2, Ledger_Number, Chk_Type, Synchronized, User_Account, Logged_Code ) ".
				 " SELECT TransDt_id, Chk_number, Chk_bank, Chk_ValueDate, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2, Ledger_Number, Chk_Type, Synchronized, User_Account, '".$_SESSION['useraccount']."' ".
				 " FROM ChkjourDt ".
				 " WHERE ChkjourDt.TransDt_id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error();   
		  
		  
		$query = " INSERT INTO temp_billjourdt (TransDt_id, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2, Ledger_Number, Bill_type, Synchronized, Logged_Code ) ".
				 " SELECT TransDt_id, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2, Ledger_Number, Bill_type, Synchronized, '".$_SESSION['useraccount']."' ".
				 " FROM BilljourDt ".
				 " WHERE BilljourDt.TransDt_id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error();    

		// $query = " INSERT INTO ".$_SESSION['dbLabel'].".temp_AccLink (Journal_Id, Link_ID, Link_Ref, Link_Type, Journal_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_PaidAmnt, Sale_PaidAmntbase1, Sale_PaidAmntbase2, ".
				 // " Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, Trans_Date, Trans_ValueDate, Trans_Description, CompanyName, DirYear, Link_DirYear, User_Account ) ".
				 // " SELECT Journal_Id, Link_ID, Link_Ref, Link_Type, Journal_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_PaidAmnt, Sale_PaidAmntbase1, Sale_PaidAmntbase2, ".
				 // " Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, Trans_Date, Trans_ValueDate, Trans_Description, CompanyName, DirYear, Link_DirYear, User_Account ".
				 // " FROM ".$_SESSION['dbLabel'].".AccLink ".
				 // " WHERE AccLink.Journal_Id In (Select TransDt_Id From Temp_TransDt Where Trans_Id = '".$STransId."') ".
				 // " And AccLink.Journal_Type = '".$TransType."' ".
				 // " And upper(AccLink.CompanyName) = upper('".$DirCompany."') ".
				 // " And upper(AccLink.DirYear) = upper('".$DirYear."') ";
		// //echo $query; exit;		 
		// if (!updateData($connection, $query, true))
		  // $message  = mysql_error();   

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

					// $query_detailLink = "insert into ".$_SESSION['dbLabel'].".temp_detaillink(Detaillink_id,Detaillink_date, year, id, company, journal_type, ".
										// " form_id, ledger_number, project_code, costcent_code, saleman_number, amount, amountbase1, ".
										// " amountbase2,currency_code, remark, related_journalType,relation_id,reference,trans_reference,link_belongToGoup)".
										// " select Detaillink_id,Detaillink_date, year, id, company, journal_type, form_id, detaillink.ledger_number, project_code, ".
										// " detaillink.costcent_code, saleman_number, amount, amountbase1, amountbase2, detaillink.currency_code, remark, ".
										// " related_journalType,relation_id,reference,trans_reference,link_belongToGoup ".
										// " from ".$_SESSION['dbLabel'].".detaillink as  detaillink ".
										// " left join transdt on transdt.transdt_id = relation_id ".
										// " where journal_type = '$TransType' And upper(company) = upper('".$DirCompany."') ".
										// " And upper(year) = upper('".$DirYear."') and  Trans_Id = '".$STransId."' "; 
					// //echo $query_detailLink; exit;
					// $res_detailLink = mysql_query($query_detailLink,$connection);
					
					
					
					
					$query_detailLink = "INSERT INTO ".$_SESSION['dbLabel'].".`temp_alloclink`(`AllocLink_id`, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`, `transtype`) 
					select null, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`, `transtype`
					from ".$_SESSION['dbLabel'].".`alloclink`
					where 
 					( trans_id = '".$STransId."' OR if((select IFNULL(TransDt_dbcd,'C') from transdt inner join suppliers on transdt.ledger_number = suppliers.ledger_number and trans_id = '".$STransId."') = 'D' , journal_idD = ( SELECT journal_id FROM trans WHERE trans_id = '".$STransId."' ) , journal_idC = ( SELECT journal_id FROM trans WHERE trans_id = '".$STransId."' ) ) )
					AND upper(AllocComp) = upper('".$DirCompany."')
					AND AllocYear = '".$DirYear."'
					AND transtype = '$TransType' ";
					// 
					$res_detailLink = mysql_query($query_detailLink,$connection);
					//  echo mysql_error($connection); 	
					//  echo $query_detailLink; exit;
					
					
					
					
	}
	header ("Location: ./Form_Trans.php?actionmode=&mainaction=edit&txtTransId=".$STransId."&message=".$message."&TransType=".$TransType);
exit;
}

else if($mainmode == 'ConfirmTrans' &&  $STransId != '' ){
	$update = "update trans set Trans_Confirmed=1, Trans_UserConfirmed = '".$_SESSION['useraccount']."' where trans_id = $STransId; ";
	$res = mysql_query($update,$connection);	
	if($res) $message="Transaction is confirmed!";
	else 	$message= mysql_error($connection); 	
}

//Load Payment Request
else if($mainmode == "loadrequest" && $SPaymentRqstId != ''){
	$ErrorExists = 0;

	fbegin();	
	$vTransId = get_nextsequence('trans_id','',$connection);	
	fcommit();
		
	$query = " INSERT INTO temp_trans (Trans_ID, Trans_Reference, Trans_Date, Trans_SysDate, Trans_Remark, Trans_Type, Trans_Representative, ".
	         " Trans_ManualNo, Currency_Code, Trans_CashReference, CashType_code, Project_Code, Costcent_code, Trans_Posted, Journal_Id, ".
			 " Trans_AmountDb1, Trans_AmountDb2, Trans_Amountcd1, Trans_Amountcd2, Trans_BelongsToGroup, Synchronized, PaymentRqst_Id, ".
			 " Trans_UserConfirmed, User_Account, Logged_Code ) ".
			 " SELECT $vTransId, Null, now(), now(), ".
			 " if($paymentrqstNoDt =1,Concat(PaymentRqst_Remark,if(paymentrqst_cash=1,'/ Cash /',
			 if(paymentrqst_check,'<br>Cheque /','')),if(paymentrqst_costshare=1,'Costshare /',
			 if(paymentrqst_guarantee,'Guarantee /','')),PaymentRqst_AMOUNT,' ',Currency_Code),
			 PaymentRqst_Remark), ".
			 " 'PV', PaymentRqst_Name, ".
	         " PaymentRqst_ManualNo, Currency_Code, Null, Null, Project_Code, Costcent_code, 0, Null, ".
			 " PaymentRqst_AmountD1, PaymentRqst_AmountD2, PaymentRqst_AmountC1, PaymentRqst_AmountC2, $FI_BelongsToGrp, 0, ".
			 " PaymentRqst_Id, User_Confirmed, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' ".
			 " FROM PaymentRqst ".
			 " WHERE PaymentRqst_Id = ".$SPaymentRqstId;
	//echo $query; exit;
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error($connection); 	
	}
	
	if ($ErrorExists == 0) {
		$STransId = $vTransId;
		
		$sub_query = " SELECT PaymentRqstDt_Id, PaymentRqst_Id, PaymentRqst_Date, Ledger_Number, PaymentRqstDt_Desc, PaymentRqstDt_Desc1, ". 
					 " PaymentRqstDt_ValueDate, Currency_Code, ifNull(PaymentRqstDt_Amount,0), ifNull(PaymentRqstDt_Amount1,0), ifNull(PaymentRqstDt_Amount2,0), ".
					 " PaymentRqstDt_dbcd, PaymentRqstdt_dbcdAra   ".
					 " FROM PaymentRqstDt ".
					 " WHERE PaymentRqst_Id = ".$SPaymentRqstId;
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());		

		while($sub_rows=mysql_fetch_array($sub_result)){
		
			fbegin();
			$vTransDtId = get_nextsequence('transdt_id','',$connection);	
			fcommit();
			
			$query = " INSERT INTO temp_transdt (TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ". 
					 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, Detail_Code, Synchronized, User_Account, Logged_Code )  ".
					 " VALUES ( ".$vTransDtId.", ".$vTransId.", '".$sub_rows[7]."', '".$sub_rows[2]."', '".$sub_rows[3]."', '".$sub_rows[4]."', ".
					 "          '".$sub_rows[5]."', '".$sub_rows[6]."', ".$sub_rows[8].", ".$sub_rows[9].", ".$sub_rows[10].", '".$sub_rows[11]."', '+', ".
					 "          Null, 0, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."'	) ";
			//echo $query; exit;
			if (updateData($connection, $query, true)) {
		
				$query = " INSERT INTO temp_cstjourdt (TransDt_id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, CstJourDt_Amount1, CstJourDt_Amount2, Synchronized, User_Account, Logged_Code ) ".
						 " SELECT $vTransDtId, Project_code, Costcent_Code, CstRqst_Prcnt, CstRqst_Amount, CstRqst_Amount1, CstRqst_Amount2, 0, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' ".
						 " FROM CstRqst ".
						 " WHERE CstRqst.PaymentRqstDt_Id = '".$sub_rows[0]."'";
						 
				if (!updateData($connection, $query, true))
					$message  = mysql_error(); 
				  
		
				$query = " INSERT INTO temp_chkjourdt (TransDt_id, Chk_number, Chk_bank, Chk_ValueDate, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2, Ledger_Number, Chk_Type, Synchronized, User_Account, Logged_Code ) ".
						 " SELECT $vTransDtId, Chk_number, Chk_bank, Chk_ValueDate, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2, Ledger_Number, Chk_Type, 0, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' ".
						 " FROM ChkRqst ".
						 " WHERE ChkRqst.PaymentRqstDt_Id = '".$sub_rows[0]."'";
						 
				if (!updateData($connection, $query, true))
					$message  = mysql_error();   
				  
		
				$query = " INSERT INTO temp_billjourdt (TransDt_id, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2, Ledger_Number, Bill_type, Synchronized, Logged_Code ) ".
						 " SELECT $vTransDtId, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2, Ledger_Number, Bill_type, 0, '".$_SESSION['useraccount']."' ".
						 " FROM BillRqst ".
						 " WHERE BillRqst.PaymentRqstDt_Id = '".$sub_rows[0]."'";
						 
				if (!updateData($connection, $query, true))
					$message  = mysql_error();    
			}
			else {
				$message  = mysql_error($connection); 
			}	

		}
	
	
	}

}


//Load Sales Order
else if($mainmode == "loadsorder" && $SSorderId != ''){
	$ErrorExists = 0;

	fbegin();	
	$vTransId = get_nextsequence('trans_id','',$connection);	
	fcommit();
		
	$query = " INSERT INTO temp_trans (Trans_ID, Trans_Reference, Trans_Date, Trans_SysDate, Trans_Remark, Trans_Type, Trans_Representative, ".
	         " Trans_ManualNo, Currency_Code, Trans_CashReference, CashType_code, Project_Code, Costcent_code, Trans_Posted, Journal_Id, ".
			 " Trans_AmountDb1, Trans_AmountDb2, Trans_Amountcd1, Trans_Amountcd2, Trans_BelongsToGroup, Synchronized, PaymentRqst_Id, ".
			 " Trans_UserConfirmed, User_Account, Logged_Code ) ".
			 " SELECT $vTransId, Null, now(), now(), concat('Sorder Ref: ', Sorder_Reference), 'RV', Null, ".
	         " Null, Currency_Code, Null, Null, Project_Code, Costcent_code, 0, Null, 0, 0, 0, 0, $FI_BelongsToGrp, 0, ".
			 " Null, Null, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' ".
			 " FROM Sorder ".
			 " WHERE Sorder_Id = ".$SSorderId;
	
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error($connection); 	
	}
	
	if ($ErrorExists == 0) {
		$STransId = $vTransId;
		
		$sub_query = " SELECT Sorder_Id, Sorder_Date, Client_Code, Currency_Code, ". 
					 " (ifNull(Sorder.Sorder_Taxable,0) + ifNull(Sorder.Sorder_NoneTaxable,0) + IfNull(Sorder.Sorder_VAT,0) - ifNull(Sorder.Sorder_DiscountAmount,0) + ".
					 "  (ifNull(Sorder.Sorder_Tax1,0) + ifNull(Sorder.Sorder_Tax2,0) + ifNull(Sorder.Sorder_Tax3,0) + ifNull(Sorder.Sorder_Tax4,0) + ifNull(Sorder.Sorder_Tax5,0))) As NetTotal,  ".
					 " concat('Sorder Ref: ', Sorder_Reference), Project_Code, Costcent_code ".
					 " FROM Sorder ".
					 " WHERE Sorder_Id = ".$SSorderId;
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());		

		while($sub_rows=mysql_fetch_array($sub_result)){
		
			fbegin();
			$vTransDtId = get_nextsequence('transdt_id','',$connection);	
			fcommit();
			
			$vTransDtAmount    = $sub_rows[4];
			$vTransDtAmountB1  = ConvertCurrency($sub_rows[3], $base1, $sub_rows[1], $vTransDtAmount, $connection); 
			$vTransDtAmountB2  = ConvertCurrency($sub_rows[3], $base2, $sub_rows[1], $vTransDtAmount, $connection);
			
			
			$query = " INSERT INTO temp_transdt (TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ". 
					 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, Detail_Code, Synchronized, User_Account, Logged_Code )  ".
					 " VALUES ( ".$vTransDtId.", ".$vTransId.", '".$sub_rows[3]."', now(), '".$sub_rows[2]."', '".$sub_rows[5]."', Null, ".
					 "          now(), $vTransDtAmount, $vTransDtAmountB1, $vTransDtAmountB2, 'C', '+', Null, 0, ".
					 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."'	) ";
			//echo $query; exit;
			if (updateData($connection, $query, true)) {
		
				$vCstJourDtPer   = 100;
				$vCstJourDtAmt   = $vTransDtAmount;
				$vCstJourDtAmt1  = $vTransDtAmountB1;
				$vCstJourDtAmt2  = $vTransDtAmountB2;
				$vProjectCodeDt	 = GetSQLValueString($sub_rows[6],'text');
				$vCostCentCodeDt = GetSQLValueString($sub_rows[7],'text');
				
				//Case Header Project or Costcenter Is Not Empty Automatically Insert Into CstjourDt	
				if ($sub_rows[6] != '' || $sub_rows[7] != '' ) {
				
					$query = " INSERT INTO temp_cstjourdt (TransDt_Id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, CstJourDt_Amount1, CstJourDt_Amount2, ".
							 " Synchronized, User_Account, Logged_Code ) ". 
							 " VALUES ( ".$vTransDtId.", $vProjectCodeDt, $vCostCentCodeDt, $vCstJourDtPer, $vCstJourDtAmt, $vCstJourDtAmt1, $vCstJourDtAmt2, ".
							 "          0, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."'	) ";
							 
					//echo $query."<br>";exit;				
					$result=mysql_query($query,$connection);
				}

				
				$sub_query = " Select Sum(if(TransDt_dbcd='D', ifNull(Transdt_Amount1,0), 0)) As TotalDebitAmount1, Sum(if(TransDt_dbcd='D', ifNull(Transdt_Amount2,0), 0)) As TotalDebitAmount2, ".
							 " Sum(if(TransDt_dbcd='C', ifNull(Transdt_Amount1,0), 0)) As TotalCreditAmount1, Sum(if(TransDt_dbcd='C', ifNull(Transdt_Amount2,0), 0)) As TotalCreditAmount2 ".
							 " From Temp_TransDt ".
							 " Where Trans_ID = ".$STransId;
				$sub_result = selectData($connection, $sub_query);
				
				$vTransAmountDb1 = $sub_result[0];
				$vTransAmountDb2 = $sub_result[1];
				$vTransAmountcd1 = $sub_result[2];
				$vTransAmountcd2 = $sub_result[3];
				
				if(empty($vTransAmountDb1)) $vTransAmountDb1 = 0;
				if(empty($vTransAmountDb2)) $vTransAmountDb2 = 0;
				if(empty($vTransAmountcd1)) $vTransAmountcd1 = 0;
				if(empty($vTransAmountcd2)) $vTransAmountcd2 = 0;
				
					 
				$sub_query1 = " UPDATE temp_trans SET ".
							  " Trans_AmountDb1 = $vTransAmountDb1, Trans_AmountDb2 = $vTransAmountDb2, ".
							  " Trans_Amountcd1 = $vTransAmountcd1, Trans_Amountcd2 = $vTransAmountcd2 ".
							  " WHERE Trans_ID = ".$STransId;
				$sub_result1=mysql_query($sub_query1,$connection);
				
				
				$sub_query2 = " UPDATE sorder SET Sorder_Invoiced = 1 WHERE Sorder_ID = ".$SSorderId;
				$sub_result1=mysql_query($sub_query2,$connection);
		
				
			}
			else {
				$message  = mysql_error($connection); 
			}	

		}
	
	
	}

}

//Post Transactions
else if($mainmode == "posttrx"){

	$vSelectedRows = $_POST['SelectedRows']; 
	
	$sub_query = " select Trans_ID , myuserAcc  from ( ".
				 " Select Trans.Trans_ID  as Trans_ID , Trans.User_Account  as myuserAcc ".
				 " From Trans ".
				 " Where Trans.Trans_ID In (".$vSelectedRows.") ".
				 " ) as Q where Q.Trans_ID not in (select trans_id from temp_trans) ";
				        
	//echo $sub_query; exit;
	$sub_result=mysql_query($sub_query,$connection);
	while($sub_row=mysql_fetch_row($sub_result)){
		$vTransID = $sub_row[0];
		$vUser = $sub_row[1];
		
		$vTransCashCode  = '';
		$vTransCashRef   = '';
		/*	
		$query   = " SELECT Trans_Reference, Costcent_code, Project_Code, CashType_Code, Trans_CashReference FROM Trans WHERE Trans_id = $vTransID ";
		$result  = selectData($connection, $query);
		$vTransRef      = $result[0];
		$vCostCentCode  = $result[1];
		$vProjectCode   = $result[2];
		$vTransCashCode = $result[3];
		$vTransCashRef  = $result[4];
						
		if ($vTransRef == '') {
			if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
			else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
			else $vProjCostCent = '';
								
			if ($TransType == 'PV') 	 $RefField = 'Payment_RefGovernment';
			else if ($TransType == 'RV') $RefField = 'Receipt_RefGovernment';
			else if ($TransType == 'DV') $RefField = 'Dbtnote_RefGovernment';
			else if ($TransType == 'CV') $RefField = 'Crdnote_RefGovernment';
			else if ($TransType == 'CT') $RefField = 'Contra_RefGovernment';	
						
			fbegin();
			$vTransRef = get_nextsequence($RefField,$vProjCostCent,$connection);	
			fcommit();
							
			$query = " UPDATE Trans SET ".
					 " Trans_Reference = $vTransRef ".
					 " WHERE Trans_id = $vTransID ";
							
			if (!updateData($connection, $query, true)) 
				$message  = mysql_error();
						
		}	
					
		//Set The CashType Reference
		if ($vTransCashRef == '' && $vTransCashCode != '') {
						
			fbegin();
			$vTransCashRef = get_nextsequence_cashtype('CashType_Reference' , $vTransCashCode, $TransType ,$connection);	
			fcommit();
							
			$query = " UPDATE Trans SET ".
					 " Trans_CashReference = $vTransCashRef ".
					 " WHERE Trans_id = $vTransID ";
							
			if (!updateData($connection, $query, true)) 
				$message  = mysql_error();
						
		}*/
		
		$sub_query1 = " UPDATE Trans SET ".
					  " Acctrx_posted = 1 , Trans_UserConfirmed = '".$_SESSION['useraccount']."' ".
					  " WHERE Trans_id = '".$vTransID."'";
						
		if (!updateData($connection, $sub_query1, true)) 
			$message  = mysql_error();
		
		//Create Related Journal For Each Transaction
		$message = Create_TransJv($vTransID, $_SESSION['dbName'], $_SESSION['dbLabel'], $vUser, $vUser); 	
	}
	
}

else if($mode == "changecurrency" && $STransId != ''){ 
 
	$sub_query = " UPDATE temp_trans SET Currency_Code = '".$txtCurr."' WHERE Trans_ID = ".$STransId;
	$sub_result=mysql_query($sub_query,$connection);
	//echo $sub_query."<br>"; exit;

	if (!($sub_result)){
		$message  = mysql_error($connection); 
	}
}

//Post Mode	
else if($mode == "post" && $STransId != ''){  
	// var_dump($_POST);exit;
	if (!isset($txtCurr))
	   $txtCurr = $base1;
	$txtCostCentCode = "".$txtCostCentCode;   
	if ($txtCostCentCode == '')	$CostCentCode = 'Null';
	else		$CostCentCode = "'".$txtCostCentCode."'";
	
	$txtProjectCode = "".$txtProjectCode;	
	if ($txtProjectCode == '')		$ProjectCode = 'Null';
	else		$ProjectCode = "'".$txtProjectCode."'";      
	
	if (empty($txtCashType))		$CashTypeCode = 'Null';
	else		$CashTypeCode = "'".$txtCashType."'";	
	if($txtAdvancePayment == '') $txtAdvancePayment=0;

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
	
	$AllowSave = 1;
	
	$vCstJourDtBalPer   = 0;
	$vCstJourDtBalAmt   = 0;
	$vCstJourDtBalAmt1  = 0;
	$vCstJourDtBalAmt2  = 0;
	
	$vChkJourDtBalAmt   = 0;
	$vChkJourDtBalAmt1  = 0;
	$vChkJourDtBalAmt2  = 0;
	
	$vTransAmountDb1 = 0;
	$vTransAmountDb2 = 0;
	$vTransAmountcd1 = 0;
	$vTransAmountcd2 = 0;
		
	
	if ($Module_Project == 1 || $Module_CostCenter == 1 || $Module_ProjectDt == 1 || $Module_CostCenterDt == 1) {	
		$sub_query1 = " Select TransDt.TransDt_ID, (100 - Round(Sum(ifNull(CstjourDt_Per,0)),2)) As CstjourDtPer, ".
					  " (Round(ifNull(Transdt_Amount,0), ".$DecimalBase1.") - Round(Sum(ifNull(CstJourDt_Amount,0)), ".$DecimalBase1.") ) As CstJourDtAmount, ".
					  " (Round(ifNull(Transdt_Amount1,0), ".$DecimalBase1.") - Round(Sum(ifNull(CstJourDt_Amount1,0)), ".$DecimalBase1.") ) As CstJourDtAmount1, ".
					  " (Round(ifNull(Transdt_Amount2,0), ".$DecimalBase1.") - Round(Sum(ifNull(CstJourDt_Amount2,0)), ".$DecimalBase1.") ) As CstJourDtAmount2 ".
					  " From Temp_TransDt As TransDt ";
		if ($Module_ReferenceByCostcenter == 1 || $Module_RestrictProjCost == 1 || $Module_RestrictCost == 1)
			$sub_query1 .=" left Join Temp_CstjourDt on TransDt.TransDt_ID = Temp_CstjourDt.TransDt_ID ";
		else 
			$sub_query1 .=" inner Join Temp_CstjourDt on TransDt.TransDt_ID = Temp_CstjourDt.TransDt_ID ";
		$sub_query1 .=" Where TransDt.Trans_ID = '".$STransId."' ".
					  " Group By TransDt.TransDt_ID ";
					  
							  
		//echo $sub_query1; exit;
		$sub_result1=mysql_query($sub_query1,$connection);
		while($sub_row1=mysql_fetch_row($sub_result1)){
		
			$vTransDtId         = $sub_row1[0];
			$vCstJourDtBalPer   = $sub_row1[1];
			$vCstJourDtBalAmt   = $sub_row1[2];
			$vCstJourDtBalAmt1  = $sub_row1[3];
			$vCstJourDtBalAmt2  = $sub_row1[4];
			
			if($vCstJourDtBalPer != 0 || $vCstJourDtBalAmt1 != 0 || $vCstJourDtBalAmt2 != 0) {
				$AllowSave = 0;
				$ErrorRecId = $vTransDtId;
				$message='Save not allowed. Total of Projects/Costcenters does not match Total Amount.';
				break;
			}
		}	
	}
	
						
	
	$sub_query2 = " Select TransDt.TransDt_ID, ".
	              " (Round(ifNull(Transdt_Amount,0), ".$DecimalBase1.") - Round(Sum(ifNull(Chk_Amount,0)), ".$DecimalBase1.") ) As ChkAmount, ".
				  " (Round(ifNull(Transdt_Amount1,0), ".$DecimalBase1.") - Round(Sum(ifNull(Chk_Amount1,0)), ".$DecimalBase1.") ) As ChkAmount1, ".
				  " (Round(ifNull(Transdt_Amount2,0), ".$DecimalBase1.") - Round(Sum(ifNull(Chk_Amount2,0)), ".$DecimalBase1.") ) As ChkAmount2 ".
				  " From Temp_TransDt As TransDt Inner Join Temp_ChkjourDt on TransDt.TransDt_ID = Temp_ChkjourDt.TransDt_ID ".
				  " Where TransDt.Trans_ID = '".$STransId."' ".
				  " Group By TransDt.TransDt_ID ";
				  
					      
	//echo $sub_query2; exit;
	$sub_result2=mysql_query($sub_query2,$connection);
	while($sub_row2=mysql_fetch_row($sub_result2)){
	
		$vTransDtId         = $sub_row2[0];
		$vChkJourDtBalAmt   = $sub_row2[1];
		$vChkJourDtBalAmt1  = $sub_row2[2];
		$vChkJourDtBalAmt2  = $sub_row2[3];
		
		if($vChkJourDtBalAmt != 0 || $vChkJourDtBalAmt1 != 0 || $vChkJourDtBalAmt2 != 0) {
			$AllowSave = 0;
			$ErrorRecId = $vTransDtId;
			$message='Save not allowed. Total of Cheques does not match Total Amount.';
			break;
		}
	}
	
	
	$sub_query3 = " Select TransDt.TransDt_ID, ".
	              " (Round(ifNull(Transdt_Amount,0), ".$DecimalBase1.") - Round(Sum(ifNull(Bill_Amount,0)), ".$DecimalBase1.") ) As BillAmount, ".
				  " (Round(ifNull(Transdt_Amount1,0), ".$DecimalBase1.") - Round(Sum(ifNull(Bill_Amount1,0)), ".$DecimalBase1.") ) As BillAmount1, ".
				  " (Round(ifNull(Transdt_Amount2,0), ".$DecimalBase1.") - Round(Sum(ifNull(Bill_Amount2,0)), ".$DecimalBase1.") ) As BillAmount2 ".
				  " From Temp_TransDt As TransDt Inner Join Temp_BilljourDt on TransDt.TransDt_ID = Temp_BilljourDt.TransDt_ID ".
				  " Where TransDt.Trans_ID = '".$STransId."' ".
				  " Group By TransDt.TransDt_ID ";
					      
	//echo $sub_query3; exit;
	$sub_result3=mysql_query($sub_query3,$connection);
	while($sub_row3=mysql_fetch_row($sub_result3)){
	
		$vTransDtId          = $sub_row3[0];
		$vBillJourDtBalAmt   = $sub_row3[1];
		$vBillJourDtBalAmt1  = $sub_row3[2];
		$vBillJourDtBalAmt2  = $sub_row3[3];
		
		if($vBillJourDtBalAmt != 0 || $vBillJourDtBalAmt1 != 0 || $vBillJourDtBalAmt2 != 0) {
			$AllowSave = 0;
			$ErrorRecId = $vTransDtId;
			$message='Save not allowed. Total of Bills does not match Total Amount.';
			break;
		}
	}
	
	/*$sub_query4 = " Select TransDt.TransDt_ID, ".
				  " (Round(ifNull(Transdt_Amount,0), ".$DecimalBase.") - Round(Sum(ifNull(Sale_PaidAmnt,0)),".$DecimalBase.") ) As PaidAmnt, ".
				  " (Round(ifNull(Transdt_Amount1,0), ".$DecimalBase1.") - Round(Sum(ifNull(Sale_PaidAmntBase1,0)),".$DecimalBase1.") ) As PaidAmnt1, ".
				  " (Round(ifNull(Transdt_Amount2,0), ".$DecimalBase2.") - Round(Sum(ifNull(Sale_PaidAmntBase2,0)),".$DecimalBase2.") ) As PaidAmnt2 ".
				  " From Temp_TransDt As TransDt Inner Join ".$_SESSION['dbLabel'].".Temp_AccLink on TransDt.TransDt_ID = Temp_AccLink.Journal_ID ".
				  " And Temp_AccLink.Journal_Type = '".$TransType."' ".
				  " And upper(Temp_AccLink.CompanyName) = upper('".$DirCompany."') ".
				  " And upper(Temp_AccLink.DirYear) = upper('".$DirYear."') ".
				  " Where TransDt.Trans_ID = '".$STransId."' ".
				  " Group By TransDt.TransDt_ID "; 
							  
	//echo $sub_query4; exit;
	$sub_result4=mysql_query($sub_query4,$connection);
	while($sub_row4=mysql_fetch_row($sub_result4)){
		
		$vTransDtId       = $sub_row4[0];
		$vAccLinkBalAmt   = $sub_row4[1];
		$vAccLinkBalAmt1  = $sub_row4[2];
		$vAccLinkBalAmt2  = $sub_row4[3];
		
		//if($vAccLinkBalAmt != 0 || $vAccLinkBalAmt1 != 0 || $vAccLinkBalAmt2 != 0) {
		if($vAccLinkBalAmt != 0) {
			$AllowSave = 0;
			$ErrorRecId = $vTransDtId;
			$message='Save not allowed. Invoice(s) paid amount does not match Total Amount.';
			break;
		}
	}*/
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

	$sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
				  
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	 
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) { 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && insertMySQLDate($txtDate) < $LockedPeriodDate) $ExceedLockPeriod = 1;
		 
		$DateQuery = "select datediff(date_format('".insertMySQLDate(displayToday())."', '%Y-%m-%d %H:%i:%s'),date_format('".insertMySQLDate($txtDate)."','%Y-%m-%d 00:00:00')) ";
		$DateQuery_result = mysql_query($DateQuery,$connection) or die(mysql_error());
		$mydatediff = mysql_fetch_array($DateQuery_result);
		 
		
		
		if ($LockedPeriodDays != '' && $mydatediff[0] > 0 && $mydatediff[0]  >= $LockedPeriodDays) $ExceedLockPeriod = 1; 
		 
		if ($ExceedLockPeriod == 1) {
			 $AllowSave = 0;
			$message='Save not allowed. Exceed Lock Period.'; 
		} 
		 
	}					
			

	if ($Module_UniqueManualNo == 1 && $txtManualNo != "") {		
		//Check For Manual No To Be Unique
		$sub_query = " Select Count(*) From ( Select Trans_ID From Trans Where Trans_Type = '".$TransType."' and upper(Trans_ManualNo) = '".$txtManualNo."' and Trans_Id != $STransId ".
					 "                 Union  Select Trans_ID From Temp_Trans Where Trans_Type = '".$TransType."' and upper(Trans_ManualNo) = '".$txtManualNo."' and Trans_Id != $STransId ) Q1 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 1 ) {
			$AllowSave = 0;
			$message = 'Save not allowed. Manual No should be unique.';
		}	
	}	
						
	if ($AllowSave == 1) {	
		
		$sub_query4 = " Select Sum(if(TransDt_dbcd='D', ifNull(Transdt_Amount1,0), 0)) As TotalDebitAmount1, Sum(if(TransDt_dbcd='D', ifNull(Transdt_Amount2,0), 0)) As TotalDebitAmount2, ".
					  " Sum(if(TransDt_dbcd='C', ifNull(Transdt_Amount1,0), 0)) As TotalCreditAmount1, Sum(if(TransDt_dbcd='C', ifNull(Transdt_Amount2,0), 0)) As TotalCreditAmount2 ".
					  " From Temp_TransDt ".
					  " Where Trans_ID = ".$STransId;
		$sub_result4 = selectData($connection, $sub_query4);
			
		$vTransAmountDb1 = $sub_result4[0];
		$vTransAmountDb2 = $sub_result4[1];
		$vTransAmountcd1 = $sub_result4[2];
		$vTransAmountcd2 = $sub_result4[3];
			
				 
		$sub_query5 = " UPDATE temp_trans SET ".
					  " Trans_AmountDb1 = $vTransAmountDb1, Trans_AmountDb2 = $vTransAmountDb2, ".
					  " Trans_Amountcd1 = $vTransAmountcd1, Trans_Amountcd2 = $vTransAmountcd2, ".
					  " Currency_Code = '".$txtCurr."', Trans_Date = '".insertMySQLDate($txtDate)."', ".
					  " Trans_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', ".
					  " Trans_Representative = '".ereg_replace("'", "\'", trim($txtRepresent))."',  ".
					  " Trans_ManualNo = '".ereg_replace("'", "\'", trim($txtManualNo))."',  ".
					  " CashType_code = $CashTypeCode,  ".
					  " Project_Code = $ProjectCode, Costcent_code = $CostCentCode, ".
					  " AdvancePayment = $txtAdvancePayment".
					  " WHERE Trans_ID = ".$STransId;
				 
		$sub_result5=mysql_query($sub_query5,$connection);
		//echo $sub_query5."<br>"; exit;
	
	
		if ($sub_result5){
			
			$sub_query6 = " UPDATE temp_transdt SET ".
						  " Trans_Date = '".insertMySQLDate($txtDate)."' ".
						  " WHERE Trans_ID = ".$STransId;
				 
			$sub_result6=mysql_query($sub_query6,$connection);
					
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			//echo $SMode;exit;
			
			$vTransCashCode   = '';
			$vTransCashRef    = '';
			$vOldProjCode  	  = '';
			$vOldCostCentCode = '';
			$vTransPosted	  = 0;
			
			// In Edit Case, Get The Old Values For CashType, Project and Costcenter For References Issue
			$query   = " SELECT CashType_Code, Trans_CashReference, Project_Code, Costcent_code, ifNull(acctrx_Posted,0)  FROM Trans WHERE Trans_id = $STransId ";
			$result  = selectData($connection, $query);
			$vTransCashCode   = $result[0];
			$vTransCashRef    = $result[1];
			$vOldProjCode  	  = $result[2];
			$vOldCostCentCode = $result[3];
			$vTransPosted     = $result[4];
			
			$query_checkDelivery  = "select count(*) as TransExist from trans where trans_id = '$STransId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($TransExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
			
			fbegin();	
			$resultvars = mysql_query("set @result :=0 ", $connection);
			$query = "CALL CopyData_TempTrans('".$SMode."', ".$STransId.", '".$_SESSION['useraccount']."', '".$_SESSION['dbLabel']."', @result) ";
			//  echo $query;echo "<br>"; exit;
			$result = mysql_query($query,$connection) or die(mysql_error($connection));
		
			$query1 = " select @result from dual ";
			$result1 = mysql_query($query1,$connection) or die(mysql_error());
			$cur1 = mysql_fetch_row($result1);
			$result = $cur1[0];
			
			//$result = $result[0];
			//echo $query; exit;
			//echo 'error='.$result; exit;
			
			if ($result == 1){ 
				fcommit();
				
				$query   = " SELECT Trans_Reference, Costcent_code, Project_Code FROM Trans WHERE Trans_id = $STransId ";
				$result  = selectData($connection, $query); 
				$vTransRef  = $result[0];
				$vCostCentCode = $result[1];
				$vProjectCode  = $result[2];
						//$vTransRef != '' &&
				
				$existCode = 0;
				if ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $vTransRef != ''){
					$querychk = "select 1 from sequence where '$vOldCostCentCode' like Concat(Sequence.CostCenter,'%') and '$txtCostCentCode' like Concat(Sequence.CostCenter,'%') ";
					$reschk = mysql_query($querychk, $connection);
					$rwchk = mysql_fetch_row($reschk);
					$existCode = $rwchk[0];
				}
				if ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $vTransRef != ''){
					$querychk = "select 1 from sequence where '$vOldProjCode' like Concat(Sequence.Project,'%') and '$txtProjectCode' like Concat(Sequence.Project,'%') ";
					$reschk = mysql_query($querychk, $connection);
					$rwchk = mysql_fetch_row($reschk);
					$existCode = $rwchk[0];
				}	
				
				if (($vTransRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $existCode == 0) ||
				     ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $existCode == 0)) || 
					 ($Module_ReferenceByBelongsToGroup == 1 && $vTransRef == '') ) {
						 
					if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
					else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
					else $vProjCostCent = '';
								
					if ($TransType == 'PV') 	 $RefField = 'Payment_RefGovernment';
					else if ($TransType == 'RV') $RefField = 'Receipt_RefGovernment';
					else if ($TransType == 'DV') $RefField = 'Dbtnote_RefGovernment';
					else if ($TransType == 'CV') $RefField = 'Crdnote_RefGovernment';
					else if ($TransType == 'CT') $RefField = 'Contra_RefGovernment';
						
					fbegin();
					if ($Module_ReferenceByBelongsToGroup == 1)
						$vTransRef = get_nextsequence_belongsToGroup("'".insertMySQLDate($txtDate)."'",$RefField,$FI_BelongsToGrp,$connection);
					else $vTransRef = get_nextsequence($RefField,$vProjCostCent,$connection);	
					fcommit();
							
					$query = " UPDATE Trans SET ".
							 " Trans_Reference = $vTransRef ".
							 " WHERE Trans_id = $STransId ";
							
					if (!updateData($connection, $query, true)) 
						$message  = mysql_error();
					 
							if ($vTransRef != '' && $TransType == 'PV'){
								$queryacc = "SELECT distinct user_code, ifnull(nbrofdays,0), ifnull(view_access,0) FROM ".$_SESSION['dbLabel'].".notification_access
											where notification_name='PV_Created' and ifnull(view_access,0) = 1 ";
								$resacc = mysql_query($queryacc, $connection);
								while ($rwacc = mysql_fetch_array($resacc)){
									$querynot = "call sendNotification('PV_Created', '$rwacc[0]', $rwacc[1], $rwacc[2], $STransId, '') ";
									$resnot = mysql_query($querynot, $connection);
								}							
							}
							if ($vTransRef != '' && $TransType == 'RV'){
								$queryacc = "SELECT user_code, ifnull(nbrofdays,0), ifnull(view_access,0) FROM ".$_SESSION['dbLabel'].".notification_access
											where notification_name='RV_Created' and ifnull(view_access,0) = 1 ";
								$resacc = mysql_query($queryacc, $connection);
								while ($rwacc = mysql_fetch_array($resacc)){
									$querynot = "call sendNotification('RV_Created', '$rwacc[0]', $rwacc[1], $rwacc[2], $STransId, '') ";
									$resnot = mysql_query($querynot, $connection);
								}							
							}
					 
					 }
						
						if(  $Module_InvoiceGrid == 2 && $vTransRef != ''){
						$vMainCompanyName=explode('_',$_SESSION['dbName']);  
						$DirCompany  = $vMainCompanyName[0];
						preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
						$DirYear =  $DirYears[0][0];  
						
						$res_del = mysql_query($query_del,$connection);		
						$query_del = "delete from ".$_SESSION['dbLabel'].".alloclink where alloclink.transdt_id  in (select transdt_id from transdt 
									where trans_id = $STransId)  And upper(alloclink.Alloccomp) = upper('".$DirCompany."') And upper(alloclink.Allocyear) = upper('".$DirYear."') ";
						// echo $query_del; 
						$res_del = mysql_query($query_del,$connection);						
						$query_detaillink = "INSERT INTO ".$_SESSION['dbLabel'].".`alloclink`(`AllocLink_id`, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`,transtype,ledger_number)";
						$query_detaillink .= "select null, `AllocLink_date`, `journal_idD`, `journal_idC`, `currency_code`, `amount`, `amountbase1`, `amountbase2`, `AllocComp`, `AllocYear`, `allocRemark`, `trans_id`, `transdt_id`,`transtype`,`ledger_number` ".
								"from ".$_SESSION['dbLabel'].".temp_alloclink ".
								" WHERE Trans_id = $STransId ";
						 // echo $query_detaillink;echo "<br>";//exit;
						$res_detaillink = mysql_query($query_detaillink,$connection);
						
						$query_del = "delete from ".$_SESSION['dbLabel'].".temp_alloclink WHERE Trans_id = $STransId  And upper(temp_alloclink.Alloccomp) = upper('".$DirCompany."') And upper(temp_alloclink.Allocyear) = upper('".$DirYear."') ";
						 // echo $query_del; exit;
				}	 	$res_del = mysql_query($query_del,$connection);		
				//Set The CashType Reference
				if (($vTransCashRef == '' || $vTransCashCode != $txtCashType) && $txtCashType != '') {
						
					fbegin();
					$vTransCashRef = get_nextsequence_cashtype("'".insertMySQLDate($txtDate)."'",'CashType_Reference' , $txtCashType, $TransType ,$connection);	
					fcommit();
							
					$query = " UPDATE Trans SET ".
							 " Trans_CashReference = $vTransCashRef ".
							 " WHERE Trans_id = $STransId ";
							
					if (!updateData($connection, $query, true)) 
						$message  = mysql_error();
						
				}
				if($TransType == 'RV'){
					$query = "select ifnull(Trans_Confirmed,0) from trans where trans_id = $STransId;";
					$res = mysql_query($query,$connection);
					$rw = mysql_fetch_row($res);
					$Trans_Confirmed = $rw[0];
					if($Trans_Confirmed == 0){
						$up = "update trans set Trans_Confirmed = 1, Trans_UserConfirmed = '".$_SESSION['useraccount']."' where trans_id = $STransId;";
						$res = mysql_query($up,$connection);
					}
				}
				// If Module Post Trx Is False Then Create Reference and Jv, Else Reference and Jv Will Be Created When Posting Transactions.
				if (($ModulePostTrx == 0) || ($ModulePostTrx == 1 && $vTransPosted == 1)) {
					$message = Create_TransJv($STransId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
				}	
				 
			} else{
				//$message  = mysql_error(); 
				$message  = 'Error In CopyData_TempTrans Function.'; 
				frollback();
			}
			if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$STransId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'trans', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
			
		} else{
			$message  = mysql_error(); 
			frollback();
		}
		
	}
}


else if($mode == "convertInvoiceAmount" && $mainmode == ''){
	$Amount = $_GET['Amount'];
	$base = $_GET['base'];
	$invoiceDate = $_GET['invoiceDate'];
	$invoiceDate = explode('-',$invoiceDate);
	$invoiceDate2 = $invoiceDate[2].'-'.$invoiceDate[1].'-'.$invoiceDate[0];
	if($base == '1')
	$vAmount    = ConvertCurrency($base1, $base2, $invoiceDate2, $Amount, $connection); 
	else if($base == '2')
	$vAmount    = ConvertCurrency($base2, $base1, $invoiceDate2, $Amount, $connection); 
	echo $vAmount;
	exit;
}
else if($mode == "fillCstPrj" && $PTransId != ''){
	$vLedgerNo    = $txtLedgerNo;
	
	if ($Module_Project == 1 || $Module_CostCenter == 1 || $Module_ProjectDt == 1 || $Module_CostCenterDt == 1) {
		$vCstJourDtPer   = 100;

		$vProjectCodeDt	 = GetSQLValueString($PTransProjectCode,'text');
		$vCostCentCodeDt = GetSQLValueString($PTransCostCentCode,'text');
		
		//Case Header Project or Costcenter Is Not Empty Automatically Insert Into CstjourDt	
		if ($PTransProjectCode != '' || $PTransCostCentCode != '' ) {
		
			$headquery = "Select transdt_id as vTransDtId, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, Ledger_Number as vLedgerNo from temp_transdt where trans_id = '$PTransId'";
			$headresult = mysql_query($headquery,$connection);
			while($row = mysql_fetch_array($headresult)){
			
				extract($row);

				if ($Ledger_ValidateProject == 1) {
					$sub_query = " Select Project_Code, CostCenter_code From Ledger Where Ledger_Number = '".$vLedgerNo."'";
					$sub_result = selectData($connection, $sub_query);
					
					if ($sub_result[0] != '') $PTransProjectCode = $sub_result[0];
					if ($sub_result[1] != '') $PTransCostCentCode = $sub_result[1];
				} 

				$subquery = " Select Project_Code, CostCenter_Code from temp_cstjourdt where TransDt_Id = '$vTransDtId'";
				$subresult = selectData($connection, $subquery);
				if($subresult[0] == '' && $subresult[1] == ''){
					
					$vCstJourDtAmt   = $Transdt_Amount;
					$vCstJourDtAmt1  = $Transdt_Amount1;
					$vCstJourDtAmt2  = $Transdt_Amount2;

					$query = " INSERT INTO temp_cstjourdt (TransDt_Id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, CstJourDt_Amount1, CstJourDt_Amount2, ".
							" Synchronized, User_Account, Logged_Code ) ". 
							" VALUES ( ".$vTransDtId.", $vProjectCodeDt, $vCostCentCodeDt, $vCstJourDtPer, $vCstJourDtAmt, $vCstJourDtAmt1, $vCstJourDtAmt2, ".
							"          0, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."'	) ";
					//$message = $query;		 
					//echo $query."<br>";exit;				
					$result=mysql_query($query,$connection);
					if(!$result){
						echo"QueryErr";
						exit;
					}
				}
			}
			echo "Project Code/Costcent Filled";
			exit;
		}
		echo "Error: Empty Project/ Costcent";
		exit;
	}
	echo "ModuleErr";
	exit;
}
/*
$message = ereg_replace(' ','%20',$message);
$WarningMsg = ereg_replace(' ','%20',$WarningMsg);

$PTransManualNo   = ereg_replace(' ','%20',$PTransManualNo);
$PTransProjectCode = ereg_replace(' ','%20',$PTransProjectCode);
$PTransCostCentCode = ereg_replace(' ','%20',$PTransCostCentCode);
$PTransRemark = ereg_replace(' ','%20',$PTransRemark);
$PTransRepresent = ereg_replace(' ','%20',$PTransRepresent);
*/

$message   = ReplaceHtmlChars($message);
$PTransRemark   = ReplaceHtmlChars($PTransRemark);
$PTransRepresent = ReplaceHtmlChars($PTransRepresent);
$PTransProjectCode = ReplaceHtmlChars($PTransProjectCode);
$PTransCostCentCode = ReplaceHtmlChars($PTransCostCentCode);

//echo $mode.$message; exit;

if($mode == "post") {
	if ($AllowSave == 1)
		//header ("Location: ./Form_Trans.php?TransType=".$TransType."&message=".$message);
		header ("Location: ./Form_Trans.php?txtCashType=".$txtCashType."&TransType=".$TransType."&CashBank=".$CashBank."&actionmode=".$mode."&mainaction=".$mainmode."&PrTransId=".$STransId."&PrTransRef=".$vTransRef."&message=".$message);
	else
		header ("Location: ./Form_Trans.php?TransType=".$TransType."&CashBank=".$CashBank."&actionmode=submitrecord&mainaction=".$mainmode."&ErrorRecId=".$ErrorRecId."&txtTransId=".$STransId."&message=".$message);
}	
else if ($mode == "" && ($mainmode == "delete" || $mainmode == 'ConfirmTrans'))	
	header ("Location: ./Form_TransSearch.php?TransType=".$TransType."&CashBank=".$CashBank."&message=".$message);

else if ($mode == "cancel" )		
	header ("Location: ./Form_Trans.php?TransType=".$TransType."&CashBank=".$CashBank."&message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_TransSearchPending.php?TransType=".$TransType."&CashBank=".$CashBank."&message=".$message);
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_Trans.php?TransType=".$TransType."&actionmode=".$mode."&mainaction=".$mainmode."&txtTransId=".$STransId."&message=".$message);	
else if ($mode == "editdt")		
	header ("Location: ./Form_TransDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PTransId=".$STransId."&PTransType=".$TransType."&PTransDate=".$PTransDate."&PTransDtType=".$PTransDtType."&PTransDtId=".$PTransDtId."&PAccountType=".$PAccountType."&message=".$message);
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_TransSearch.php?TransType=".$TransType."&PMode=1&message=".$message);	
else if ($mode == "" && $mainmode == "posttrx")		
	header ("Location: ./Form_TransSearchUnPosted.php?TransType=".$TransType."&message=".$message);
else if ($mode == "" && $mainmode == "searchunposted")		
	header ("Location: ./Form_TransSearchUnPosted.php?TransType=".$TransType."&PMode=1&message=".$message);
else if ($mode == "" && $mainmode == "loadrequest" ){
	if ($message != "")
		header ("Location: ./Form_TransSearchRequests.php?TransType=".$TransType."&PMode=0&message=".$message);
	else	
		header ("Location: ./Form_TransSearchRequests.php?TransType=".$TransType."&PMode=1&TransId=".$STransId."&message=".$message);
}	
else if ($mode == "" && $mainmode == "loadsorder" ){
	if ($message != "")
		header ("Location: ./Form_TransSearchSorder.php?TransType=".$TransType."&PMode=0&message=".$message);
	else	
		header ("Location: ./Form_TransSearchSorder.php?TransType=".$TransType."&PMode=1&TransId=".$STransId."&message=".$message);
}
/*else if ($mode == "insertcstjour" || $mode == "editcstjour" || $mode == "deletecstjour" )		
	header ("Location: ./Form_Trans_CstJour.php?PTransType=".$TransType."&actionmode=".$mode."&mainaction=".$mainmode."&PTransId=".$STransId."&PTransDtId=".$STransDtId."&PTransDtCurr=".$PTransDtCurr."&message=".$message);	
else if ($mode == "insertchkjour" || $mode == "editchkjour" || $mode == "deletechkjour" )		
	header ("Location: ./Form_Trans_ChkJour.php?PTransType=".$TransType."&actionmode=".$mode."&mainaction=".$mainmode."&PTransId=".$STransId."&PTransDtId=".$STransDtId."&PTransDtCurr=".$PTransDtCurr."&message=".$message);	
else if ($mode == "insertbilljour" || $mode == "editbilljour" || $mode == "deletebilljour" )		
	header ("Location: ./Form_Trans_BillJour.php?PTransType=".$TransType."&actionmode=".$mode."&mainaction=".$mainmode."&PTransId=".$STransId."&PTransDtId=".$STransDtId."&PTransDtCurr=".$PTransDtCurr."&message=".$message);

else if ($mode == "insertinvoice" || $mode == "editinvoice" || $mode == "deleteinvoice" || $mode == "deleteinvoice2" )		
	header ("Location: ./Form_Trans_Invoices.php?PTransType=".$TransType."&actionmode=".$mode."&mainaction=".$mainmode."&PTransId=".$STransId."&PTransDtId=".$STransDtId."&PTransDtCurr=".$PTransDtCurr."&message=".$message);
*/
else if ($mode == "loadinvoices" || $mode == "loadinvoices2")
	header ("Location: ./Form_Trans_ListInvoices.php?PTransType=".$TransType."&PMode=1&actionmode=".$mode."&mainaction=".$mainmode."&PTransId=".$STransId."&PTransDtId=".$STransDtId."&PTransDtCurr=".$PTransDtCurr."&message=".$message);
else if ($mode == "loadinvoices3"   )
	header ("Location: ./Form_Trans_ListInvoicesLive1.php?PMode=1");
else if ( $mode == "unallocateSup" )
	header ("Location: ./Form_ADvancedPaymentAllocation1.php?fromledger=$SendLedger_number");
 
else if ($mode == "changecurrency")	
	header ("Location: ./Form_Trans.php?TransType=".$TransType."&CashBank=".$CashBank."&txtTransId=".$STransId."&message=".$message);
else if ($mode == "submitrecord" ){
    header ("Location: ./Form_TransDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PTransDtType=".$PTransDtType."&PTransId=".$STransId."&PTransType=".$TransType."&PAccountType=".$PAccountType.	
			"&PTransDate=".$PTransDate."&PTransCurr=".$PTransCurr."&PTransCashType=".$PTransCashType."&PTransManualNo=".$PTransManualNo.
			"&PTransProjectCode=".$PTransProjectCode."&PTransCostCentCode=".$PTransCostCentCode."&PTransRepresent=".$PTransRepresent."&PTransRemark=".$PTransRemark.
			"&message=".$message);
}	
		
/*
print <<<HERE
</form>
</body>

HERE;
*/

if($Module_InvoiceGrid == 2 && $ModuleInvoiceGrid == 1 && ($mode == "submitrecord" || $mode == "submitrecord-ajax" || $mode == "editdt" || $mode == "editdt-ajax") && $STransId != "" && $STransDtId != ""){
	$sub_query = " Select 1 ".
				 " From Temp_TransDt As TransDt ".
				" Where TransDt.TransDt_ID = '".$STransDtId."' 
				and exists (select 1 from LedgerInvoice where TransDt.Ledger_Number like concat(LedgerInvoice.Ledger_Number,'%'))";
				//echo"<br>".$sub_query;exit;
	$sub_res = mysql_query($sub_query,$connection);
	$numrow = mysql_num_rows($sub_res);
	if($numrow>0){ 
		$openInvoice = 1;
		
	}
}
else $openInvoice=0;

if(($mode == "deletedt" || $mode == "submitrecord" || $mode == "submitrecord-ajax" || $mode == "editdt" || $mode == "editdt-ajax") && $STransId != "" && $STransDtId != ""){
	$sub_query = " Select Sum(if(temp_transdt.currency_code = '".$base1."', ifNull(Transdt_Amount1,0), ".
				 " if(temp_transdt.currency_code = '".$base2."', ifNull(Transdt_Amount2,0), ".
				 " ifNull(convertcurfunc(temp_transdt.currency_code, temp_trans.currency_code, temp_trans.trans_date, 0, 0, '', '', ifNull(Transdt_Amount,0)),0)))) As TotalAmount ".
				 " From Temp_TransDt ".
				 " inner join temp_trans on temp_trans.Trans_ID = temp_transdt.Trans_ID ".
				 " Where temp_transdt.Trans_ID = '".$STransId."' ".
				 " And TransDt_dbcd = '".$Type_dbcd1."'";
				 
				// echo $sub_query;
	$sub_result = selectData($connection, $sub_query);
	if (empty($sub_result[0])) $sub_result[0] = 0;
	$txtTotalAmount = number_format($sub_result[0],$DecimalBase);
}
		
$return_arr = array();

$row_array['message'] = $message;
$row_array['transid'] = $STransId;
$row_array['totalAmount'] = $txtTotalAmount;
$row_array['openInvoice'] = $openInvoice;
$row_array['STransDtId'] = $STransDtId; 
		
array_push($return_arr,$row_array);
echo json_encode($return_arr);


?>