/**
 * Copyright (c) 2009 Penril Datability (SEA) Sdn Bhd All rights reserved.
 *
 * This software is copyrighted. Under the copyright laws, this software
 * may not be copied, in whole or in part, without prior written consent
 * of Penril Datability (SEA) Sdn Bhd or its assignees. This software is
 * provided under the terms of a license between Penril Datability (SEA)
 * Sdn Bhd and the recipient, and its use is subject to the terms of that
 * license.
 */

package my.com.kfh.enterprise.services.ib104_fundtransfer.ftt;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.LinkedHashMap;
import java.util.Map;

import my.com.kfh.enterprise.services.GenericESBServicesImpl;
import my.com.kfh.enterprise.services.IBEnterpriseServices;
import my.com.kfh.enterprise.services.IBEnterpriseServicesWorkspace;
import my.com.kfh.enterprise.services.IBUtils;
import my.com.kfh.enterprise.services.IBUtilsOnlineAcc;
import my.com.kfh.enterprise.services.ib101_access.AccessConstants;
import my.com.kfh.enterprise.services.ib101_access.IBAccessDBUtils;
import my.com.kfh.enterprise.services.ib104_fundtransfer.constant.FTTConstants;
import my.com.kfh.enterprise.services.ib104_fundtransfer.others.IBStdDailyLimitBaseServices;
import my.com.kfh.enterprise.services.ib104_fundtransfer.thirdparty.IBFundTransferDBUtils;
import my.com.kfh.enterprise.services.ib104_fundtransfer.thirdparty.ThirdPartyTransferTags;
import my.com.kfh.enterprise.services.ib112_si.IBGenericSIServices;
import my.com.kfh.enterprise.services.ib112_si.SIConstants;
import my.com.kfh.enterprise.services.ib112_si.SIDBUtils;
import my.com.kfh.enterprise.services.ib112_si.SI_PAYMENT_MODE;
import my.com.kfh.enterprise.services.ib116_online_acc.constant.OnlineAccConstants;
import my.com.kfh.error.exception.IBBusinessException;
import my.com.kfh.error.exception.IBGenericException;
import my.com.kfh.error.exception.IBServiceException;
import my.com.kfh.error.handler.CommonErrorCode;
import my.com.kfh.error.handler.IBErrorHandler;
import my.com.kfh.esb.response.ESBAccountEnquiryTC100Bean;
import my.com.kfh.esb.response.ESBFttTransferBean;
import my.com.kfh.esb.response.ESBRimRetrieveProfileBean;
import my.com.kfh.esb.response.ESBTransferGLtoCASABean;
import my.com.kfh.esb.response.ESBTransferToGLBean;
import my.com.kfh.hibernate.utils.HibernateOnlineAccUtils;
import my.com.kfh.integration.OnlineAccPromoBean;
import my.com.kfh.sms.services.SMSConstants;
import my.com.kfh.sms.services.SMSServices;
import my.com.kfh.web.utils.BVI_DateTime;
import my.com.kfh.web.utils.DataValidator;
import my.com.kfh.web.utils.DateTimeUtils;
import my.com.kfh.web.utils.FormatterUtils;
import my.com.kfh.web.utils.GSTUtils;
import my.com.kfh.web.utils.IBLoadProperty;
import my.com.kfh.web.utils.IBLogWriter;
import my.com.kfh.web.utils.IBLogger;
import my.com.kfh.web.utils.IBOfacBlackList;
import my.com.kfh.web.utils.IBSessionObjects;
import my.com.kfh.web.utils.IBTimer;
import my.com.kfh.web.utils.ResourcesUtils;
import my.com.kfh.web.utils.constant.ESBConstants;
import my.com.kfh.web.utils.constant.LogTables;
import my.com.kfh.web.utils.constant.ServiceInfo;

import com.broadvision.data.client.DataManager;
import com.broadvision.data.common.TableData;

/**
 * <pre>
 * PROGRAMMER: Chang Giat Yeng
 * CHANGE-NO:
 * TASK-NO:
 * DATE CREATED: Apr 7, 2010
 * TAG AS:
 * REASON(S):
 * MODIFICATION:
 * </pre>
 */

/**
 * <Class description>
 */
public class IBFttSIResultsServices extends IBGenericFttServices
{
	private static Class c_oClass = IBFttSIResultsServices.class;

	/**
	 * @ Class constructor specifying session object.
	 *
	 * @param p_oIBSessionObjects Session object contains all information stored in HTTP session
	 */
	public IBFttSIResultsServices (IBSessionObjects m_oIBSessionObjects)
	{
		super (m_oIBSessionObjects);
	}

	/**
	 * Execute from scheduler
	 *
	 * @param siId SI Transaction ID
	 * @throws IBGenericException
	 */
	@SuppressWarnings("unchecked")
	public static void executeTransaction (String siId) throws IBGenericException
	{
		String m_sMethodName = "executeTransaction";
		IBTimer m_oTimer = IBLogger.logBSFNMethodEnteringMessage (c_oClass, m_sMethodName, String.class.getName ());

		String m_sCharges = "0";
		String m_sGSTCharges = "0";
		String m_sSICharges = "0";
		String m_sSIChargesRefNo = null;
		boolean m_boSIChargeStatus = false;
		String m_sSIGSTCharges = "0";
		String m_sSIGSTChargesRefNo = null;
		boolean m_boSIGSTChargeStatus = false;
		String m_sSIChargesRevertRefNo = null;
		boolean m_boSIChargeRevertStatus = false;
		double m_dAvailableBal = 0.0;
		double m_dTransferAmount = 0.0;
		double m_dTotalAmount = 0.0;
		double m_dSICharges = 0.0;
		double m_dCharges = 0.0;
		double m_dGSTCharges = 0.0;
		String m_sSIChargeResponseCode = null;
		boolean m_boIsFundSufficient = true;
		boolean m_bChargeStatus = false;
		String m_sChargesRefNo ="";

		String m_sActualStatus = null;
		String m_sStatus = ResourcesUtils.getUnsuccessful ();
		String m_sReason="";

		boolean m_boIsResultSuccessful = false;
		String m_sEsbDescription = null;
		String m_sChargeDescription = null;
		String m_sGSTChargeDescription = null;
		String m_sPhoenixReference = "";
		String m_sBalance = "";
		StringBuffer m_sFileContent = null;
		String m_sDebitedLocalAmount = null;
		String m_sLocalAmount = "";

		String m_sBranchCode = null;
		String m_sBranchName = null;

		long m_sUserId = 0;
		Float m_fNonResLimit= null;
		String residencyType = "";
		String SIGSTCharges = "0";

		//#-- added by pixa 20121017 start
		OnlineAccPromoBean onlineAccTrnxPromoBean=null;	
		OnlineAccPromoBean onlineAccSIPromoBean=null;
		//#-- added by pixa 20121017 end 
		
		try
		{
			BVI_DateTime m_oDate = new BVI_DateTime ();
			String m_sDate = DateTimeUtils.formatDayMonthYear (m_oDate);
			String m_sTime = m_oDate.getTime ();

			//mock up
			IBSessionObjects m_oSessionObj = mock(IBSessionObjects.class);
			when(m_oSessionObj.getDataManager()).thenReturn(new DataManager());
			when(m_oSessionObj.getRemoteIPAddress ()).thenReturn("127.0.0.1");

			String m_sTrnxID = IBUtils.getTransactionId (m_oSessionObj.getDataManager ());

			IBEnterpriseServices p_oEnterpriseServices = new IBEnterpriseServicesWorkspace(m_oSessionObj);

			TableData table = SIDBUtils.getSICurrentTransId (p_oEnterpriseServices, siId);
			String currentTrnxId  = table.getStringValue(0, LogTables.IB_SI.CURRENT_TRNX_ID.toString ());
			String siPaymentModeCode = table.getStringValue(0, LogTables.IB_SI.PAYMENT_MODE.toString ());
			String trnxTypeDisplay = table.getStringValue(0, LogTables.IB_SI.TRNX_TYPE.toString ());
			String m_sSIServiceCode = table.getStringValue (0, LogTables.IB_SI.SERVICE_CODE.toString ());


			m_sEsbDescription = ESBConstants.FUND_TRANSFER_FTT;
			m_sEsbDescription = IBGenericSIServices.getESBDescription (m_sEsbDescription, siPaymentModeCode);

			m_sChargeDescription = ESBConstants.FTT_CHARGES;
			m_sGSTChargeDescription = ESBConstants.FTT_GST_CHARGES;
			m_sChargeDescription = IBGenericSIServices.getESBDescription (m_sChargeDescription, siPaymentModeCode);
			m_sGSTChargeDescription = IBGenericSIServices.getESBDescription (m_sGSTChargeDescription, siPaymentModeCode);

			GenericESBServicesImpl m_oEsbServices = new GenericESBServicesImpl (m_oSessionObj);

			//get user id from trnx
			table = FTTDBUtils.getTransactionByTrnxId(p_oEnterpriseServices, currentTrnxId);
			String userId = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.USER_ID.toString ());
        	residencyType = IBUtils.getResidencyType(p_oEnterpriseServices, Long.parseLong(userId)); 
        	
			com.broadvision.visitor.client.Visitor visitor = mock(com.broadvision.visitor.client.Visitor.class);
			when(visitor.getId()).thenReturn(Long.parseLong(userId));
			when(m_oSessionObj.getVisitor()).thenReturn(visitor);

			//get various data from transaction
			String m_sFromAccount = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.FROM_ACCOUNT_NO.toString ());
			String m_sToAccount = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_ACC_NO.toString ());
			m_sLocalAmount = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.LOCAL_AMOUNT.toString ());
			String fromCurrency = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.FROM_CURRENCY.toString ());
			String toCurrency = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.TO_CURRENCY.toString ());
			m_sCharges = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.CHARGES.toString ());
			m_sGSTCharges = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.GST_CHARGES.toString ());


			//get user rim no
			String rimNo = IBAccessDBUtils.getRimNoByUserId(p_oEnterpriseServices, userId);
			when(m_oSessionObj.getHttpSessionAttrObject (AccessConstants.RIM_NO)).thenReturn(rimNo);

			String m_sTermsDeclaration=table.getStringValue(0, LogTables.IB_FTT_TRANSFER.OTHER1.toString ());
			String m_sFttCountry = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.FTT_COUNTRY.toString ());
			String m_sTransactionDesc = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.DESCRIPTION.toString ());
			String m_sToCurrencyCode = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.TO_CURRENCY.toString ());
			String m_sSpecialBankCode = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.CURR_CONDITION_NO.toString ());
			String m_sForeignAmount = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.FOREIGN_AMOUNT.toString ());

			ESBRimRetrieveProfileBean m_oProfileBean =  m_oEsbServices.getProfile (rimNo);
			String m_sSenderName = m_oProfileBean.getLastName ();
			String m_sSenderAddress1 = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.SENDER_ADDRESS1.toString ());
			String m_sSenderAddress2 = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.SENDER_ADDRESS2.toString ());
			String m_sSenderPostcode = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.SENDER_POSTCODE.toString ());
			String m_sSenderCountry = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.SENDER_COUNTRY.toString ());
			String m_sSenderContact = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.SENDER_CONTACT.toString ());
			String m_sBeneficiaryName = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_NAME.toString ());
			String m_sBeneficiaryAddress1 = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_ADDRESS1.toString ());
			String m_sBeneficiaryAddress2 = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_ADDRESS2.toString ());
			String m_sBeneficiaryID = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_ID.toString ());
			String m_sBeneficiaryContact = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_CONTACT.toString ());
			String m_sBeneficiaryCountry = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_COUNTRY.toString ());
			String m_sBeneficiaryEmail = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_EMAIL.toString ());
			String m_sBeneficiaryBank = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_BANK.toString ());
			String m_sBeneficiaryAccountNo = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_ACC_NO.toString ());
			String m_sBeneficiaryBranch = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_BRANCH.toString ());
			String m_sBeneficiaryCity = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_CITY.toString ());
			String m_sEmail = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.BENEFICIARY_EMAIL.toString ());
			String senderName = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.SENDER_NAME.toString ());
			String otherPaymentDetails = table.getStringValue(0, LogTables.IB_FTT_TRANSFER.OTHER_PAYMENT_DETAILS.toString ());

			StringBuilder m_sbDesc = new StringBuilder();
			m_sbDesc.append ("TT Transfer to ");
			m_sbDesc.append (m_sBeneficiaryName);
			if(!DataValidator.isEmptyString (m_sBeneficiaryID))
			{
				m_sbDesc.append (" - ");
				m_sbDesc.append (m_sBeneficiaryID);
			}

			if(!DataValidator.isEmptyString (m_sCharges) && DataValidator.isValidNumber (m_sCharges))
			{
				m_dCharges = Double.parseDouble (DataValidator.isEmptyString (m_sCharges)?"0.0":m_sCharges);
			}

			if(!DataValidator.isEmptyString (m_sGSTCharges) && DataValidator.isValidNumber (m_sGSTCharges))
			{
				m_dGSTCharges = Double.parseDouble (DataValidator.isEmptyString (m_sGSTCharges)?"0.0":m_sGSTCharges);
			}

			/*
             * check blacklisted beneficiary name
             */
            if (IBFundTransferDBUtils.isNameBlacklisted (null, m_sBeneficiaryName))
			{
            	m_boIsResultSuccessful = false;
            	m_sActualStatus = IBOfacBlackList.BLACK_LISTED;

            	m_sStatus = ResourcesUtils.getUnsuccessful ();
            	m_sReason = ResourcesUtils.getBusinessExceptionErrorMessage (IBBusinessException.FTT_FUND_TRANSFER, FTTConstants.ERR_BLACKLISTED_BENE_NAME);
			}
            else
            {
				//check daily limit
				Map m_oSILimitMap = IBGenericSIServices.verifySIFttDailyLimitByBank (p_oEnterpriseServices, null, null,
					m_sSIServiceCode, m_sLocalAmount, m_oDate.getSimpleDate (), true, residencyType);
				
				Map m_oDailyLimitReturnMap = IBStdDailyLimitBaseServices.checkFttDailyLimit(p_oEnterpriseServices ,m_oDate.getSimpleDate (),
						m_sLocalAmount, residencyType , true , false);
				
				if ((!((Boolean) m_oDailyLimitReturnMap.get (ThirdPartyTransferTags.STATUS)).booleanValue ()))
 	            {
 	            	m_boIsResultSuccessful = false;
  
 	            	m_sStatus = ResourcesUtils.getUnsuccessful ();
 	            	m_sReason = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_BANK_STD_LIMIT,
 	                		new String [] { FormatterUtils.formatMoneyDisplay ((String) m_oDailyLimitReturnMap.get (ThirdPartyTransferTags.MAX_LIMIT),
 	                				fromCurrency, true) });	
 	            }
				else if (!((Boolean) m_oSILimitMap.get (SIConstants.TRANS_STATUS)).booleanValue ())
		        {
					m_boIsResultSuccessful = false;
					m_sStatus = ResourcesUtils.getUnsuccessful ();
					m_sReason = ResourcesUtils.getBusinessExceptionErrorMessage (IBBusinessException.SI,
		            		SIConstants.ERR_BANK_MAX_LIMIT,
		            		new String [] { FormatterUtils.formatMoneyDisplay ( (String)m_oSILimitMap.get (SIConstants.MAX_LIMIT),
		            				fromCurrency, true) });
		        }
				else
				{
					ESBAccountEnquiryTC100Bean m_oTCEnquiryBean = m_oEsbServices.getAccountDetailsTC100 (m_sFromAccount);
					if (!DataValidator.isEmptyString (m_oTCEnquiryBean.getAvailable_Bal ()))
					{
						m_dAvailableBal = Double.parseDouble (m_oTCEnquiryBean.getAvailable_Bal ());
					}


					if (SI_PAYMENT_MODE.RECURRING_PAYMENT.getCode ().equals (siPaymentModeCode))
					{
						m_dSICharges = IBGenericSIServices.getSICharges (ServiceInfo.SI_FEE_FTT);
						m_sSICharges = String.valueOf (m_dSICharges);

						//#-- added by pixa 20121017 start --remember to include import at top
		            	onlineAccSIPromoBean = IBUtilsOnlineAcc.getChargesIfIsOnlineAccount(m_oEsbServices,m_sFromAccount, OnlineAccConstants.SI);
		            	if(onlineAccSIPromoBean !=null){
		            		m_sSICharges = onlineAccSIPromoBean.getPromotionCharges();
		            		m_dSICharges = Double.valueOf(m_sSICharges);
		            	}
		            	System.out.println("SI Charges: " + m_sSICharges);
		            	//#-- added by pixa 20121017 end --
		            	
						if (m_dSICharges > 0)
						{
							if (m_dAvailableBal > m_dSICharges)
							{
								String m_sChargeGLAccount = IBGenericSIServices.getSICollectionAccountNo (m_sFromAccount);

								ESBTransferToGLBean m_oESBTransferToGLBean = m_oEsbServices.chargesTransfer (m_sFromAccount,
									m_sChargeGLAccount, m_sSICharges, ESBConstants.SI_CHARGES, null, senderName, m_sBeneficiaryName, m_sTransactionDesc, otherPaymentDetails);

								m_sSIChargeResponseCode = m_oESBTransferToGLBean.getResponseCode ();
								if (ESBConstants.IB_SUCCESS_RC.equalsIgnoreCase (m_sSIChargeResponseCode))
								{
									m_boSIChargeStatus = true;
									m_sSIChargesRefNo = m_oESBTransferToGLBean.getReferenceNo ();
									
									String SIGSTChargesRate = IBUtils.getGSTRate(new IBEnterpriseServicesWorkspace(m_oSessionObj), IBLoadProperty.getValue(GSTUtils.SI_CHARGES_CODE));
		    						SIGSTCharges = GSTUtils.gstAmount2Dec(m_sSICharges, SIGSTChargesRate);
		    						
		    						ESBTransferToGLBean m_oGSTESBTransferToGLBean = m_oEsbServices.chargesTransfer (m_sFromAccount,
		    								ResourcesUtils.getGLAccountResource ("gl.account.gst"), SIGSTCharges, ESBConstants.SI_GST_CHARGES, null, senderName, m_sBeneficiaryName, m_sTransactionDesc, otherPaymentDetails);
		    						
		    						String m_sSIGSTChargeResponseCode = m_oGSTESBTransferToGLBean.getResponseCode ();
			    					if (ESBConstants.IB_SUCCESS_RC.equalsIgnoreCase (m_sSIGSTChargeResponseCode)){
			    						m_boSIGSTChargeStatus = true;
			    						m_sSIGSTChargesRefNo = m_oGSTESBTransferToGLBean.getReferenceNo ();
			    					}else{
			    						m_boIsFundSufficient = false;
										m_boIsResultSuccessful = false;
										m_sStatus = ResourcesUtils.getUnsuccessful ();
										m_sReason = m_oGSTESBTransferToGLBean.getErrorMessage ();
			    						
			    						ESBTransferGLtoCASABean m_oESBTransferGLtoCASABean = m_oEsbServices.transferGLtoCASA(m_sChargeGLAccount, m_sFromAccount, m_sSICharges, ESBConstants.SI_CHARGES_REVERT, null, m_sBeneficiaryName, otherPaymentDetails);
			    						
			    						String m_sSIGSTRevertChargeResponseCode = m_oESBTransferGLtoCASABean.getResponseCode ();
			    						if (ESBConstants.IB_SUCCESS_RC.equalsIgnoreCase (m_sSIGSTRevertChargeResponseCode)){
			    							m_boSIChargeRevertStatus = true;
			    							m_sSIChargesRevertRefNo = m_oESBTransferGLtoCASABean.getReferenceNo();
								}
			    					}
								}
								else
								{
									m_boIsFundSufficient = false;
									m_boIsResultSuccessful = false;
									m_sStatus = ResourcesUtils.getUnsuccessful ();
									m_sReason = m_oESBTransferToGLBean.getErrorMessage ();
								}
							}
							else
							{
								m_boIsFundSufficient = false;
								m_boIsResultSuccessful = false;
								m_sStatus = ResourcesUtils.getUnsuccessful ();
								m_sReason = ResourcesUtils.getApplicationResourceMessage (SIConstants.RESOURCES_INSUFFICIENT_FUND);
							}
						}
					}

					if (m_boIsFundSufficient)
					{
						m_dTransferAmount = Double.parseDouble (m_sLocalAmount);
						m_dTotalAmount = m_dTransferAmount + m_dSICharges + m_dCharges + Double.parseDouble(SIGSTCharges) + m_dGSTCharges;

						if(m_dAvailableBal < m_dTotalAmount)
						{
							m_boIsFundSufficient = false;
							m_boIsResultSuccessful = false;
							m_sStatus = ResourcesUtils.getUnsuccessful ();
							m_sReason = ResourcesUtils.getApplicationResourceMessage (SIConstants.RESOURCES_INSUFFICIENT_FUND);
						}
					}

					if (m_boIsFundSufficient)
					{
						//process FTT transfer through phoenix
						ESBFttTransferBean m_oESBFttTransferBean = m_oEsbServices.foreignFundTransfer (m_sFromAccount, m_sToCurrencyCode,
								m_sForeignAmount, m_sCharges, m_sGSTCharges, m_sEsbDescription, null, m_sChargeDescription, m_sGSTChargeDescription,  senderName, m_sBeneficiaryName, m_sTransactionDesc, otherPaymentDetails);

						//calculate charges through phoenix
						String m_sChargesResponseCode = m_oESBFttTransferBean.getChargesResponseCode ();
						m_bChargeStatus = m_oESBFttTransferBean.getChargesStatus ();

						if (ESBConstants.IB_SUCCESS_RC.equals (m_sChargesResponseCode))
						{
							String m_sChargesFromAccBalance = m_oESBFttTransferBean.getChargesFromAccountBalance ();
							m_sChargesRefNo = m_oESBFttTransferBean.getChargesReferenceNo ();

							//get FTT response code from Phoenix
							String m_sResponseCode = m_oESBFttTransferBean.getFttResponseCode ();
							boolean m_bFTTStatus = m_oESBFttTransferBean.getFttStatus ();
							if (ESBConstants.IB_SUCCESS_RC.equalsIgnoreCase (m_sResponseCode))
							{
								m_sStatus = ResourcesUtils.getAccepted ();
								m_boIsResultSuccessful = true;
								m_sBalance = m_oESBFttTransferBean.getFttFromAccountBalance ();
								m_sPhoenixReference = m_oESBFttTransferBean.getFttReferenceNo ();
								m_sDebitedLocalAmount = m_oESBFttTransferBean.getFttLocalAmount ();

								if(!DataValidator.isEmptyString (m_sPhoenixReference))
								{
									String m_sRefNoLabel = ResourcesUtils.getApplicationResourceMessage ("general.reference.number.short"); //(Ref No : )
									m_sbDesc.append ("<br>").append ("(").append (m_sRefNoLabel).append (":").append (m_sPhoenixReference).append (")");
								}

								m_sFileContent  = new StringBuffer ();
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.terms")).append (" : ").append (m_sTermsDeclaration).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.country")).append (" : ").append (m_sFttCountry).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.description")).append (" : ").append (m_sTransactionDesc).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.other.payment.details")).append (" : ").append (otherPaymentDetails).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.currency")).append (" : ").append (m_sToCurrencyCode).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.foreign.amount")).append (" : ").append (m_sForeignAmount).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("general.fromAccount")).append (" : ").append (m_sFromAccount).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.sender.name")).append (" : ").append (senderName).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.sender.address1")).append (" : ").append (m_sSenderAddress1).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.sender.address2")).append (" : ").append (m_sSenderAddress2).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.sender.postcode")).append (" : ").append (m_sSenderPostcode).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.sender.country")).append (" : ").append (m_sSenderCountry).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.sender.contact")).append (" : ").append (m_sSenderContact).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryName")).append (" : ").append (m_sBeneficiaryName).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryAddress1")).append (" : ").append (m_sBeneficiaryAddress1).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryAddress2")).append (" : ").append (m_sBeneficiaryAddress2).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryCountry")).append (" : ").append (m_sBeneficiaryCountry).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryID")).append (" : ").append (m_sBeneficiaryID).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryContact")).append (" : ").append (m_sBeneficiaryContact).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryEmail")).append (" : ").append (m_sBeneficiaryEmail).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryBank")).append (" : ").append (m_sBeneficiaryBank).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiary.bank.code.swift")).append (" : ").append (m_sSpecialBankCode).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryAccountNo")).append (" : ").append (m_sBeneficiaryAccountNo).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryBranch")).append (" : ").append (m_sBeneficiaryBranch).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryCity")).append (" : ").append (m_sBeneficiaryCity).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("general.reference.number")).append (" : ").append (FormatterUtils.formatTransID (m_sTrnxID)).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("general.reference")).append (" : ").append (m_sPhoenixReference).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("general.transaction.date")).append (" : ").append (m_sDate).append ("\n");
								m_sFileContent.append (ResourcesUtils.getApplicationResourceMessage ("general.transaction.time")).append (" : ").append (m_sTime);

								//send email to beneficiary
								if (!DataValidator.isEmptyString (m_sEmail))
								{
									/*
									 * email transfer notification to recipient
									 */
									String m_sSubject = ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.bene.email.subject");
									String m_sCustomerName = IBAccessDBUtils.getLastNameByUserId(p_oEnterpriseServices, userId);

									StringBuffer m_sbEmailMsg = new StringBuffer ();
									m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.bene.email.greetCustomer", new String [] {m_sSubject, m_sBeneficiaryName} ));
									m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.bene.email.note1",
											new String [] {m_sCustomerName, m_sDate.concat (" ").concat (m_sTime) } ));

									IBLogWriter m_oTableCreater = new IBLogWriter();
									m_sbEmailMsg.append (m_oTableCreater.RowCreater ("S", ResourcesUtils.getApplicationResourceMessage ("general.status"), m_sStatus, null, null)).append("\n");
									m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("general.amount"), FormatterUtils.formatMoneyDisplay(m_sForeignAmount, m_sToCurrencyCode, true), null, null)).append("\n");
									m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("general.reference.number"), FormatterUtils.formatTransID (m_sTrnxID), null, null)).append("\n");
									if(!DataValidator.isEmptyString (m_sPhoenixReference))
									{
										m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("general.reference"), m_sPhoenixReference, null, null)).append("\n");
									}
									m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.description"),
											DataValidator.isEmptyString (m_sTransactionDesc) ? "-" : m_sTransactionDesc, null, null)).append("\n");
			                    	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("ib104.other.payment.details"),
			                    			DataValidator.isEmptyString (otherPaymentDetails) ? "-" : otherPaymentDetails, null, null)).append("\n");
									m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.bene.email.country"), m_sBeneficiaryCountry, null, null)).append("\n");
									m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.bene.email.bankname"), m_sBeneficiaryBank, null, null)).append("\n");
									m_sbEmailMsg.append (m_oTableCreater.RowCreater ("E", ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.bene.email.bankcity"), m_sBeneficiaryCity, null, null)).append("\n");

									m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.bene.email.note2"));
									m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.bene.email.disclaimer"));

									IBUtils.sendEmail (p_oEnterpriseServices, null, m_sEmail, m_sSubject, m_sbEmailMsg.toString (), m_sStatus, null);
								}
							}
							else//FTT failed, display ftt error message and response code
							{
								m_sBalance = m_sChargesFromAccBalance;
								m_sStatus = ResourcesUtils.getUnsuccessful ();
								m_sReason = m_oESBFttTransferBean.getFttErrorMessage ();
							}
						}
						else //FTT charges failed, display charges error message and response code
						{
							m_sStatus = ResourcesUtils.getUnsuccessful ();
							m_sReason = m_oESBFttTransferBean.getChargesErrorMessage ();
						}
					}

				}
            }
			//Print receipt
			if(m_boIsResultSuccessful)
			{
				Map<String, String> m_oReceiptDetails = new LinkedHashMap <String, String> ();
				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("receipt.transaction.type"), trnxTypeDisplay);
				m_oReceiptDetails.put(ResourcesUtils.getApplicationResourceMessage("ib104.transfer.ftt.sender.name"), senderName);
				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryName"), m_sBeneficiaryName);
				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("general.status"), m_sStatus);
				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.beneficiaryAccountNo"), m_sBeneficiaryAccountNo);
				m_oReceiptDetails.put(ResourcesUtils.getApplicationResourceMessage("ib104.transfer.ftt.description"), m_sTransactionDesc);
				m_oReceiptDetails.put(ResourcesUtils.getApplicationResourceMessage("ib104.other.payment.details"), otherPaymentDetails);
				//				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.local.amount"), (String) m_oViewBean.get (FTTConstants.VBEAN_LOCAL_AMOUNT_DISPLAY));
				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.foreign.amount"),
						FormatterUtils.formatMoneyDisplay(m_sForeignAmount, toCurrency, true));
				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("ib104.transfer.ftt.charges"),
						FormatterUtils.formatMoneyDisplay(m_sCharges, null, true));
				
				 if(!DataValidator.isEmptyString(m_sGSTCharges) && !("0.00".equals(m_sGSTCharges)|| "0.0".equals(m_sGSTCharges)|| "0".equals(m_sGSTCharges)))
				{
				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("general.gst.charges"),
						FormatterUtils.formatMoneyDisplay(m_sGSTCharges, null, true));
				}
				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("general.reference.number"), FormatterUtils.formatTransID (m_sTrnxID));
				if(!DataValidator.isEmptyString (m_sPhoenixReference))
				{
					m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("general.reference"), m_sPhoenixReference );
				}
				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("general.transaction.date"), m_sDate );
				m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("general.transaction.time"), m_sTime);

				//Add KFH GST Account No
				 if(!DataValidator.isEmptyString(m_sGSTCharges) && !("0.00".equals(m_sGSTCharges)|| "0.0".equals(m_sGSTCharges)|| "0".equals(m_sGSTCharges)))
					m_oReceiptDetails.put (ResourcesUtils.getApplicationResourceMessage ("general.gst.id.no"), IBLoadProperty.getValue("gst.id.no") );
				
				//Insert into table IB_RECEIPT_DETAILS
				IBUtils.loopIntoReceiptDetails (p_oEnterpriseServices, m_oReceiptDetails, m_oDate.getSimpleDate (), m_sTrnxID);
				
				//#-- added by pixa 20121017 start
                if (onlineAccSIPromoBean !=null){
        	    	HibernateOnlineAccUtils.saveIBOnlineAccPromoTrnx(onlineAccSIPromoBean);
        	    }
            	onlineAccTrnxPromoBean = IBUtilsOnlineAcc.getChargesIfIsOnlineAccount(m_oEsbServices,m_sFromAccount, OnlineAccConstants.FTT);
            	if(onlineAccTrnxPromoBean !=null){
            		HibernateOnlineAccUtils.saveIBOnlineAccPromoTrnx(onlineAccTrnxPromoBean);
            	}
                //#-- added by pixa 20121017 end
			}

			//log into si history
			IBLogger.logSIHistory(p_oEnterpriseServices, rimNo, siId, m_sTrnxID, m_oDate.getJavaDate (),
					SIConstants.TRANSCODE_FTT_TRANSFER,
					m_sFromAccount, m_sToAccount, fromCurrency, toCurrency,
					DataValidator.isEmptyString(m_sDebitedLocalAmount)?m_sLocalAmount:m_sDebitedLocalAmount,
					m_sForeignAmount,
					String.valueOf (m_dCharges),
					m_sSICharges, // SICharges
					m_sStatus,
					m_sReason,
					m_sPhoenixReference,
					"", // PhxRevRefNo
					false, // PhxRevStatus
					"", // EpayRefNo
					m_sChargesRefNo, // PhxChargeRefNo
					m_bChargeStatus, // PhxChargeStatus
					"", // PhxChargeRevRefNo
					false, // PhxCharRevStatus
					m_sSIChargesRefNo, // SIChargeRefNo
					m_boSIChargeStatus,
					m_sSIChargesRevertRefNo, // SIChargeRevRefNo
					m_boSIChargeRevertStatus, // SIChargeRevStatus
					m_sSIServiceCode,
					m_boIsResultSuccessful,
					m_sSIGSTCharges, // SI GST Charges
					m_sGSTCharges, // Service GST Charges
					"", // SIGSTChargesRevertRefNo
					false); // SIGSTChargeRevertStatus


			if (m_boIsResultSuccessful)
			{
				m_sBranchCode = IBUtils.getBranchCodeByAccNo (m_sFromAccount);
				IBLogger.writeLog("branchCode: " + m_sBranchCode);

				if (!DataValidator.isEmptyString (m_sBranchCode))
				{
					m_sBranchName = IBUtils.getBranchNameByBranchCode (p_oEnterpriseServices, m_sBranchCode);
				}
				IBLogger.writeLog("m_sBranchName: " + m_sBranchName);
				String m_sFilename = FTTConstants.FTT_FILE_NAME + m_oDate.getSimpleDate () + m_sTrnxID + IBLogger.FILE_EXTENSION_TXT;
				IBLogger.writeLog("m_sFilename: " + m_sFilename);

				IBLogger.getFttFilePathAndEmail (p_oEnterpriseServices, m_sTrnxID, m_oDate, m_sFileContent, m_sFilename, m_sPhoenixReference);
				IBLogger.logFTTFileToRPTLIST (p_oEnterpriseServices, m_sTrnxID, m_oDate, m_sFilename,
						m_sBranchName, FTTConstants.FTT_APPL_TYPE);
			}
			
			//SMS Notification START
			SMSServices.sendCustomerSMSForSI (
					p_oEnterpriseServices, 
					userId, 
					m_sSIServiceCode, 
					SIConstants.TRANSCODE_FTT_TRANSFER, 
					m_sStatus, 
					m_sTrnxID, 
					m_sFromAccount, 
					DataValidator.isEmptyString(m_sDebitedLocalAmount)?m_sLocalAmount:m_sDebitedLocalAmount, 
					m_oDate,
					FormatterUtils.formatMoneyDisplay (m_sBalance, "", true),
					m_sBeneficiaryName.length()>18?m_sBeneficiaryName.substring(0, 18):m_sBeneficiaryName);
			//SMS Notification END
		}
		catch (Exception e)
		{
			e.printStackTrace();
			if (e instanceof IBGenericException)
			{
				throw (IBGenericException) e;
			}
			throw IBErrorHandler.createServiceException(
					IBServiceException.GENERAL_SERVICE_ERROR, true,
					new String[] {CommonErrorCode.GENERIC_CODE, "", "", "", IBErrorHandler.generateErrorMessage(e)}, c_oClass);
		}

		IBLogger.logBSFNMethodLeavingMessage (c_oClass, m_sMethodName, m_oTimer);
	}
}

