/**
 * Copyright (c) 2010 Penril Datability (M) 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 (M) Sdn Bhd or its assignees. This software is
 * provided under the terms of a license between Penril Datability (M)
 * Sdn Bhd and the recipient, and its use is subject to the terms of that
 * license.
 */
package my.com.kfh.enterprise.services.ib104_fundtransfer.ibft;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import my.com.kfh.enterprise.services.IBEnterpriseServicesWorkspace;
import my.com.kfh.enterprise.services.IBUtils;
import my.com.kfh.enterprise.services.common.CommonConstants;
import my.com.kfh.enterprise.services.ib101_access.AccessConstants;
import my.com.kfh.enterprise.services.ib104_fundtransfer.interbank.InterbankConstants;
import my.com.kfh.enterprise.services.ib104_fundtransfer.others.IBTransferLimitConstant;
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.ib106_utility.UtilityConstants;
import my.com.kfh.enterprise.services.ib114_online_contest.ContestContants;
import my.com.kfh.enterprise.services.integration.ESBPhoenixWSServices;
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.request.ESBRequestPhoenixWSBean;
import my.com.kfh.esb.response.ESBAccCreateDateBean;
import my.com.kfh.esb.response.ESBAccountEnquiryTC100Bean;
import my.com.kfh.esb.response.ESBChargesInquiryRespBean;
import my.com.kfh.esb.response.ESBCompanyProfileBean;
import my.com.kfh.esb.response.ESBIBFTResponseBean;
import my.com.kfh.hibernate.tables.onlineMobile.IbftTransfer;
import my.com.kfh.hibernate.tables.onlineMobile.MobileTransaction;
import my.com.kfh.hibernate.utils.onlineMobile.HibernateOnlineMobileReportsUtils;
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.IBDynaBean;
import my.com.kfh.web.utils.IBDynaBeanManager;
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.SettingsUtils;
import my.com.kfh.web.utils.constant.CurrencyCode;
import my.com.kfh.web.utils.constant.ESBConstants;
import my.com.kfh.web.utils.constant.ServiceInfo;
import my.com.kfh.web.utils.constant.TransactionType;

/**
 * <pre>
 * PROGRAMMER: Latipah Ab Rashid
 * CHANGE-NO:
 * TASK-NO:
 * DATE CREATED: Oct 25, 2010
 * TAG AS:
 * REASON(S):
 * MODIFICATION:
 * </pre>
 */

/**
 * <Class description>
 */
public class IBIBFTResultsServices extends IBEnterpriseServicesWorkspace
{
	private static Class<IBIBFTResultsServices> c_oClass = IBIBFTResultsServices.class;
	//OCBC, Citibank, HSBC, UOB, StanChart
	public static String [] foreignBankList = new String [] {"519469","589170","539981","589836","504324"};
	
	public IBIBFTResultsServices (IBSessionObjects p_oIBSessionObjects)
	{
		super (p_oIBSessionObjects);
	}

	/**
     * Verify TAC and verify amount against maximum limit for transfer.<BR>
     * Perform transfer to host.<BR>
     * If transaction is successful, create transfer receipt and if schedule date is today, send email to recipient.<BR>
     * Then, logs transaction details.
     *
     * @throws IBGenericException
     */
    public void processTransferResult () throws IBGenericException
    {
        String m_sMethodName = "processTransferResult";
        IBTimer m_oTimer = IBLogger.logBSFNMethodEnteringMessage (c_oClass, m_sMethodName);

        IBDynaBean m_oViewBean = null;

        IBDynaBean m_oServiceInfoBean = null;
        String m_sServiceName = TransactionType.FUND_TRANSFER_IBFT;
        String m_sServiceMaxLimit = "0";
        String m_sServiceCode = "";

        BVI_DateTime m_oCurrentBVIDateTime = null;
        String m_sTransStatus = ResourcesUtils.getUnsuccessful ();
        String m_sTransStatusMsg = "";
        String m_sFromAccount = "";
        String m_sFromAccountCreateDate = "";
        String m_sBeneBankCode = "";
        String m_sBeneBankDis = "";
        String m_sBeneAccountNo = "";
        String m_sBeneHolderName = "";
        String m_sAmount = "0";
        String m_sAmountDis = "";
        String m_sUserTransactionRefNo = "";
        String m_sTransactionDesc ="";
        String otherPaymentDetails ="";
        String m_sHostRefNo = "";
        String m_sIBFTAuditNo = "";
        String m_sNewBalance = "";
        String m_sTransId = "";
        String m_sFormattedTransId = "";
        String m_sEffectiveDate = "";
        String m_sIbftBankMemberId = "";
        String m_sRimNo = "";
        String m_sActualStatus = "";
		String m_sEmail = "";

        String m_sFromIsoCurrency = CurrencyCode.MALAYSIA_RINGGIT; //defaulted to MYR
        String m_sToIsoCurrency = CurrencyCode.MALAYSIA_RINGGIT; //defaulted to MYR
        //to acct iso currency -> where to get??

        String m_sDateDis = "";
        String m_sTimeDis = "";
        boolean m_boIsResultSuccessful = Boolean.FALSE;
        boolean m_boIsDisplayNewBalance = Boolean.FALSE;
        boolean m_bContestFlag = false;
        Float m_fUserLimit = null;
        Map<String, String> m_oReceiptMap = new LinkedHashMap<String, String> ();
        StringBuffer m_sbLogDetails = new StringBuffer ();

    	float m_fTotalAmountSingleService = 0;
		float m_fTotalAmountDoubleService = 0;
    	float m_fBankTransferLimit = 0;
    	float m_fUserTransferLimit = 0;
    	
		long m_sUserId = 0;
		String residencyType = "";
		String m_sTransferLimit = "0";
		String senderName = "";
		
		String m_sChargesRefNo = null;
		String gstChargesRefNo = null;
    	
        try
        {
        	String m_sCustomerName = getIBSessionObjects ().getVisitor ().getStringValue (AccessConstants.VISITOR_LAST_NAME);
            m_oViewBean = (IBDynaBean) getIBDynaBean ().get (IBFTConstants.IBFT_TRANSFER_VIEW) == null
                ? IBDynaBeanManager.createIBDynaBean (IBFTConstants.IBFT_TRANSFER_VIEW, getIBDynaBean ().getActionMapping ())
                        : (IBDynaBean) getIBDynaBean ().get (IBFTConstants.IBFT_TRANSFER_VIEW);

            if (m_oViewBean != null)
            {
                m_oServiceInfoBean = (IBDynaBean) m_oViewBean.get (ServiceInfo.SERVICE_INFO_BEAN);
            }

            if (m_oServiceInfoBean != null)
            {
                /*
                 * UPASS Verify TAC
                 */
                if (((Boolean) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_TAC_REQUIRED)).booleanValue ())
                {
                    getIBAuthenticationServices ().userVerifyTac ((String)getIBDynaBean ().get (UtilityConstants.TAC_VALUE),getIBSessionObjects().getIBSessionId());
                }

                /*
                 * get max limit if not empty
                 */
                if (!DataValidator.isEmptyString ((String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_MAX_LIMIT)))
                {
                	m_sServiceMaxLimit = DataValidator.isEmptyString ((String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_MAX_LIMIT)) ?
        					ThirdPartyTransferTags.ZERO_AMOUNT : (String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_MAX_LIMIT);
                }

                m_sServiceCode = (String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_SERVICE_CODE);
                m_sServiceName = (String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_SERVICE_NAME);
            }

            m_oCurrentBVIDateTime = new BVI_DateTime();
            m_sDateDis = DateTimeUtils.formatDayMonthYear (m_oCurrentBVIDateTime);
            m_sTimeDis = m_oCurrentBVIDateTime.getTime ();
            m_sEffectiveDate = m_oCurrentBVIDateTime.getSimpleDate ();

            m_sFromAccount = (String) getIBDynaBean ().get (IBFTConstants.FROM_ACCOUNT);
            m_sAmount = (String) getIBDynaBean ().get (IBFTConstants.AMOUNT);
            m_sAmountDis = (String) m_oViewBean.get (IBFTConstants.AMOUNT_DIS);
            m_sBeneBankCode = (String) getIBDynaBean ().get (IBFTConstants.BENE_BANK);
            m_sBeneBankDis = (String) m_oViewBean.get (IBFTConstants.BENE_BANK_DIS);
            m_sBeneAccountNo = (String) getIBDynaBean ().get (IBFTConstants.BENE_ACCOUNT_NO);
            m_sBeneHolderName = (String) m_oViewBean.get (IBFTConstants.BENE_NAME);
            m_sIbftBankMemberId = (String) m_oViewBean.get (IBFTConstants.BANK_MEMBER_ID);
            m_sUserTransactionRefNo = (String) getIBDynaBean ().get (IBFTConstants.TRANSACTION_REF_NO);
            m_sTransactionDesc = (String) getIBDynaBean ().get (IBFTConstants.TRANSACTION_DESC);
            otherPaymentDetails = (String) getIBDynaBean().get(IBFTConstants.OTHER_PAYMENT_DETAILS);
            m_sFromIsoCurrency = (String) m_oViewBean.get (IBFTConstants.FROM_ISO_CURRENCY);
            m_sEmail = (String) getIBDynaBean ().get (IBFTConstants.BENE_EMAIL);
            senderName = (String) m_oViewBean.get(IBFTConstants.SENDER_NAME);
            /*
             * get transaction ID
             */
            m_sTransId = IBUtils.getTransactionId (getIBSessionObjects ().getDataManager ());
            m_sFormattedTransId = FormatterUtils.formatTransID (m_sTransId);

            String m_sIsStaffAccount = (String) m_oViewBean.get(IBFTConstants.IS_STAFF_ACCOUNT);
            String m_sServiceCharges = "0.00";
            String gstCharges = "0.00";
            String chargesDisplay = "-";
            String gstChargesDisplay = "-";
            String gstAbsorbedAmount = null;
            String totalCharges = "0.00";
            String gstAbsorbed = "N";
            
            
            /*
             * check blacklisted beneficiary name
             */
            if (IBFundTransferDBUtils.isNameBlacklisted (this, m_sBeneHolderName))
			{
            	m_boIsResultSuccessful = Boolean.FALSE;
            	m_sActualStatus = IBOfacBlackList.BLACK_LISTED;

                m_sTransStatus = ResourcesUtils.getUnsuccessful ();
                m_sTransStatusMsg = ResourcesUtils.getBusinessExceptionErrorMessage (IBBusinessException.IBFT, IBFTConstants.ERR_BLACKLISTED_BENE_NAME);
			}
            else
            {
            	
            	m_sRimNo = (String)getIBSessionObjects ().getHttpSessionAttrObject (AccessConstants.RIM_NO);
            	m_sUserId = (long)getIBSessionObjects().getVisitor().getId();
            	ESBCompanyProfileBean residencyByRim = getESBServices ().getProfileByAccRim(null, m_sRimNo);
        		residencyType = residencyByRim.getResidency();
        		
        		//get charges, if foregin bank pcc = 871, local bank pcc = 870
        		if (ESBConstants.ACC_NONSTAFF.equalsIgnoreCase(m_sIsStaffAccount)){
        			String pcc = "870";
            		for(int i = 0; i < foreignBankList.length; i++){
            			if(foreignBankList[i].equals(m_sIbftBankMemberId)){
            				pcc = "871";
            				break;
            			}
            		}
        			
        			ESBChargesInquiryRespBean chargeInquiry = getESBServices().getChargesInfo(m_sFromAccount, pcc);
                	
                	if(ESBConstants.IB_SUCCESS_RC.equals (chargeInquiry.getResponseCode ())){
                		totalCharges = chargeInquiry.getChargeAmount();
                		String gstChargeAmount = chargeInquiry.getGstChargeAmount();
                		
                		
                		Double charges = Double.valueOf(totalCharges)-Double.valueOf(gstChargeAmount);
                		Double dGstCharges = Double.valueOf(gstChargeAmount);
                		
                		m_sServiceCharges = String.valueOf(Math.round(new BigDecimal(charges).floatValue() * 100.0) / 100.0);
                		gstCharges = (dGstCharges>0)?(String.valueOf(Math.round(new BigDecimal(dGstCharges).floatValue() * 100.0) / 100.0)):"0.00";
                		
                		chargesDisplay = (charges>0)?FormatterUtils.formatMoneyDisplay (m_sServiceCharges, m_sFromIsoCurrency, true):"-";
                		gstChargesDisplay = (dGstCharges>0)?FormatterUtils.formatMoneyDisplay (gstCharges, m_sFromIsoCurrency, true):"-";
                		
                		String gstChargesRate = IBUtils.getGSTRate(this, IBLoadProperty.getValue(GSTUtils.IBFT_CHARGES_CODE));
                		gstAbsorbedAmount = GSTUtils.gstCalcCharges(m_sServiceCharges, gstChargesRate);
                		gstAbsorbed = GSTUtils.isGSTAmountAbsorbed(gstAbsorbedAmount);
                	}
        		}
            	m_oViewBean.set(InterbankConstants.SERVICE_CHARGES_DISP, chargesDisplay);
            	m_oViewBean.set(InterbankConstants.GST_CHARGES_DIS, gstChargesDisplay);
        		
    			/*
    			 * check daily limit based on IBFT transfer (combine open and registered IBFT - IBFTOPEN+IBFTFAV against IBFTLIM)
    			 */
//        		if(residencyType.equalsIgnoreCase(ThirdPartyTransferTags.NON_RESIDENT_TYPE))
//        		{
//        			m_oServiceInfoBean = IBUtils.getServiceInfoBean (ServiceInfo.FUND_TRANSFER_STANDARD_DAILY_LIMIT_NON_RES, getIBDynaBean (),getIBSessionObjects (), true);
//        			
//        			m_sTransferLimit = (String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_MAX_LIMIT);
//        			
//        			m_sTransferLimit = DataValidator.isEmptyString (m_sTransferLimit) ?
//        					ThirdPartyTransferTags.ZERO_AMOUNT : m_sTransferLimit;
//							
//					if(Float.valueOf(m_sServiceMaxLimit).floatValue() > Float.valueOf(m_sTransferLimit).floatValue() )
//	    			{
//	    				m_sServiceMaxLimit = m_sTransferLimit;
//	    			}
//        		}
//        		else
//        		{
        			m_oServiceInfoBean = IBUtils.getServiceInfoBean (ServiceInfo.FUND_TRANSFER_IBFT_LIMIT, getIBDynaBean (),getIBSessionObjects (), true);
        			
        			m_sTransferLimit = (String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_MAX_LIMIT);
        			
        			m_sTransferLimit = DataValidator.isEmptyString (m_sTransferLimit) ?
        					ThirdPartyTransferTags.ZERO_AMOUNT : m_sTransferLimit;
//        		}
        		
            	m_fBankTransferLimit = m_sTransferLimit == null ? 0 : Float.valueOf (m_sTransferLimit); 
    			m_fTotalAmountDoubleService = IBFundTransferDBUtils.getTotalIbftTransferAmountByServiceCode (this, null, m_sEffectiveDate);
    			m_fTotalAmountDoubleService = m_fTotalAmountDoubleService + Float.valueOf (m_sAmount) + Float.valueOf(gstCharges) + Float.valueOf(m_sServiceCharges);
    			
    			/*
                 * check daily limit based on service code (open IBFT, registered IBFT separately - IBFTOPEN, IBFTFAV)
                 */
                m_fUserLimit = IBFundTransferDBUtils.getUserTransferLimit (getIBSessionObjects (), m_sServiceCode, false);
    			if (m_fUserLimit != null)
    			{
    				m_fUserTransferLimit = m_fUserLimit;
    			}
    			else
    			{
    				/**
    				 * if serviceLimit is empty, set default limit to 0.
    				 */
    				
    				if(Float.valueOf(IBTransferLimitConstant.USER_STANDARD_LIMIT).floatValue() > Float.valueOf (m_sServiceMaxLimit).floatValue())
    				{
    					m_fUserTransferLimit = Float.valueOf (m_sServiceMaxLimit).floatValue();
    				}
    				else
    				{
    					m_fUserTransferLimit = Float.valueOf(IBTransferLimitConstant.USER_STANDARD_LIMIT).floatValue();
    				}
    			}
    			m_fTotalAmountSingleService = IBFundTransferDBUtils.getTotalIbftTransferAmountByServiceCode (this, m_sServiceCode, m_sEffectiveDate);
    			m_fTotalAmountSingleService = m_fTotalAmountSingleService + Float.valueOf (m_sAmount) + Float.valueOf(gstCharges) + Float.valueOf(m_sServiceCharges);

    			if (m_fTotalAmountDoubleService > m_fBankTransferLimit)
    			{
    				m_boIsResultSuccessful = Boolean.FALSE;

                    m_sTransStatus = ResourcesUtils.getUnsuccessful ();
                    m_sTransStatusMsg = ResourcesUtils.getBusinessExceptionErrorMessage (IBBusinessException.IBFT,
                    		IBFTConstants.ERR_BANK_MAX_AMOUNT,
                    		new String [] { FormatterUtils.formatMoneyDisplay (String.valueOf (m_fBankTransferLimit), 
                    				CurrencyCode.MALAYSIA_RINGGIT, true) });
    			}
    			else if (m_fTotalAmountSingleService > m_fUserTransferLimit)
    			{
    				m_boIsResultSuccessful = Boolean.FALSE;

                    m_sTransStatus = ResourcesUtils.getUnsuccessful ();
                    m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_CHANGE_MAX_AMOUNT,
 	                		new String [] { FormatterUtils.formatMoneyDisplay (String.valueOf (m_fBankTransferLimit),
 	                				CurrencyCode.MALAYSIA_RINGGIT, true) });
    			}
                else
                {
                	
                	ESBIBFTResponseBean m_oESBIBFTResponseBean = getESBServices ().ibftFundTransfer (
                         		m_sRimNo, m_sFromAccount, m_sBeneAccountNo, m_sAmount, m_sIbftBankMemberId, senderName, m_sBeneHolderName, m_sTransactionDesc, otherPaymentDetails);
//                	}
                		
                	m_sIBFTAuditNo = m_oESBIBFTResponseBean.getAuditNo ();
                	m_sTransStatusMsg = m_oESBIBFTResponseBean.getErrorMessage ();
					m_sActualStatus =  m_oESBIBFTResponseBean.getErrorInfo ();
                	
    				if (ESBConstants.IB_SUCCESS_RC.equals (m_oESBIBFTResponseBean.getResponseCode ()))
    				{
    					m_boIsResultSuccessful = Boolean.TRUE;
    					m_sHostRefNo = m_oESBIBFTResponseBean.getReferenceNo ();
    					
						m_boIsDisplayNewBalance = true;

						// TC 100 - Account Balance
						ESBAccountEnquiryTC100Bean m_oTCEnquiryBean = getESBServices ().getAccountDetailsTC100 (m_sFromAccount);
						m_sNewBalance = FormatterUtils.formatMoneyDisplay (
    							DataValidator.isEmptyString (m_oTCEnquiryBean.getAvailable_Bal().trim()) ? "0"
    									: m_oTCEnquiryBean.getAvailable_Bal().trim(),
    									m_sFromIsoCurrency, true);

    					// Account Creation Date
    					ESBPhoenixWSServices m_oESBPhoenixWSServices = new ESBPhoenixWSServices();
    					ESBRequestPhoenixWSBean m_oRequest = new ESBRequestPhoenixWSBean();
    					// From Account Creation Date
    					m_oRequest.setAcctNo (m_sFromAccount);
    					ESBAccCreateDateBean m_oAccCreateDateBean = m_oESBPhoenixWSServices.getAccCreateDate (m_oRequest);
    					m_sFromAccountCreateDate = m_oAccCreateDateBean.getDtAccOpen();
    				}
    				else
    				{
    					m_boIsResultSuccessful = Boolean.FALSE;
    					m_sTransStatus = ResourcesUtils.getUnsuccessful ();
    				}
				}
            }
            
            if (m_boIsResultSuccessful)
            {
            	m_sTransStatus = ResourcesUtils.getSuccessful ();

            	/*
            	 * email transfer notification to beneficiary
            	 */
            	if (!DataValidator.isEmptyString (m_sEmail))
                {
    				String m_sSubject = ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.email.subject");

                	StringBuffer m_sbEmailMsg = new StringBuffer ();
                	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.email.greetCustomer", new String [] {m_sSubject, m_sBeneHolderName} ));
                	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.email.note1",
                			new String [] {m_sCustomerName, m_sDateDis.concat (" ").concat (m_sTimeDis) } ));

                	IBLogWriter m_oTableCreater = new IBLogWriter();
                	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("S", ResourcesUtils.getApplicationResourceMessage ("general.status"), m_sTransStatus, null, null)).append("\n");
                	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("general.amount"), m_sAmountDis, null, null)).append("\n");
                	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("general.reference.number"), FormatterUtils.formatTransID (m_sFormattedTransId), null, null)).append("\n");
                	if(!DataValidator.isEmptyString (m_sHostRefNo))
    				{
                		m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("general.reference"), m_sHostRefNo, null, null)).append("\n");
    				}
                	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.remarks"),
                			DataValidator.isEmptyString (m_sTransactionDesc) ? "-" : m_sTransactionDesc, null, null)).append("\n");
                	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.other.payment.details"),
                			DataValidator.isEmptyString (otherPaymentDetails) ? "-" : otherPaymentDetails, null, null)).append("\n");
                	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("ib104.sender.name"),
                			DataValidator.isEmptyString (senderName) ? "-" : senderName, null, null)).append("\n");
                	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.bene.bank"), m_sBeneBankDis, null, null)).append("\n");
                	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("E", ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.transaction.ref.no"),
                			DataValidator.isEmptyString (m_sUserTransactionRefNo) ? "-" : m_sUserTransactionRefNo, null, null)).append("\n");

                	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.email.note2"));
                	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.email.disclaimer"));

                	IBUtils.sendEmail (this, null, m_sEmail, m_sSubject, m_sbEmailMsg.toString (), m_sTransStatus, null);
                }

                /*
                 * receipt
                 */
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("receipt.transaction.type"), m_sServiceName);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.sender.name"), senderName);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.bene.name"), m_sBeneHolderName);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.status"), m_sTransStatus);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.amount"), m_sAmountDis);
                if(!"-".equalsIgnoreCase(chargesDisplay))
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.charges"), chargesDisplay);
                if(!"-".equalsIgnoreCase(gstChargesDisplay))
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.gst.charges"), gstChargesDisplay);
                
                if (!DataValidator.isEmptyString (m_sTransactionDesc))
				{
					m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.remarks"), m_sTransactionDesc);
				}
                if(!DataValidator.isEmptyString (otherPaymentDetails)){
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.other.payment.details"), otherPaymentDetails);
                }

                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.bene.bank"), m_sBeneBankDis);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.bene.acct.no"), m_sBeneAccountNo);
                if (!DataValidator.isEmptyString (m_sUserTransactionRefNo))
				{
					m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.transaction.ref.no"), m_sUserTransactionRefNo);
				}
                if (!DataValidator.isEmptyString (m_sEmail))
				{
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.email"), m_sEmail);
				}

                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.reference.number"), m_sFormattedTransId);
                if(!DataValidator.isEmptyString (m_sHostRefNo))
				{
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.reference"), m_sHostRefNo);
				}
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.transaction.date"), m_sDateDis);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.transaction.time"), m_sTimeDis);

                //Add KFH GST ID No
                if(!"-".equalsIgnoreCase(gstChargesDisplay))
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.gst.id.no"), IBLoadProperty.getValue("gst.id.no"));
				
                /*
                 * log into IB_RECEIPT_DETAIL
                 */
                IBUtils.loopIntoReceiptDetails (this, m_oReceiptMap, m_oCurrentBVIDateTime.getSimpleDate (), m_sTransId);

                m_oViewBean.set (CommonConstants.RECEIPT_MAP, m_oReceiptMap);

                String m_sReceiptLink = IBUtils.getReceiptLink (IBFTConstants.IBFT_TRANSFER_FORM, IBFTConstants.IBFT_TRANSFER_VIEW);
                m_oViewBean.set (CommonConstants.RECEIPT_LINK, m_sReceiptLink);
            }
            
            //Checking Contest module
            String m_sContestAmount = SettingsUtils.getSetting(ContestContants.ONLINE_CONTEST_AMOUNT);
			if(m_boIsResultSuccessful)
			{
	            if(Double.parseDouble (m_sAmount)>Double.parseDouble (m_sContestAmount)
						|| Double.parseDouble (m_sAmount)== Double.parseDouble (m_sContestAmount))
				{
					//check whether Contest is ON/OFF
					String m_sContestFlag = SettingsUtils.getSetting(ContestContants.ONLINE_CONTEST_FLAG);
					
					if(m_sContestFlag.equalsIgnoreCase(ContestContants.ONLINE_CONTEST_ON))
					{
						//Check Date start & end date
						Date m_oTodayDate = new Date();
						String m_sStartDate = SettingsUtils.getSetting(ContestContants.ONLINE_CONTEST_START_DATE);
						String m_sEndDate = SettingsUtils.getSetting(ContestContants.ONLINE_CONTEST_END_DATE);
						
						SimpleDateFormat m_oSDF = new SimpleDateFormat("dd/MM/yyyy");
						
						Date m_oStartDate = m_oSDF.parse(m_sStartDate);
						Date m_EndDate = m_oSDF.parse(m_sEndDate);
						
						if(m_oTodayDate.compareTo(m_oStartDate) > 0 && m_oTodayDate.compareTo(m_EndDate) < 0)
						{
							m_bContestFlag = true;
						}
					}
				}
			}
			m_oViewBean.set (ContestContants.IS_CONTEST_ON, m_bContestFlag);
			getIBDynaBean().set("trnxId", m_sTransId);
			getIBDynaBean().set("trnxType", m_sServiceName);

			m_sbLogDetails.append (ResourcesUtils.getApplicationResourceMessage ("ib104.ibft.transfer.to"));
			m_sbLogDetails.append (" ").append (m_sBeneHolderName);
			m_sbLogDetails.append (" (").append (m_sBeneBankDis).append (": ").append (m_sBeneAccountNo).append (")");
            if (!DataValidator.isEmptyString (m_sHostRefNo))
			{
            	m_sbLogDetails.append ("<br>")
	            	.append ("(")
		        	.append (ResourcesUtils.getApplicationResourceMessage ("general.reference.number.short")).append (": ").append (m_sHostRefNo)
		        	.append (")");
			}

            /*
             * log into IB_IBFT_TRANSFER.
             * This is done after set data into viewbean and formbean and pass the formbean to IBLogger.
             */
            IBLogger.logIbftTransferActivity (this, m_sTransId, m_sServiceName, 
            		m_oCurrentBVIDateTime, m_sFromAccount, m_sBeneAccountNo, 
            		m_sFromIsoCurrency, m_sToIsoCurrency, m_sFromAccountCreateDate, 
            		m_sAmount, 
            		m_sAmount,//TODO local amount 
            		m_sTransactionDesc, 
            		m_sBeneHolderName, m_sBeneBankDis, m_sBeneBankCode, m_sIbftBankMemberId,
            		m_sUserTransactionRefNo, m_sEmail, m_sbLogDetails.toString (), 
            		m_sEffectiveDate, m_sServiceCode, 
            		m_sTransStatus, m_sTransStatusMsg, m_sActualStatus, 
            		m_sIBFTAuditNo, m_sHostRefNo, null, null, 
            		m_sServiceCharges, m_sChargesRefNo, gstCharges, gstChargesRefNo);
            
            /*
             * log into IB_TRANSACTION_HISTORY
             * receipt indicator is based whether have receipt or not, based on result status.
             */
			IBLogger.logInetTranHistory (this,
					m_sTransId,
					m_sServiceName,
					m_sFromAccount,
					m_sFromIsoCurrency,
					m_sBeneAccountNo,
					m_sToIsoCurrency,
					m_sAmount,
					m_sbLogDetails.toString (),
					m_sTransStatus,
					null, null,
					m_sEffectiveDate,
					getIBSessionObjects ().getRemoteIPAddress (),
					"",
					m_boIsResultSuccessful,
					m_sHostRefNo,
					null, // Other1
					null, null,
					getIBSessionObjects ().getIBSessionId (),
					null, null, null, m_sFromAccountCreateDate, null,
					m_sTransStatusMsg,
					null,
					null,
					null,
					// Penril: Additional fields for GST report
					m_sServiceCharges,
					gstCharges,
					gstAbsorbed,
					gstAbsorbedAmount,
					getIBSessionObjects().getGSTGLAccount(),
					m_sBeneHolderName,
					m_sBeneBankDis,
					m_sChargesRefNo,
					String.valueOf(getIBSessionObjects().getVisitor().getId()),
					m_sIsStaffAccount);
					// End Penril: Additional fields for GST report);

            m_oViewBean.set (IBFTConstants.TRNX_ID, m_sFormattedTransId);
            m_oViewBean.set (IBFTConstants.HOST_REFERENCE_NO, m_sHostRefNo);
            m_oViewBean.set (IBFTConstants.IS_RESULT_SUCCESSFUL, m_boIsResultSuccessful);
            m_oViewBean.set (IBFTConstants.IS_DISPLAY_NEW_BALANCE, m_boIsDisplayNewBalance);
            m_oViewBean.set (IBFTConstants.STATUS, m_sTransStatus);
            m_oViewBean.set (IBFTConstants.REASON, m_sTransStatusMsg);
            m_oViewBean.set (IBFTConstants.FROM_ACCT_NEW_BAL, m_sNewBalance);
            m_oViewBean.set (IBFTConstants.TRNX_DATE, m_sDateDis);
            m_oViewBean.set (IBFTConstants.TRNX_TIME, m_sTimeDis);
            
            
//          SMS Notification START
			String m_sCustomerSMSMessage = "-";
			String m_sBeneficiarySMSMessage = "-";
			
			String m_sCustomerAmount = SMSServices.formatAmountValue(m_sAmount, m_sFromIsoCurrency);
			String m_sBeneficiaryAmount = SMSServices.formatAmountValue(m_sAmount, m_sToIsoCurrency);

			String m_sTransactionTypeForSMSMessage = ResourcesUtils.getApplicationResourceMessage(SMSConstants.RESOURCE_SMS_TEXT_MESSAGE_SERVICE_IBFT);
			
			m_sCustomerSMSMessage = SMSServices.generateCustomerSMSMessage(
					m_sTransactionTypeForSMSMessage,
					m_sCustomerAmount,
					m_sBeneHolderName.length()>14?m_sBeneHolderName.substring(0, 14):m_sBeneHolderName,
					m_sTransStatus,
					new Date(),
					m_sNewBalance);
			
			SMSServices.sendCustomerSMS(this, 
					m_oViewBean, 
					m_sFromAccount, 
					m_sTransStatus, 
					null, //SI_PAYMENT_MODE.PAY_NOW.getCode () 
					m_sServiceName, 
					m_sTransId,
					m_sAmount,  
					getIBSessionObjects().getVisitor().getId(), 
					m_sCustomerSMSMessage, 
					m_oCurrentBVIDateTime,
					SMSConstants.DEBIT_IB_TYPE);
			
			m_sBeneficiarySMSMessage = SMSServices.generateBeneficiaryOtherSMSMessage(
					m_oViewBean, 
					m_sTransactionTypeForSMSMessage, 
					m_sBeneAccountNo, 
					m_sBeneficiaryAmount, 
					m_oCurrentBVIDateTime);
			
			SMSServices.sendBeneficiarySMS(this, 
					getIBDynaBean(),
					m_oViewBean, 
					m_sFromAccount, 
					m_sTransStatus, 
					null, //SI_PAYMENT_MODE.PAY_NOW.getCode () 
					m_sServiceName, 
					m_sTransId, 
					getIBSessionObjects().getVisitor().getId(), 
					m_sBeneficiarySMSMessage, 
					m_oCurrentBVIDateTime,
					"");
			
			ESBAccountEnquiryTC100Bean m_oTCEnquiryBean = getESBServices ().getAccountDetailsTC100 (m_sFromAccount);
			
			m_oViewBean.set (IBFTConstants.FROM_ACCT_NEW_BAL,  FormatterUtils.formatMoneyDisplay (
					DataValidator.isEmptyString (m_oTCEnquiryBean.getAvailable_Bal().trim()) ? "0"
							: m_oTCEnquiryBean.getAvailable_Bal().trim (),
							m_sFromIsoCurrency, true));

			// UAT START
			m_oViewBean.set(SMSConstants.VBEAN_SMS_UAT_IS_BENE_SMS_SENT, SMSServices.isSMSLogged(this, m_oViewBean.get(SMSConstants.VBEAN_SMS_BENE_MOBILE_NO).toString(), SMSConstants.SMS_NOTIFICATION_TYPE, m_oCurrentBVIDateTime.getDateDDMMMYYYYHMS()));
			m_oViewBean.set(SMSConstants.VBEAN_SMS_UAT_IS_CUSTOMER_SMS_SENT, SMSServices.isSMSLogged(this, m_oViewBean.get(SMSConstants.VBEAN_SMS_CUSTOMER_MOBILE_NO).toString(), SMSConstants.SMS_NOTIFICATION_TYPE, m_oCurrentBVIDateTime.getDateDDMMMYYYYHMS()));
			m_oViewBean.set(SMSConstants.VBEAN_SMS_UAT_BENE_SMS_MESSAGE, m_sBeneficiarySMSMessage);
			m_oViewBean.set(SMSConstants.VBEAN_SMS_UAT_CUSTOMER_SMS_MESSAGE, m_sCustomerSMSMessage);
			// UAT END
				
			// SMS Notification END
            

            getIBDynaBean ().set (IBFTConstants.IBFT_TRANSFER_VIEW, m_oViewBean);

            
            //#-- added by pixa(joo) 20130111 start
            try{
            	String ChannelObj = "";
            	Date fromAccCreateDate = null;
            	Date effDate = null;
            	
            	if(getIBSessionObjects().getHttpSessionAttrObject("ChannelObj") != null)
            	{
            		ChannelObj = getIBSessionObjects().getHttpSessionAttrObject("ChannelObj").toString();
            	}
            	if(ChannelObj.equals("mobileApp"))
	            {
        			SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");	
        			
        			try{
        				if(!DataValidator.isEmptyString ((String)m_sFromAccountCreateDate))
        					fromAccCreateDate = timestampFormat.parse(m_sFromAccountCreateDate);
        			}
                	catch (Exception e)
            		{
                		e.printStackTrace();
            		}
        			
        			try{
        				if(!DataValidator.isEmptyString ((String)m_sFromAccountCreateDate)){
        					String effDateString = HibernateOnlineMobileReportsUtils.convertToDateFormat(m_sEffectiveDate);
                			effDate = dateFormat.parse(effDateString);
        				}
        			}
                	catch (Exception e)
            		{
                		e.printStackTrace();
            		}
        			
        			MobileTransaction m_oMobileTransaction = new MobileTransaction();
        			m_oMobileTransaction.setDate(new Date());
        			m_oMobileTransaction.setRimNo(m_sRimNo);
        			m_oMobileTransaction.setUsername(getIBSessionObjects ().getVisitor ().getName());
        			m_oMobileTransaction.setCustomerName(getIBSessionObjects ().getVisitor ().getStringValue (AccessConstants.VISITOR_LAST_NAME));
        			m_oMobileTransaction.setIbTransactionId(m_sTransId);
        			m_oMobileTransaction.setTransactionType("1043");
        			m_oMobileTransaction.setFromAccount(m_sFromAccount);
        			m_oMobileTransaction.setFromCy(m_sFromIsoCurrency);
        			m_oMobileTransaction.setToAccount(m_sBeneAccountNo);
        			m_oMobileTransaction.setToCy(m_sToIsoCurrency);
        			m_oMobileTransaction.setAmount(Double.valueOf(Double.parseDouble(m_sAmount)));
        			m_oMobileTransaction.setStatus(m_sTransStatus);
        			if(effDate != null)
        				m_oMobileTransaction.setEffectiveDate(effDate);
        			m_oMobileTransaction.setRemoteIp(getIBSessionObjects ().getRemoteIPAddress ());
        			m_oMobileTransaction.setPhoenixReference("");
        			m_oMobileTransaction.setEpayReference("");
        			m_oMobileTransaction.setPhoenixRevertReferenceNo("");
        			m_oMobileTransaction.setPhoenixChargesReferenceNo("");
        			m_oMobileTransaction.setPhoenixRevertChargesReferen("");
        			m_oMobileTransaction.setDetails(m_sbLogDetails.toString());
        			if(fromAccCreateDate != null)
        				m_oMobileTransaction.setFromAccountCreationDate(fromAccCreateDate);
        			m_oMobileTransaction.setToAccountCreationDate(null);
        			m_oMobileTransaction.setType("IN");
        			

        			IbftTransfer m_oIbftTransfer = new IbftTransfer();
        			//m_oIbftTransfer.setLocalAmount(Double.parseDouble(m_sAmount));
        			m_oIbftTransfer.setPaymentDetails(m_sbLogDetails.toString());
        			m_oIbftTransfer.setBeneficiaryName(m_sBeneHolderName);
        			m_oIbftTransfer.setBeneficiaryBank(m_sBeneBankDis);
        			//m_sBeneBankCode
        			m_oIbftTransfer.setBeneficiaryTransactionRefNo(m_sUserTransactionRefNo);
        			m_oIbftTransfer.setBeneficiaryEmail(m_sEmail);
        			m_oIbftTransfer.setDescription(m_sTransactionDesc);
        			m_oIbftTransfer.setReason(m_sTransStatusMsg);
        			m_oIbftTransfer.setHostReference(m_sHostRefNo);
        			HibernateOnlineMobileReportsUtils.insertIBFTTransferStore(m_oIbftTransfer);
	            }
            }
        	catch (Exception e)
    		{
        		e.printStackTrace();
    		}
            //#-- added by pixa(joo) 20130111 end
            
            
            /*
             * clear session after transfer,
             * so account enquiry will not display balance in session,
             * instead get from host in new session
             */
			getIBSessionObjects ().setAccountEnquiryBean (null);
        }
        catch (Exception e)
        {
        	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);
    }
    public static void main(String[] args) {
    	String totalCharges = "1.06";
		String gstRate = "6";
		
		Double charges = Double.valueOf(totalCharges)/(100+(Double.valueOf(gstRate)*100))*100;
		String m_sServiceCharges = String.valueOf(Math.round(new BigDecimal(charges).floatValue() * 100.0) / 100.0);
		Double dGstCharges = Double.valueOf(totalCharges)-charges;
		String gstCharges = String.valueOf(Math.round(new BigDecimal(dGstCharges).floatValue() * 100.0) / 100.0);
		gstCharges = (dGstCharges>0)?gstCharges:"0.00";
		
		System.out.println("Total Charges " + totalCharges);
		System.out.println("Service Charges " + m_sServiceCharges);
		System.out.println("Charges " + charges);
		System.out.println("GST Charges " + gstRate);
		
		
		
	
	}
}
