/**
 * 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.thirdparty;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

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.others.IBStdDailyLimitBaseServices;
import my.com.kfh.enterprise.services.ib106_utility.UtilityConstants;
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.SI_PAYMENT_MODE;
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.ESBCompanyProfileBean;
import my.com.kfh.esb.response.ESBThirdFundTransferBean;
import my.com.kfh.hibernate.tables.onlineMobile.IntrabankFundTransfer;
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.DataUtils;
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.IBDynaBean;
import my.com.kfh.web.utils.IBDynaBeanManager;
import my.com.kfh.web.utils.IBLogWriter;
import my.com.kfh.web.utils.IBLogger;
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.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 bt Abdul Rashid
 * CHANGE-NO:
 * TASK-NO:
 * DATE CREATED: Oct 16, 2008
 * TAG AS:
 * REASON(S):
 * MODIFICATION:
 * </pre>
 */

/**
 * Send transfer details to host to perform favourite Intrabank transfer.
 */
public class IBReg3rdPartyTransferResultsServices extends IBGenericSIServices
{
	private static Class c_oClass = IBReg3rdPartyTransferResultsServices.class;

	private static String VIEWBEAN = ThirdPartyTransferTags.REG_THIRDPARTY_TRANSFER_VIEW;

	/**
	 * Class constructor specifying session object.
	 *
	 * @param m_oIBSessionObjects session object containing all information stored in HTTP session
	 */
	public IBReg3rdPartyTransferResultsServices (IBSessionObjects m_oIBSessionObjects)
	{
		super (m_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 if any Exception are thrown
	 */
	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;
		BVI_DateTime m_oCurrentBVIDateTime = null;
		ESBThirdFundTransferBean m_oReturnedESBBean = new ESBThirdFundTransferBean ();
		String m_sTransStatus = ResourcesUtils.getUnsuccessful ();
		String m_sTransStatusMsg = "";
		String m_sFromAccount = "";
		String m_sToRegAccount = "";
		String m_sAmount = "0";
		String m_sAmountDis = "";
		String m_sLocalAmountStr = "";
		String m_sAccountHolderName = "";
        String m_sEmail = "";
		String m_sUserTransferRef = "";
        String m_sHostRefNo = "";
		String m_sFromAccNewBalance = "";
		String m_sToAccNewBalance = "";
		String m_sTransId = "";
		String m_sFormattedTransId = "";
        String m_sServiceMaxLimit = "";
        String m_sFromIsoCurrency = CurrencyCode.MALAYSIA_RINGGIT; //default to MYR
        String m_sToIsoCurrency = CurrencyCode.MALAYSIA_RINGGIT; //default to MYR
        String m_sResponseCode = "";
        String m_sServiceCode = ServiceInfo.FUND_TRANSFER_INTRA_FAV;
//        String m_sServiceCodeStdLim = ServiceInfo.FUND_TRANSFER_STANDARD_DAILY_LIMIT;
        String m_sServiceName = TransactionType.FUND_TRANSFER_INTRA;
        String m_sFrmAccCrtDt = "";
        String m_sToAccCrtDt = "";
		boolean m_boIsResultSuccessful = false;
		boolean m_boToDisplayNewBal = false;
		Float m_fUserLimit = null;

//      si
		Date m_oEffectiveDate = null;
		boolean m_boSIIndicator = false;
		boolean m_boDeleteSIIndicator = false;
		String m_sEffectiveDate = null;
		String m_sPaymentFrequencyDisplay = null;
		String m_sPayFrequency = null;
		String m_sTerminationDate = null;
		String m_sPaymentMode = null;
		String m_sPaymentModeDisplay = null;
		String m_sEffectiveDateDisplay = null;
		String m_sTerminationDateDisplay = null;

		Map<String, String> m_oReceiptMap = new LinkedHashMap<String, String> ();

		double m_dAvailableBal = 0.0;
		double m_dTotalTransferAmount = 0.0;
		boolean m_boIsFundSufficient = true;
		String m_sSIServiceCode = ServiceInfo.SI_INTRA_FAV_LIMIT;
		String m_sSIServiceMaxLimit = null;
		IBDynaBean m_oSIServiceInfoBean = null;
		boolean m_boIsScheduler = false;
		String m_sRimNo = "";
		long m_sUserId = 0;
		Float specialDailyLimit= null;
		Float userDailyLimit= null;
		String residencyType = "";
		String senderName = "";
		String otherPaymentDetails = "";

		try
		{
			m_oViewBean = (IBDynaBean) getIBDynaBean ().get (VIEWBEAN) == null
				? IBDynaBeanManager.createIBDynaBean (VIEWBEAN, getIBDynaBean ().getActionMapping ())
						:(IBDynaBean) getIBDynaBean ().get (VIEWBEAN);
				
				m_sRimNo = (String)getIBSessionObjects ().getHttpSessionAttrObject (AccessConstants.RIM_NO);
	        	m_sUserId = (long)getIBSessionObjects().getVisitor().getId();
	        	userDailyLimit = IBUtils.getUserDailyLimit(this, m_sUserId);
	        	ESBCompanyProfileBean residencyByRim = getESBServices ().getProfileByAccRim(null, m_sRimNo);
	    		residencyType = residencyByRim.getResidency();
	        	specialDailyLimit = IBUtils.getSpecialDailyLimit(this, m_sUserId);
	        	specialDailyLimit = IBStdDailyLimitBaseServices. getSystemDailyLimit(this, getIBDynaBean (), getIBSessionObjects (), residencyType , specialDailyLimit);
	        	
	    		
	        	

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

			m_oCurrentBVIDateTime = DateTimeUtils.getCurrentIBDateTimeObject ();
			m_oEffectiveDate = m_oCurrentBVIDateTime.getJavaDate ();

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

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

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

			m_sPaymentMode = (String)getIBDynaBean ().get (SIConstants.PAY_MODE);
			m_sPaymentModeDisplay = (String)m_oViewBean.get (SIConstants.PAY_MODE_DISPLAY);
			m_sEffectiveDateDisplay = (String)m_oViewBean.get (SIConstants.EFFECTIVE_DATE_DISPLAY);

			if (!SI_PAYMENT_MODE.PAY_NOW.getCode ().equals (m_sPaymentMode))
			{
				m_boSIIndicator = true;
				m_sServiceName = IBGenericSIServices.getSITransType (m_sServiceName, m_sPaymentMode);

				m_sEffectiveDate = (String)m_oViewBean.get (SIConstants.EFFECTIVE_DATE_FORMAT);
				BVI_DateTime m_oIbEffectiveDateTime = new BVI_DateTime (m_sEffectiveDate);
				m_oEffectiveDate = m_oIbEffectiveDateTime.getJavaDate ();

				if (SI_PAYMENT_MODE.RECURRING_PAYMENT.getCode ().equals (m_sPaymentMode))
				{
					m_sPayFrequency = (String)getIBDynaBean ().get (SIConstants.PAY_FREQUENCY);
					m_sPaymentFrequencyDisplay = (String)m_oViewBean.get (SIConstants.PAY_FREQUENCY_DISPLAY);
					m_sTerminationDate = (String) m_oViewBean.get (SIConstants.TERMINATION_DATE_FORMAT);
					m_sTerminationDateDisplay = (String)m_oViewBean.get (SIConstants.TERMINATION_DATE_DISPLAY);
				}
			}

			m_sEffectiveDate = DateTimeUtils.formatIBDateTimeToYMD (m_oEffectiveDate);
			m_sFromAccount = (String) getIBDynaBean ().get (ThirdPartyTransferTags.FROM_ACCOUNT);
			m_sToRegAccount = (String) getIBDynaBean ().get (ThirdPartyTransferTags.TO_REG_ACCOUNT);
			m_sAmount = (String) getIBDynaBean ().get (ThirdPartyTransferTags.AMOUNT);
			m_sUserTransferRef = (String) getIBDynaBean ().get (ThirdPartyTransferTags.TRANSFER_REF);
            m_sEmail = (String) getIBDynaBean ().get (ThirdPartyTransferTags.EMAIL);
            m_sFromIsoCurrency = (String) m_oViewBean.get (ThirdPartyTransferTags.FROM_ISO_CURRENCY);
            m_sToIsoCurrency = (String) m_oViewBean.get (ThirdPartyTransferTags.TO_ISO_CURRENCY);
            m_sAmountDis = (String) m_oViewBean.get (ThirdPartyTransferTags.AMOUNT_DIS);
            m_sAccountHolderName = (String) m_oViewBean.get (ThirdPartyTransferTags.ACCOUNT_HOLDER_NAME);
            senderName = (String) m_oViewBean.get(ThirdPartyTransferTags.SENDER_NAME);
            otherPaymentDetails = (String) m_oViewBean.get (ThirdPartyTransferTags.OTHER_PAYMENT_DETAILS);

			/*
			 * get transaction ID
			 */
	        m_sTransId = IBUtils.getTransactionId (getIBSessionObjects ().getDataManager ());
	        m_sFormattedTransId = FormatterUtils.formatTransID (m_sTransId);

            /*
             * convert amount to local (RM)
             */
            m_sLocalAmountStr = IBFundTransferDBUtils.getLocalAmount (this, m_sToIsoCurrency, m_sAmount, m_oServiceInfoBean);

            if (SI_PAYMENT_MODE.PAY_NOW.getCode ().equals (m_sPaymentMode))
            {
	            /*
	             * check limit againts total amount per day
	             */
		        Map m_oBankLimitReturnMap = IB3rdPartyTransferBaseServices.checkIntraTransferDailyLimit (this,
	            		getIBDynaBean (), getIBSessionObjects (), m_sLocalAmountStr, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler ,residencyType);

				m_fUserLimit = IBFundTransferDBUtils.getUserTransferLimit (getIBSessionObjects (), m_sServiceCode, m_boIsScheduler);

				Map m_oUserLimitReturnMap = IB3rdPartyTransferBaseServices.checkIntraTransferDailyLimitByServiceCode (this,
						m_sLocalAmountStr, m_sServiceMaxLimit, m_fUserLimit, m_sServiceCode, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler , residencyType ,
						m_oBankLimitReturnMap);
				
				/*
	             * check daily limit
	             */
	            
	            Map m_oStdBankingLimitReturnMap = IBStdDailyLimitBaseServices.checkBankDailyLimit(this, getIBDynaBean (), 
	            		getIBSessionObjects (), m_sAmount , specialDailyLimit, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler , residencyType);
	            
	            Map m_oStdUserLimitReturnMap = IBStdDailyLimitBaseServices.checkUserDailyLimit(this, getIBDynaBean (), 
	            		getIBSessionObjects (), m_sAmount , userDailyLimit, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler);
	            
	            if (!((Boolean) m_oUserLimitReturnMap.get (ThirdPartyTransferTags.STATUS)).booleanValue ())
				{ 
	            	m_boIsResultSuccessful = false;

					m_sTransStatus = ResourcesUtils.getUnsuccessful ();
					m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_CHANGE_MAX_AMOUNT,
							new String [] { FormatterUtils.formatMoneyDisplay ((String) m_oUserLimitReturnMap.get (ThirdPartyTransferTags.MAX_LIMIT),
									CurrencyCode.MALAYSIA_RINGGIT, true) });
				}
	            else if ((!((Boolean) m_oBankLimitReturnMap.get (ThirdPartyTransferTags.STATUS)).booleanValue ())&&(0 <= specialDailyLimit.floatValue()))
	            {
	            	m_boIsResultSuccessful = false;

	                m_sTransStatus = ResourcesUtils.getUnsuccessful ();
	                m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_BANK_MAX_AMOUNT,
	                		new String [] { FormatterUtils.formatMoneyDisplay ((String) m_oBankLimitReturnMap.get (ThirdPartyTransferTags.MAX_LIMIT),
	                				CurrencyCode.MALAYSIA_RINGGIT, true) });
	            }
	            else if (!((Boolean) m_oStdUserLimitReturnMap.get (ThirdPartyTransferTags.STATUS)).booleanValue ())
	            {
	            	m_boIsResultSuccessful = false;

	                m_sTransStatus = ResourcesUtils.getUnsuccessful ();
	                m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_USER_STD_LIMIT,
 	                		new String [] { FormatterUtils.formatMoneyDisplay (String.valueOf(specialDailyLimit) ,
 	                				CurrencyCode.MALAYSIA_RINGGIT, true) });
	                
//	                m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_USER_STD_LIMIT,
//	                		new String [] { FormatterUtils.formatMoneyDisplay ((String) m_oStdUserLimitReturnMap.get (ThirdPartyTransferTags.MAX_LIMIT),
//	                				CurrencyCode.MALAYSIA_RINGGIT, true) });
	            }
	            else if ((!((Boolean) m_oStdBankingLimitReturnMap.get (ThirdPartyTransferTags.STATUS)).booleanValue ()))
	            {
	            	m_boIsResultSuccessful = false;
 
	                m_sTransStatus = ResourcesUtils.getUnsuccessful ();
	                m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_BANK_STD_LIMIT,
	                		new String [] { FormatterUtils.formatMoneyDisplay ((String) m_oStdBankingLimitReturnMap.get (ThirdPartyTransferTags.MAX_LIMIT),
	                				CurrencyCode.MALAYSIA_RINGGIT, true) });	
	            }
	            else
	            {
					ESBAccountEnquiryTC100Bean m_oTCEnquiryBean = getESBServices ().getAccountDetailsTC100 (m_sFromAccount);
					if (!DataValidator.isEmptyString (m_oTCEnquiryBean.getAvailable_Bal ()))
					{
						m_dAvailableBal = Double.parseDouble (m_oTCEnquiryBean.getAvailable_Bal ());
					}

					m_dTotalTransferAmount = Double.parseDouble (m_sAmount);

					if(m_dAvailableBal < m_dTotalTransferAmount)
					{
						m_boIsFundSufficient = false;
						m_boIsResultSuccessful = false;
						m_sTransStatus = ResourcesUtils.getUnsuccessful ();
						m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (SIConstants.RESOURCES_INSUFFICIENT_FUND);
					}

					if (m_boIsFundSufficient)
					{
						/*
		            	 * do transfer
		            	 */
						try
						{
							ESBCompanyProfileBean toAccProfile = getESBServices ().getProfileByAccRim(m_sToRegAccount, null);
		            		String toAccRimo = toAccProfile.getRimNo();
		            		
							m_oReturnedESBBean = getESBServices ().intrabankFundTransfer (
								ESBConstants.FUND_TRANSFER_3RD, m_sFromAccount, m_sToRegAccount, m_sUserTransferRef, otherPaymentDetails, m_sAmount, m_sEffectiveDate, senderName, m_sAccountHolderName, toAccRimo);
							
							m_sResponseCode = m_oReturnedESBBean.getResponseCode ().trim ();
							if (ESBConstants.IB_SUCCESS_RC.equalsIgnoreCase (m_sResponseCode))
							{
								m_sTransStatus = ResourcesUtils.getSuccessful ();
								m_boIsResultSuccessful = true;
								m_boToDisplayNewBal = true;
								
								 m_sHostRefNo = m_oReturnedESBBean.getReferenceNo ().trim ();
								 
								 m_sFromAccNewBalance = FormatterUtils.formatMoneyDisplay (
										 DataValidator.isEmptyString (m_oReturnedESBBean.getFromAccountBalance ().trim ()) ? "0"
		 										: m_oReturnedESBBean.getFromAccountBalance ().trim (),
												 m_sFromIsoCurrency, true);
								 
								 m_sToAccNewBalance = FormatterUtils.formatMoneyDisplay (
										 DataValidator.isEmptyString (m_oReturnedESBBean.getToAccountBalance ().trim ()) ? "0"
		 										: m_oReturnedESBBean.getToAccountBalance ().trim (),
												 m_sFromIsoCurrency, true);
							}
							else
							{
								m_boIsResultSuccessful = false;

								m_sTransStatus = ResourcesUtils.getUnsuccessful ();
								m_sTransStatusMsg = m_oReturnedESBBean.getErrorMessage ();
							}
						}
						catch (IBBusinessException esbBusinessException)
						{
							/*
							 * catches Business Exception from ESB.intrabankFundTransfer()
							 */
							m_boIsResultSuccessful = false;

							m_sTransStatus = ResourcesUtils.getUnsuccessful ();
							m_sTransStatusMsg = esbBusinessException.getErrorMessage ();
						}
						m_sFrmAccCrtDt = m_oReturnedESBBean.getFromAccountCreateDate();
						m_sToAccCrtDt = m_oReturnedESBBean.getToAccountCreateDate();
					}
		        }
            }
			else	// create SI transaction
            {
				/*
				 * check SI limit against amount per transaction
				 */
				m_sServiceCode = m_sSIServiceCode;
				m_oSIServiceInfoBean = IBUtils.getServiceInfoBean (m_sServiceCode, getIBDynaBean (), getIBSessionObjects (), false);
	            m_sSIServiceMaxLimit = (String) m_oSIServiceInfoBean.get (ServiceInfo.BEAN_ATT_MAX_LIMIT);

				Map m_oSIBankLimitReturnMap = IB3rdPartyTransferBaseServices.checkIntraTransferDailyLimit (this,
	            		getIBDynaBean (), getIBSessionObjects (), m_sLocalAmountStr, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler , residencyType);

				m_fUserLimit = IBFundTransferDBUtils.getUserTransferLimit (getIBSessionObjects (), m_sServiceCode, m_boIsScheduler);

	            Map m_oSIUserLimitReturnMap = IB3rdPartyTransferBaseServices.checkIntraTransferDailyLimitByServiceCode (this,
						m_sLocalAmountStr, m_sSIServiceMaxLimit, m_fUserLimit, m_sServiceCode, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler ,residencyType ,
						m_oSIBankLimitReturnMap);
	            
	            /*
	             * check daily limit
	             */
	            
	            Map m_oStdBankingLimitReturnMap = IBStdDailyLimitBaseServices.checkBankDailyLimit(this, getIBDynaBean (), 
	            		getIBSessionObjects (), m_sAmount , specialDailyLimit, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler , residencyType);
	            
	            Map m_oStdUserLimitReturnMap = IBStdDailyLimitBaseServices.checkUserDailyLimit(this, getIBDynaBean (), 
	            		getIBSessionObjects (), m_sAmount , userDailyLimit, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler);
	            
	            if (!((Boolean) m_oSIUserLimitReturnMap.get (ThirdPartyTransferTags.STATUS)).booleanValue ())
				{
	            	m_boIsResultSuccessful = false;

					m_sTransStatus = ResourcesUtils.getUnsuccessful ();
					m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_CHANGE_MAX_AMOUNT,
							new String [] { FormatterUtils.formatMoneyDisplay ((String) m_oSIBankLimitReturnMap.get (SIConstants.MAX_LIMIT),
									CurrencyCode.MALAYSIA_RINGGIT, true) });
					
				}
	            else if ((!((Boolean) m_oSIBankLimitReturnMap.get (ThirdPartyTransferTags.STATUS)).booleanValue ())&&(0 <= specialDailyLimit.floatValue()))
	            {
	            	m_boIsResultSuccessful = false;

	                m_sTransStatus = ResourcesUtils.getUnsuccessful ();
	                m_sTransStatusMsg = ResourcesUtils.getBusinessExceptionErrorMessage (IBBusinessException.SI, SIConstants.ERR_BANK_MAX_LIMIT,
							new String [] { FormatterUtils.formatMoneyDisplay ( (String)m_oSIBankLimitReturnMap.get (SIConstants.MAX_LIMIT),
									CurrencyCode.MALAYSIA_RINGGIT, true) });
	            }
	            else if (!((Boolean) m_oStdUserLimitReturnMap.get (ThirdPartyTransferTags.STATUS)).booleanValue ())
	            {
	            	m_boIsResultSuccessful = false;

	                m_sTransStatus = ResourcesUtils.getUnsuccessful ();
	                m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_USER_STD_LIMIT,
 	                		new String [] { FormatterUtils.formatMoneyDisplay (String.valueOf(specialDailyLimit) ,
 	                				CurrencyCode.MALAYSIA_RINGGIT, true) });
	                
//	                m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_USER_STD_LIMIT,
//	                		new String [] { FormatterUtils.formatMoneyDisplay ((String) m_oStdUserLimitReturnMap.get (ThirdPartyTransferTags.MAX_LIMIT),
//	                				CurrencyCode.MALAYSIA_RINGGIT, true) });
	            }
	            else if ((!((Boolean) m_oStdBankingLimitReturnMap.get (ThirdPartyTransferTags.STATUS)).booleanValue ()))
	            {
	            	m_boIsResultSuccessful = false;
 
	                m_sTransStatus = ResourcesUtils.getUnsuccessful ();
	                m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyTransferTags.ERR_BANK_STD_LIMIT,
	                		new String [] { FormatterUtils.formatMoneyDisplay ((String) m_oStdBankingLimitReturnMap.get (ThirdPartyTransferTags.MAX_LIMIT),
	                				CurrencyCode.MALAYSIA_RINGGIT, true) });	
	            }
	            else
	            {
//	            	SI created. Will pending on scheduler.
					m_boIsResultSuccessful = true;
					m_sTransStatus = ResourcesUtils.getAccepted ();
	            }
            }

			if (m_boIsResultSuccessful)
			{
				if (SI_PAYMENT_MODE.PAY_NOW.getCode ().equals (m_sPaymentMode))
				{
                    if (!DataValidator.isEmptyString (m_sEmail))
					{
                    	/*
                    	 * email transfer notification to recipient
                    	 */
                    	String m_sSubject = ResourcesUtils.getApplicationResourceMessage ("ib104.thirdparty.email.subject");
                    	String m_sCustomerName = getIBSessionObjects ().getVisitor ().getStringValue (AccessConstants.VISITOR_LAST_NAME);

                    	StringBuffer m_sbEmailMsg = new StringBuffer ();
                    	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.thirdparty.email.greetCustomer", new String [] {m_sSubject, m_sAccountHolderName} ));
                    	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.thirdparty.email.note1",
                    			new String [] {m_sCustomerName,
                    				DateTimeUtils.formatDayMonthYear (m_oCurrentBVIDateTime).concat (" ").concat (m_oCurrentBVIDateTime.getTime()) } ));

                    	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"), 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.transferReference"),
                    			DataValidator.isEmptyString (m_sUserTransferRef) ? "-" : m_sUserTransferRef, null, null)).append("\n");
                    	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("E", ResourcesUtils.getApplicationResourceMessage ("ib104.other.payment.details"),
                    			DataValidator.isEmptyString (otherPaymentDetails) ? "-" : otherPaymentDetails, null, null)).append("\n");

                    	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.thirdparty.email.note2"));
                    	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.thirdparty.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 ("general.beneficiary.name"), m_sAccountHolderName);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.status"), m_sTransStatus);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.toAccount"), m_sToRegAccount);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.amount"), m_sAmountDis);

                if (!DataValidator.isEmptyString (m_sUserTransferRef))
                {
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.transferReference"), m_sUserTransferRef);
                }
                if (!DataValidator.isEmptyString (otherPaymentDetails))
                {
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.other.payment.details"), otherPaymentDetails);
                }
                if (!DataValidator.isEmptyString (m_sEmail))
                {
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.beneficiary.email"), m_sEmail);
                }
                if (!DataValidator.isEmptyString (m_sPaymentModeDisplay))
				{
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib112.si.payment.mode"), m_sPaymentModeDisplay);
				}
				if (!DataValidator.isEmptyString (m_sPaymentFrequencyDisplay))
				{
					m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.payment.frequency"), m_sPaymentFrequencyDisplay);
				}
				if (!DataValidator.isEmptyString (m_sEffectiveDateDisplay))
				{
					m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.start.date"), m_sEffectiveDateDisplay);
				}
				if (!DataValidator.isEmptyString (m_sTerminationDateDisplay))
				{
					m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.terminate.date"), m_sTerminationDateDisplay);
				}
                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"),
                		DateTimeUtils.formatDayMonthYear (m_oCurrentBVIDateTime));
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.transaction.time"),
                		m_oCurrentBVIDateTime.getTime ());

                /*
                 * 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 (ThirdPartyTransferTags.REG_THIRDPARTY_TRANSFER_FORM, VIEWBEAN);
                m_oViewBean.set (CommonConstants.RECEIPT_LINK, m_sReceiptLink);
			}

			StringBuffer m_sbDescription = new StringBuffer (ThirdPartyTransferTags.DESC_TRANSFER_INTRA_REGISTERED)
            	.append (" (")
            	.append (m_sAccountHolderName)
            	.append (")");

			if (!DataValidator.isEmptyString (m_sHostRefNo))
			{
				m_sbDescription.append ("<br>")
	            	.append ("(")
	            	.append (ResourcesUtils.getApplicationResourceMessage ("general.reference.number.short")).append (": ").append (m_sHostRefNo)
	            	.append (")");
			}

			/*
			 * log into IB_INTRA_TRANSFER
			 */
			IBLogger.logTransfer (this,
					m_sTransId,
					m_sServiceName,
					m_oCurrentBVIDateTime,
					m_sFromAccount,
					m_sFromIsoCurrency,
					m_sToRegAccount,
					m_sToIsoCurrency,
					m_sLocalAmountStr,
					m_sAmount,
					m_sUserTransferRef,
					otherPaymentDetails,
					m_sTransStatus,
					m_sTransStatusMsg,
					DateTimeUtils.convertStringToBVIDateTime (m_sEffectiveDate, "yyyyMMdd"),
					getIBSessionObjects ().getRemoteIPAddress (),
					m_sbDescription.toString (),
					m_sHostRefNo,
					m_sServiceCode,
					"","",
					m_sFrmAccCrtDt,
					m_sToAccCrtDt,
					m_sAccountHolderName,
					m_sEmail,
					String.valueOf (DataUtils.convertBooleanToInt (m_boSIIndicator)),
					senderName);

			/*
			 * 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_sToRegAccount,
					m_sToIsoCurrency,
					m_sAmount,
					m_sbDescription.toString (),
					m_sTransStatus,
					"","",
					m_sEffectiveDate,
					getIBSessionObjects ().getRemoteIPAddress (),
					"",
					m_boIsResultSuccessful,
					m_sHostRefNo,
					"",
					"","",
					getIBSessionObjects ().getIBSessionId (),
					"","","",
					m_sFrmAccCrtDt,
					m_sToAccCrtDt,
					m_sTransStatusMsg,
					m_sPaymentMode,
					m_sPayFrequency,
					m_sTerminationDate,
					"","","","","","","","","","");

			if (m_boSIIndicator && m_boIsResultSuccessful)
			{
				IBLogger.logSIDetail (
						this,
						m_sTransId,
						m_sTransId,
						SIConstants.TRANSCODE_INTRA_TRANSFER,
						m_sServiceName,
						m_sPaymentMode,
						m_sPayFrequency,
						m_sEffectiveDate,
						m_sTerminationDate,
						m_sServiceCode,
						m_boDeleteSIIndicator
						);
			}

			if (ResourcesUtils.getAccepted ().equalsIgnoreCase (m_sTransStatus))
			{
				m_sTransStatus = ResourcesUtils.getApplicationResourceMessage ("ib104.statusMessage");
			}

			m_oViewBean.set (ThirdPartyTransferTags.REFERENCE_NO, m_sFormattedTransId);
			m_oViewBean.set (ThirdPartyTransferTags.HOST_REFERENCE_NO, m_sHostRefNo);
			m_oViewBean.set (ThirdPartyTransferTags.IS_RESULT_SUCCESSFUL, Boolean.valueOf (m_boIsResultSuccessful));
			m_oViewBean.set (ThirdPartyTransferTags.STATUS, m_sTransStatus);
			m_oViewBean.set (ThirdPartyTransferTags.REASON, m_sTransStatusMsg);

			/*
			 * TO_DISPLAY_NEW_BALANCE: based on schedule date, if today then display balance, else do not display.
			 */
			m_oViewBean.set (ThirdPartyTransferTags.TO_DISPLAY_NEW_BALANCE, Boolean.valueOf (m_boToDisplayNewBal));
			m_oViewBean.set (ThirdPartyTransferTags.FROM_ACCT_NEW_BAL, m_sFromAccNewBalance);
			m_oViewBean.set (ThirdPartyTransferTags.TRANS_DATE, DateTimeUtils.formatDayMonthYear (m_oCurrentBVIDateTime));
			m_oViewBean.set (ThirdPartyTransferTags.TRANS_TIME, m_oCurrentBVIDateTime.getTime());

//			 SMS Notification START
			String m_sCustomerSMSMessage = "-";
			String m_sBeneficiarySMSMessage = "-";

			String m_sFormatAmount = SMSServices.formatAmountValue(m_sAmount, m_sFromIsoCurrency);
			String m_sTransactionTypeForSMSMessage = ResourcesUtils.getApplicationResourceMessage(SMSConstants.RESOURCE_SMS_TEXT_MESSAGE_SERVICE_THIRD);
			
			m_sCustomerSMSMessage = SMSServices.generateCustomerSMSMessage(
					m_sTransactionTypeForSMSMessage, 
					m_sFormatAmount,
					m_sAccountHolderName.length()>15?m_sAccountHolderName.substring(0, 15):m_sAccountHolderName,
					m_sTransStatus, 
					new Date(),
					m_sFromAccNewBalance);
			
			SMSServices.sendCustomerSMS(this, 
					m_oViewBean, 
					m_sFromAccount, 
					m_sTransStatus, 
					getIBDynaBean().get(SIConstants.PAY_MODE).toString(), 
					m_sServiceName, 
					m_sTransId,
					m_sAmount, 
					getIBSessionObjects().getVisitor().getId(), 
					m_sCustomerSMSMessage, 
					m_oCurrentBVIDateTime,
					SMSConstants.DEBIT_IB_TYPE);
			
			m_sBeneficiarySMSMessage = SMSServices.generateBeneficiarySMSMessage( 
					m_sTransactionTypeForSMSMessage, 
					m_sFormatAmount, 
					new Date(), 
					m_sToAccNewBalance);
			
			SMSServices.sendBeneficiarySMS(this, 
					getIBDynaBean(),
					m_oViewBean, 
					m_sFromAccount, 
					m_sTransStatus, 
					getIBDynaBean().get(SIConstants.PAY_MODE).toString(), 
					m_sServiceName, 
					m_sTransId,
					getIBSessionObjects().getVisitor().getId(), 
					m_sBeneficiarySMSMessage, 
					m_oCurrentBVIDateTime,
					SMSConstants.CREDIT_IB_TYPE);
			
			ESBAccountEnquiryTC100Bean m_oTCEnquiryBean = getESBServices ().getAccountDetailsTC100 (m_sFromAccount);
			
			m_oViewBean.set (ThirdPartyTransferTags.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 (VIEWBEAN, m_oViewBean);

			
			//#-- added by pixa 20130111 start(joo)
            try{
            	String ChannelObj = "";
            	Date fromAccCreateDate = null;
            	Date toAccCreateDate = 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_sFrmAccCrtDt))
        						fromAccCreateDate = timestampFormat.parse(m_sFrmAccCrtDt);
        			}
                	catch (Exception e)
            		{
                		e.printStackTrace();
            		}
        			
        			try{
        				if(!DataValidator.isEmptyString ((String)m_sToAccCrtDt))
        					toAccCreateDate = timestampFormat.parse(m_sToAccCrtDt);
        			}
                	catch (Exception e)
            		{
                		e.printStackTrace();
            		}
        			
        			try{
        				if(!DataValidator.isEmptyString ((String)m_sEffectiveDate))
        				{
        					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(getIBSessionObjects ().getVisitor ().getStringValue (AccessConstants.VISITOR_RIM_NO));
        			m_oMobileTransaction.setUsername(getIBSessionObjects ().getVisitor ().getName());
        			m_oMobileTransaction.setCustomerName(getIBSessionObjects ().getVisitor ().getStringValue (AccessConstants.VISITOR_LAST_NAME));
        			m_oMobileTransaction.setIbTransactionId(m_sTransId);
        			m_oMobileTransaction.setTransactionType("1041");
        			m_oMobileTransaction.setFromAccount(m_sFromAccount);
        			m_oMobileTransaction.setFromCy(m_sFromIsoCurrency);
        			m_oMobileTransaction.setToAccount(m_sToRegAccount);
        			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_sHostRefNo);
        			m_oMobileTransaction.setEpayReference("");
        			m_oMobileTransaction.setPhoenixRevertReferenceNo("");
        			m_oMobileTransaction.setPhoenixChargesReferenceNo("");
        			m_oMobileTransaction.setPhoenixRevertChargesReferen("");
        			m_oMobileTransaction.setDetails(m_sbDescription.toString());
        			if(fromAccCreateDate != null)
        				m_oMobileTransaction.setFromAccountCreationDate(fromAccCreateDate);
        			if(toAccCreateDate != null)
        				m_oMobileTransaction.setToAccountCreationDate(toAccCreateDate);
        			m_oMobileTransaction.setType("IN");
        			m_oMobileTransaction.setPaymentMode(m_sPaymentMode);
        			
        			//m_sbDescription.toString()
        			IntrabankFundTransfer m_oIntrabankFundTransfer = new IntrabankFundTransfer();
        			m_oIntrabankFundTransfer.setLocalAmount(Double.parseDouble(m_sLocalAmountStr));
        			m_oIntrabankFundTransfer.setRemark("");
        			m_oIntrabankFundTransfer.setServiceCode(m_sServiceCode);
        			m_oIntrabankFundTransfer.setRejectMessage(m_sTransStatusMsg);
        			m_oIntrabankFundTransfer.setAccountHolderName(m_sAccountHolderName);
        			m_oIntrabankFundTransfer.setBeneficiaryEmail(m_sEmail);			
        			HibernateOnlineMobileReportsUtils.insertIntraTransbankTransferStore(m_oMobileTransaction, m_oIntrabankFundTransfer);
	            }
            }
        	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);
	}
}
