/**
 * VALLABH KADAM 
 * EmpMaritalStatusCancel.java
 * Req Id:-[A16DSUN005]
 * */

package ibase.webitm.ejb.adm.adv;

import java.rmi.RemoteException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import ibase.utility.CommonConstants;
//import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;
//import ibase.utility.EMail;
import ibase.webitm.ejb.*;
import ibase.system.config.*;

//import javax.ejb.Stateless;
import javax.naming.InitialContext;

import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.adm.AdmCommon;
//import ibase.webitm.utility.GenericUtility;
//import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;
//import ibase.webitm.utility.TransIDGenerator;
import javax.ejb.Stateless; // added for ejb3

import org.apache.poi.ss.formula.ptg.RefNPtg;

@Stateless
public class EmpMaritalStatusCancel extends ActionHandlerEJB implements EmpMaritalStatusCancelLocal,EmpMaritalStatusCancelRemote
{	
	int updateMaritalChgCount=0;
	E12GenericUtility genericUtility= new  E12GenericUtility();
	
	@Override	
	public String actionHandler() throws RemoteException,ITMException
	{
		return "";
	}
	public String actionHandler(String tranID, String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		System.out.println("EmpMaritalStatusCancel.actionHandler()");
		System.out.println("\t tranId : " + tranID + "\n\t xtraParams" + xtraParams + "\n\t forcedFlag" + forcedFlag);
		String  retString = null;
		UserInfoBean userInfoBean=null;
		retString = actionHandler(tranID, xtraParams, forcedFlag, userInfoBean);
		return retString;
	}
	
	public String actionHandler(String tranID, String xtraParams, String forcedFlag, UserInfoBean userInfoBean) throws RemoteException,ITMException
	{
		System.out.println("EmpMaritalStatusCancel.actionHandler()");
		System.out.println("\t tranId : " + tranID + "\n\t xtraParams" + xtraParams + "\n\t forcedFlag" + forcedFlag);

		String  retString = null;
//		E12GenericUtility genericUtility = new E12GenericUtility();
		try
		{
			retString = actionCancel(tranID, xtraParams, forcedFlag);
		}
		catch(Exception e)
		{
			System.out.println("Exception :LoanOpeningCncEJB :actionHandler :" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println("returning String from LoanOpeningCncEJB :actionHandler :"+retString);
		return retString;
	}
    public String actionCancel(String tranID, String xtraParams, String forcedFlag) throws RemoteException, ITMException
//    public String  confirm(String tranID, String xtraParams, String forcedFlag) throws RemoteException, ITMException
    {
	    // TODO Auto-generated method stub
		
		System.out.println("Inside EmpMaritalStatusCancel cancel() method");
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt1=null;
		ResultSet rs = null;
		String sql = "", sql1 = "";
		ConnDriver connDriver = null;
		Timestamp tranDateTimestamp=null;
		Timestamp statusDateTimeStamp=null;
		Timestamp tranDate=null;
		Timestamp chgDate=null;
		Timestamp frDate=null;
		Timestamp toDate=null;
		
		InitialContext initialCtx = null;
		ITMDBAccessLocal itmDBAccess = null;
		AppConnectParm appConnect = null;
		AdmCommon admCommon=null;
		PayrollVoucherConfLocal payrollVoucherConf = null;
		
		boolean latestTran=true;
		
		ArrayList<String> errList = new ArrayList<String>();
		ArrayList<String> errFields = new ArrayList<String>();
		
		String empCode = "",tranDateStr="";
		String loginEmpCode = "", shortName = "", empFName = "", empMName = "", empLName = "", loginCode = "", chgTerm = "",
				newStatus="",amount="",confirmStatus="",voucherNo="",chgUser="",msgType="",autoPost="";
		String prvEmpFname="",prvEmpMname="",prvEmpLname="",prvSpouseName="",prvShortName="",oldStatus="",retString="";
		
		String paySite="",withHeld="",empCctrCodeSal="",empBankCode="",empDeptCode="";
		Date relieveDate = null;
		
		String tranType="",reffNo="",bankCode="",autoPay="",payMode="",siteCode="",finEntity="",remarks="",analCode="",confirmed="",paid="",
				acctCodePay="",cctrCodePay="",entryBatchNo="",vouchType="",currCode="",exchRate="",hold="",newVouchNo="",siteCodeAcct="",xmlString="",
				acctCode="",cctrCode="",adCode="";
		double totAmt=0.00,totAmtBc=0.00,amountDet=0.00;
		
		Timestamp vouchDate=null,effDate=null,reffDate=null,refDate=null;
		String winName = "w_payr_voucher";
		int lineNo=0;
		
		connDriver = null;
		String errString = "";
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		int cnt=0;
		Timestamp sysDate = null;
		E12GenericUtility genericUtility=new E12GenericUtility();
		StringBuffer xmlBuff=null;		
		
		try
        {
	        connDriver = new ConnDriver();
	        conn = connDriver.getConnectDB("DriverITM");
	        connDriver = null;
	        conn.setAutoCommit(false);
	        
	        appConnect = new AppConnectParm();
			initialCtx = new InitialContext(appConnect.getProperty());
	        itmDBAccess = (ITMDBAccessLocal)initialCtx.lookup("ibase/ITMDBAccessEJB/local");
	        
	        
	        Calendar currentDate = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			String sysDateStr = sdf.format(currentDate.getTime());
			
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			System.out.println("CHG_term 111 :- ["+chgTerm+"]");
			System.out.println("CHG_user 111 :- ["+chgUser+"]");
			
			chgDate=Timestamp.valueOf(genericUtility.getValidDateString(sysDateStr, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat())
					+ " 00:00:00.0");
//			UserInfoBean userInfoBean=new UserInfoBean();
//			chg_term=userInfoBean.getRemoteHost();
//			chg_user=userInfoBean.getLoginCode();
//			System.out.println("CHG_term 222 :- ["+chg_term+"]");
//			System.out.println("CHG_user 222 :- ["+chg_user+"]");
			
	        System.out.println("@V@ Tran Id fornd by transaction :- ["+tranID+"]");
	        String pkArray[]=tranID.split(":");
	        System.out.println("@V@ PK array length :-["+pkArray.length+"]");
	        System.out.println("@V@ Tran date :- ["+pkArray[0]+"]");
	        System.out.println("@V@ Emp code :- ["+pkArray[1]+"]");
	        
//	        tranDateStr = genericUtility.getValidDateTimeString(pkArray[0], genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
	        tranDateStr = pkArray[0];
//	        tranDateTimestamp = Timestamp.valueOf(pkArray[0]);
	        tranDateTimestamp = Timestamp.valueOf(genericUtility.getValidDateTimeString(pkArray[0], genericUtility.getApplDateFormat()
	        		,genericUtility.getDBDateFormat()));
	        empCode=pkArray[1];
	        
	        sql = "SELECT NEW_STATUS, SHORT_NAME, EMP_FNAME, EMP_MNAME, EMP_LNAME, STATUS_DATE, AMOUNT, CONFIRM,VOUCHER_NO," +
	        		" EMP_FNAME__O, EMP_MNAME__O, EMP_LNAME__O, SHORT_NAME__O,OLD_STATUS" +
					" FROM EMP_MARITALCHG WHERE EMP_CODE = ? AND TRAN_DATE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			pstmt.setTimestamp(2, tranDateTimestamp);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				newStatus = checkNull(rs.getString("NEW_STATUS"));
				shortName = replaceNull(rs.getString("SHORT_NAME"));
				empFName = replaceNull(rs.getString("EMP_FNAME"));
				empMName = replaceNull(rs.getString("EMP_MNAME"));
				empLName = replaceNull(rs.getString("EMP_LNAME"));
				statusDateTimeStamp = rs.getTimestamp("STATUS_DATE");
				amount = checkNull(rs.getString("AMOUNT"));
				confirmStatus = checkNull(rs.getString("CONFIRM"));
				voucherNo = checkNull(rs.getString("VOUCHER_NO"));
				prvEmpFname = checkNull(rs.getString("EMP_FNAME__O"));
				prvEmpMname = checkNull(rs.getString("EMP_MNAME__O"));
				prvEmpLname = checkNull(rs.getString("EMP_LNAME__O"));
				prvShortName = checkNull(rs.getString("SHORT_NAME__O"));
				oldStatus = checkNull(rs.getString("OLD_STATUS"));
			}
			pstmt.close();
			pstmt=null;
			rs.close();
			rs=null;
			
			System.out.println("@V@ amount :-[" + amount+"]");
			System.out.println("newStatus :-[" + newStatus+"]");
			System.out.println("statusDate :-[" + statusDateTimeStamp+"]");
			System.out.println("empFName :-[" + empFName+"]");
			System.out.println("empMName :-[" + empMName+"]");
			System.out.println("empLName :-[" + empLName+"]");        
			
			/**
			 * Select all tran date
			 * */
			ArrayList<Timestamp> tranDateAll=new ArrayList<Timestamp>();
			sql = "SELECT TRAN_DATE FROM EMP_MARITALCHG WHERE EMP_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				tranDate = rs.getTimestamp("TRAN_DATE");
				tranDateAll.add(tranDate);
			}
			pstmt.close();
			pstmt=null;
			rs.close();
			rs=null;
			
			for(Timestamp tempDate:tranDateAll)
			{
				if(tranDateTimestamp.before(tempDate))
				{
					latestTran=false;
					break;
				}
			}
			/**
			 * Check transaction is already Canceled
			 * */
			if("X".equalsIgnoreCase(confirmStatus))
			{
//				errString = itmDBAccess.getErrorString("", "VTALRDCACL", "", "", conn);
//				return errString;
				errList.add("VTALRDCACL");
				errFields.add("confirm");
			}
			/**
			 * Check Transaction is latest
			 * */
			if(!latestTran)
			{
				System.out.println("@V@ Transaction is OLD ..");
//				errString = itmDBAccess.getErrorString("", "VTOLDUPDT", "", "", conn);
//				return errString;
				errList.add("VTOLDUPDT");
				errFields.add("tran_date");
			}
			else
			{
				System.out.println("@V@ Transaction is NEW ..");
			}
			
			/**
			 * Check the old voucher voucher
			 * is in same financial year 
			 * */
			if(voucherNo!=null && voucherNo.trim().length()>0)
			{
				sql = "select fr_date,to_date from acctprd where ?  between fr_date and to_date";
				pstmt = conn.prepareStatement(sql);
				pstmt.setTimestamp(1, chgDate);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					frDate = rs.getTimestamp("fr_date");
					toDate = rs.getTimestamp("to_date");
				}							
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;	
				
				sql = "select count(1) from PAYR_VOUCHER where tran_date between ? AND ? and tran_id=?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setTimestamp(1, frDate);
				pstmt.setTimestamp(2, toDate);;
				pstmt.setString(3, voucherNo);;
				rs = pstmt.executeQuery();
				
				if (rs.next())
				{
					cnt = rs.getInt(1);
				}
				pstmt.close();
				pstmt=null;
				rs.close();
				rs=null;
				
				System.out.println("@V@ Count of the DATE query :- ["+cnt+"]");
//				cnt=1;
				if (cnt <= 0)
				{
//					errString = itmDBAccess.getErrorString("", "VTINVACTYR", "", "", conn);
//					return errString;
					errList.add("VTINVACTYR");
					errFields.add("tran_date");
				}
			}			
			
			int errListSize = errList.size();
			StringBuffer errStringXml = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root><Errors>");

			//ERRORLIST
			if (errList != null && errListSize > 0) 
			{
				for (int cnt1 = 0; cnt1 < errListSize; cnt1++) 
				{
					String errCode = (String) errList.get(cnt1);
					String errFldName = (String) errFields.get(cnt1);
					System.out.println("errCode .........." + errCode);
					System.out.println("errFldName .........." + errFldName);
					System.out.println("chg_user .........." + chgUser);
					ValidatorEJB vb=new ValidatorEJB();

					errString = vb.getErrorString(errFldName, errCode, chgUser);
					System.out.println("errString is : ::::>>>> " + errString);
					msgType = errorType(conn, errCode);
					if (errString.length() > 0)
					{
						String bifurErrString = errString.substring(errString.indexOf("<Errors>") + 8, errString.indexOf("<trace>"));
						bifurErrString = bifurErrString + errString.substring(errString.indexOf("</trace>") + 8, errString.indexOf("</Errors>"));
						errStringXml.append(bifurErrString);
						System.out.println("errStringXml .........." + errStringXml);
						errString = "";
					}
					if (msgType.equalsIgnoreCase("E")) 
					{
						break;
					}
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;

				errStringXml.append("</Errors></Root>\r\n");
			} 
			else 
			{
				errStringXml = new StringBuffer("");
			}
			errString = errStringXml.toString();
			
			/**
			 * Check NO ERROR BEFORE EXECUTION.
			 * */
			if(errString.trim().length()==0)
			{
			/**
			 * Select name prefix
			 * */
			String namePrefix = "", sex = "";
			sql = "SELECT NAME_PREFIX, SEX FROM EMPLOYEE WHERE EMP_CODE = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				namePrefix = checkNull(rs.getString("NAME_PREFIX"));
				sex = checkNull(rs.getString("SEX"));
			}
			pstmt.close();
			pstmt=null;
			rs.close();
			rs=null;		
			
			/**
			 * If Female
			 * From Married to Divorced, Separated 
			 * */
			if("F".equalsIgnoreCase(sex) && "M".equalsIgnoreCase(newStatus))
			{
				namePrefix = "Miss";
				empFName=prvEmpFname;
				empMName=prvEmpMname;
				empLName=prvEmpLname;
				shortName=prvShortName;
			}
			
				/**
				 * Check voucher is generated
				 * */
				if("Y".equalsIgnoreCase(confirmStatus) && (voucherNo!=null && voucherNo.trim().length()>0))
				{
					System.out.println("@V@ In Reverce Voucher");
					/**
					 * Select voucher details
					 * */				
					sql = "SELECT CCTR_CODE__SAL, BANK_CODE, DEPT_CODE, RELIEVE_DATE, WITH_HELD, PAY_SITE FROM EMPLOYEE WHERE EMP_CODE = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, empCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						paySite = checkNull(rs.getString("PAY_SITE"));
						withHeld = checkNull(rs.getString("WITH_HELD"));
						relieveDate = rs.getDate("RELIEVE_DATE");
						empCctrCodeSal = rs.getString("CCTR_CODE__SAL");
						empBankCode = checkNull(rs.getString("BANK_CODE"));
						empDeptCode = checkNull(rs.getString("DEPT_CODE"));
					}
					pstmt.close();
					pstmt=null;
					rs.close();
					rs=null;
					
					sql = "SELECT FIN_ENTITY, SITE_CODE__ACCT FROM SITE WHERE SITE_CODE = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, paySite);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						siteCodeAcct = checkNull(rs.getString("SITE_CODE__ACCT"));
						finEntity = checkNull(rs.getString("FIN_ENTITY"));
					}
					pstmt.close();
					pstmt=null;
					rs.close();
					rs=null;
					
					int hdrUpdate=0, detUpdate=0;
					admCommon= new AdmCommon();
					autoPost = checkNull(admCommon.getEnv("999999", "AUTO_POST", conn));
					if("NULLFOUND".equalsIgnoreCase(autoPost))
					{
						retString = itmDBAccess.getErrorString("", "VSENVAR1", "", "", conn);
						return retString;
					}
					
//					xmlBuff=new StringBuffer();
//					
//					
//					xmlBuff.append("<?xml version='1.0' encoding='ISO-8859-1'?>\n");
//					xmlBuff.append("<DocumentRoot>");
//					xmlBuff.append("<description>").append("Datawindow Root").append("</description>");
//					xmlBuff.append("<group0>");
//					xmlBuff.append("<description>").append("Group0 description").append("</description>");
//					xmlBuff.append("<Header0>");
//					xmlBuff.append("<objName><![CDATA[").append("payr_voucher").append("]]></objName>");
//					xmlBuff.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
//					xmlBuff.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
//					xmlBuff.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
//					xmlBuff.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
//					xmlBuff.append("<action><![CDATA[").append("SAVE").append("]]></action>");
//					xmlBuff.append("<elementName><![CDATA[").append("").append("]]></elementName>");
//					xmlBuff.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
//					xmlBuff.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
//					xmlBuff.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
//					xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
//					xmlBuff.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
//					xmlBuff.append("<description>").append("Header0 members").append("</description>");
					
					newVouchNo = generateTranId(winName, siteCodeAcct, tranDateStr, conn);
					System.out.println("@V@ tranId generated :: "+newVouchNo);
					
					sql="select TRAN_TYPE, EFF_DATE, EMP_CODE, REF_NO, REF_DATE, " +
							"BANK_CODE, AUTO_PAY, PAY_MODE, SITE_CODE, FIN_ENTITY, REMARKS, " +
							"ANAL_CODE, CONFIRMED, PAID, ACCT_CODE__PAY, CCTR_CODE__PAY, TOT_AMT, ENTRY_BATCH_NO, VOUCH_TYPE, " +
							"CURR_CODE, EXCH_RATE, TOT_AMT__BC, HOLD from PAYR_VOUCHER where TRAN_ID=?";
					pstmt=conn.prepareStatement(sql);
					pstmt.setString(1, voucherNo);
					rs=pstmt.executeQuery();
					if(rs.next())
					{
						tranType=checkNull(rs.getString("TRAN_TYPE"));
						effDate=rs.getTimestamp("EFF_DATE");
						empCode=checkNull(rs.getString("EMP_CODE"));
//						refNo="RV-"+sysDateStr;
						refDate=rs.getTimestamp("REF_DATE");
						bankCode=checkNull(rs.getString("BANK_CODE"));
						autoPay=checkNull(rs.getString("AUTO_PAY"));
						payMode=checkNull(rs.getString("PAY_MODE"));
						siteCode=checkNull(rs.getString("SITE_CODE"));
						finEntity=checkNull(rs.getString("FIN_ENTITY"));
						remarks=checkNull(rs.getString("REMARKS"));
						analCode=checkNull(rs.getString("ANAL_CODE"));
						paid=checkNull(rs.getString("PAID"));
						acctCodePay=rs.getString("ACCT_CODE__PAY");
						cctrCodePay=rs.getString("CCTR_CODE__PAY");
						totAmt=rs.getDouble("TOT_AMT");
						entryBatchNo=checkNull(rs.getString("ENTRY_BATCH_NO"));
						vouchType=checkNull(rs.getString("VOUCH_TYPE"));
						currCode=checkNull(rs.getString("CURR_CODE"));
						exchRate=checkNull(rs.getString("EXCH_RATE"));
						totAmtBc=rs.getDouble("TOT_AMT__BC");
						hold=checkNull(rs.getString("HOLD"));					
						
						
//						xmlBuff.append("<Detail1 dbID=\"\" domID=\"1\" objName=\"payr_voucher\" objContext=\"1\">");
//						xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
//						xmlBuff.append("<tran_id/>");
//						xmlBuff.append("<tran_date><![CDATA[" + sysDateStr + "]]></tran_date>");
//						xmlBuff.append("<tran_type><![CDATA[" + checkNull(rs.getString("TRAN_TYPE")) + "]]></tran_type>");
//						
//						String effDateStr="";
//						if(rs.getTimestamp("EFF_DATE")== null)
//						{
//							effDateStr=sysDateStr;
//							System.out.println("@V@ effDateStr : -["+effDateStr+"]");
//						}
//						else
//						{
//							effDateStr=sdf.format(rs.getTimestamp("EFF_DATE").getTime());
//							System.out.println("@V@ effDateStr : -["+effDateStr+"]");
//						}						
//						xmlBuff.append("<eff_date><![CDATA[" + effDateStr + "]]></eff_date>");
//						
//						xmlBuff.append("<emp_code><![CDATA[" + checkNull(rs.getString("EMP_CODE")) + "]]></emp_code>");
////						xmlBuff.append("<ref_no><![CDATA[" + checkNull(rs.getString("REF_NO")) + "]]></ref_no>");
////						xmlBuff.append("<ref_no><![CDATA[" +"RV-"+checkNull(voucherNo) + "]]></ref_no>");
//						xmlBuff.append("<ref_no><![CDATA[" +"RV-"+sysDateStr+ "]]></ref_no>");
//						
//						String refDateStr="";
//						if(rs.getTimestamp("REF_DATE")==null)
//						{
//							refDateStr=sysDateStr;
//							System.out.println("@V@ refDateStr : -["+refDateStr+"]");
//						}
//						else
//						{
//							refDateStr=sdf.format(rs.getTimestamp("REF_DATE").getTime());
//							System.out.println("@V@ refDateStr : -["+refDateStr+"]");
//						}						
//						xmlBuff.append("<ref_date><![CDATA[" + refDateStr + "]]></ref_date>");
//						
//						xmlBuff.append("<bank_code><![CDATA[" + checkNull(rs.getString("BANK_CODE")) + "]]></bank_code>");
//						xmlBuff.append("<auto_pay><![CDATA[" + checkNull(rs.getString("AUTO_PAY")) + "]]></auto_pay>");
//						xmlBuff.append("<pay_mode><![CDATA[" + checkNull(rs.getString("PAY_MODE")) + "]]></pay_mode>");
//						xmlBuff.append("<chg_date><![CDATA[" + sysDateStr + "]]></chg_date>");
//						xmlBuff.append("<chg_term><![CDATA[" + checkNull(chgTerm) + "]]></chg_term>");
//						xmlBuff.append("<chg_user><![CDATA[" + checkNull(chgUser) + "]]></chg_user>");
//						xmlBuff.append("<site_code><![CDATA[" + checkNull(rs.getString("SITE_CODE")) + "]]></site_code>");
//						xmlBuff.append("<fin_entity><![CDATA[" + checkNull(rs.getString("FIN_ENTITY")) + "]]></fin_entity>");
//						xmlBuff.append("<remarks><![CDATA[" + checkNull(rs.getString("REMARKS")) + "]]></remarks>");
//						xmlBuff.append("<anal_code><![CDATA[" + checkNull(rs.getString("ANAL_CODE")) + "]]></anal_code>");
////						xmlBuff.append("<confirmed><![CDATA[" + checkNull(rs.getString("CONFIRMED")) + "]]></confirmed>");
//						xmlBuff.append("<confirmed><![CDATA[N]]></confirmed>");
//						xmlBuff.append("<paid><![CDATA[" + checkNull(rs.getString("PAID")) + "]]></paid>");
//						xmlBuff.append("<acct_code__pay><![CDATA[" + rs.getString("ACCT_CODE__PAY") + "]]></acct_code__pay>");
//						xmlBuff.append("<cctr_code__pay><![CDATA[" + rs.getString("CCTR_CODE__PAY") + "]]></cctr_code__pay>");
//						xmlBuff.append("<tot_amt><![CDATA[" + (rs.getDouble("TOT_AMT")*-1) + "]]></tot_amt>");
//						xmlBuff.append("<entry_batch_no><![CDATA[" + checkNull(rs.getString("ENTRY_BATCH_NO")) + "]]></entry_batch_no>");
//						xmlBuff.append("<vouch_type><![CDATA[" + checkNull(rs.getString("VOUCH_TYPE")) + "]]></vouch_type>");
//						xmlBuff.append("<curr_code><![CDATA[" + checkNull(rs.getString("CURR_CODE")) + "]]></curr_code>");
//						xmlBuff.append("<exch_rate><![CDATA[" + checkNull(rs.getString("EXCH_RATE")) + "]]></exch_rate>");
//						xmlBuff.append("<tot_amt__bc><![CDATA[" + checkNull(rs.getString("TOT_AMT__BC")) + "]]></tot_amt__bc>");
//						xmlBuff.append("<hold><![CDATA[" + checkNull(rs.getString("HOLD")) + "]]></hold>");
//						xmlBuff.append("</Detail1>");	
					}
					pstmt.close();
					pstmt=null;
					rs.close();
					rs=null;
					
					System.out.println("@V@ Inserting Payer_voucher");
					
					sql = " INSERT INTO PAYR_VOUCHER (TRAN_ID, TRAN_DATE, TRAN_TYPE, EFF_DATE, EMP_CODE, REF_NO, REF_DATE, " +
							"BANK_CODE, AUTO_PAY, PAY_MODE, CHG_DATE, CHG_USER, CHG_TERM, SITE_CODE, FIN_ENTITY, REMARKS, " +
							"ANAL_CODE, CONFIRMED, PAID, ACCT_CODE__PAY, CCTR_CODE__PAY, TOT_AMT, ENTRY_BATCH_NO, VOUCH_TYPE, " +
							"CURR_CODE, EXCH_RATE, TOT_AMT__BC, HOLD) "
							+" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, FN_SYSDATE(), ?, ?, ?, ?, ?, " +
							"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, newVouchNo);
					pstmt.setTimestamp(2, chgDate);
					pstmt.setString(3, tranType);
					pstmt.setTimestamp(4, effDate);
					pstmt.setString(5, empCode);
//					pstmt.setString(6, tranId);
					pstmt.setString(6, "RV-"+sysDateStr);
					pstmt.setTimestamp(7, refDate);
					pstmt.setString(8, empBankCode);
					pstmt.setString(9, autoPay);
					pstmt.setString(10, payMode);
					pstmt.setString(11, chgUser);
					pstmt.setString(12, chgTerm);
					pstmt.setString(13, siteCodeAcct);
					pstmt.setString(14, finEntity);
					pstmt.setString(15, remarks);
					pstmt.setString(16, analCode);
					pstmt.setString(17, confirmed);
					pstmt.setString(18, paid);
					pstmt.setString(19, acctCodePay);
					pstmt.setString(20, cctrCodePay);
					pstmt.setDouble(21, (totAmt*-1));
					pstmt.setString(22, entryBatchNo);
					pstmt.setString(23, vouchType);
					pstmt.setString(24, currCode);
					pstmt.setString(25, exchRate);
					pstmt.setDouble(26, totAmtBc);
					pstmt.setString(27, hold);
					int payrVoucherInsertCount = pstmt.executeUpdate();
					System.out.println("@V@ row insert into payr_voucher :: " + payrVoucherInsertCount);
					pstmt.close();
					pstmt=null;
					
					
					sql="select LINE_NO, ACCT_CODE, CCTR_CODE, AMOUNT, AD_CODE from PAYR_VOUCHDET where tran_id=?";
					pstmt=conn.prepareStatement(sql);
					pstmt.setString(1, voucherNo);
					rs=pstmt.executeQuery();
					while(rs.next())
					{
						
						lineNo=rs.getInt("LINE_NO");
						acctCode=checkNull(rs.getString("ACCT_CODE"));
						cctrCode=checkNull(rs.getString("CCTR_CODE"));
						amountDet=rs.getDouble("AMOUNT");
						adCode=rs.getString("AD_CODE");
						
						
//						xmlBuff.append("<Detail2 dbID='' domID='" + lineNo + "' objName=\"payr_voucher\" objContext=\"2\">");
//						xmlBuff.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
//						xmlBuff.append("<tran_id/>");
//						xmlBuff.append("<line_no><![CDATA["+lineNo+"]]></line_no>");
//						xmlBuff.append("<acct_code><![CDATA["+checkNull(rs.getString("ACCT_CODE"))+"]]></acct_code>");
//						xmlBuff.append("<cctr_code><![CDATA["+checkNull(rs.getString("CCTR_CODE"))+"]]></cctr_code>");
//						xmlBuff.append("<amount><![CDATA["+(rs.getDouble("AMOUNT")*-1)+"]]></amount>");
//						xmlBuff.append("<ad_code><![CDATA["+checkNull(rs.getString("AD_CODE"))+"]]></ad_code>");
//						xmlBuff.append("</Detail2>");
						
						System.out.println("@V@ Inserting Payer_voucher_det");
						
						sql1 = "INSERT INTO PAYR_VOUCHDET (TRAN_ID, LINE_NO, ACCT_CODE, CCTR_CODE, AMOUNT, AD_CODE) "
								+" VALUES (?, ?, ?, ?, ?, ?)";
						pstmt1 = conn.prepareStatement(sql1);
						pstmt1.setString(1, newVouchNo);
						pstmt1.setInt(2, lineNo);
						pstmt1.setString(3, acctCode);
						pstmt1.setString(4, cctrCode);
						pstmt1.setDouble(5, amountDet);
						pstmt1.setString(6, adCode);
						int payrVouchDetInsert = pstmt1.executeUpdate();
						System.out.println("@V@ row insert into payr_vouchdet " + payrVouchDetInsert);
						pstmt1.close();
						pstmt1=null;
					}
					pstmt.close();
					pstmt=null;
					rs.close();
					rs=null;
					
//					xmlBuff.append("</Header0>");
//					xmlBuff.append("</group0>");
//					xmlBuff.append("</DocumentRoot>");
//					xmlString = xmlBuff.toString();
//					System.out.println("@V@: xmlString:-["+xmlString+"]");
//					retString = saveData(siteCodeAcct,xmlString,conn);
//					System.out.println("@V@ : retString:-["+retString+"]");
//					if (retString.indexOf("Success") > -1)
//					{
//						String[] arrayForTranId = retString.split("<TranID>");
//						int endIndex = arrayForTranId[1].indexOf("</TranID>");
//						newVouchNo = arrayForTranId[1].substring(0, endIndex);
//						System.out.println("@V@ Reverce voucher Tran Id :- [" + newVouchNo + "]");
//						
//						sql="update payr_voucher set chg_term=?, chg_user=?, it_flag='' where tran_id=?";
//						pstmt=conn.prepareStatement(sql);
//						pstmt.setString(1, chgTerm);
//						pstmt.setString(2, chgUser);
//						pstmt.setString(3, newVouchNo);
//						int updCnt=pstmt.executeUpdate();						
//						System.out.println("@V@ Chg term, Chg User update cnt :- ["+updCnt+"]");
						
						if("Y".equalsIgnoreCase(autoPost))
						{
							payrollVoucherConf = (PayrollVoucherConfLocal)initialCtx.lookup("ibase/PayrollVoucherConf/local");
							retString = checkNull(payrollVoucherConf.confirm(newVouchNo, forcedFlag, xtraParams, conn));
						}										
						
						if(retString.length() > 0 && retString.indexOf("VTMCONF2") == -1 )
						{
							System.out.println("@V@ Payrol voucher confirmed..");
						}
						else
						{
							errString=retString;
						}

//					}
//					else
//					{
//						errString=retString;
//					}
				} // REVERSE Voucher END.
				/**
				 * CHECK NO ERROR in REVERCE VOUCHER
				 * */
				if(errString!=null && errString.trim().length()==0)
				{
					/**
					 * Update Employee details
					 * */
					sql = "UPDATE EMPLOYEE SET M_STATUS = ?, M_STATUS_DATE = ?, NAME_PREFIX = ?, EMP_FNAME = ?, " +
							"EMP_MNAME = ?, EMP_LNAME = ?, SHORT_NAME = ?, CHG_USER = ?, CHG_DATE = ?, CHG_TERM = ? " +
							"WHERE EMP_CODE = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, oldStatus);
					pstmt.setTimestamp(2, statusDateTimeStamp);
					pstmt.setString(3, namePrefix);
					pstmt.setString(4, empFName);
					pstmt.setString(5, empMName);
					pstmt.setString(6, empLName);
					pstmt.setString(7, shortName);
					pstmt.setString(8, chgUser);
					pstmt.setTimestamp(9, chgDate);
					pstmt.setString(10, chgTerm);
					pstmt.setString(11, empCode);
					int updateEmployeeCount = pstmt.executeUpdate();
					pstmt.close();
					pstmt=null;
					
					System.out.println("@V@ UpdateEmployee :- [" + updateEmployeeCount+"]");
					
					if(updateEmployeeCount>0)
					{
						/**
						 * Update EMP_MARITALCHG
						 * set CONFIRMED= 'X', CONF_DATE, REVS_VOUCHER_NO
						 * */
						
						sql = "UPDATE EMP_MARITALCHG SET CONFIRM = 'X', CONF_DATE = ?,REVS_VOUCHER_NO=? WHERE EMP_CODE = ? AND TRAN_DATE = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setTimestamp(1, chgDate); 
						pstmt.setString(2, newVouchNo); 
						pstmt.setString(3, empCode); 
						pstmt.setTimestamp(4, tranDateTimestamp);
						updateMaritalChgCount = pstmt.executeUpdate();
						pstmt.close();
						pstmt=null;
						
						System.out.println("@V@ UpdateMaritalChg :- [" + updateMaritalChgCount+"]");
					}	
					if(updateMaritalChgCount>0)
					{
						errString = itmDBAccess.getErrorString("", "VTCANSUCSS", "", "", conn);
					}
				} // NO ERROR in REVERCE VOUCHER				
			} // NO ERROR BEFORE EXECUTION.
			
        } 
		catch (SQLException e)
        {
	        e.printStackTrace();
        }
		catch (Exception e)
        {
	        e.printStackTrace();
        }
		finally 
		{
			try
			{
				if(!conn.isClosed())
				{
					if(updateMaritalChgCount>0)
					{
						conn.commit();		
					}
					else
					{
						conn.rollback();
					}				
				conn.close();
				}				
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}				
			}
			catch (Exception e)
			{
				System.out.println("Exception : " + e);
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		
	    return errString;
    }
    
    private String generateTranId( String windowName, String siteCode, String tranDateStr, Connection conn) throws ITMException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String selSql = "";
		String tranId = "";
		String tranSer = "";
		String keyString = "";
		String keyCol = "";
		String xmlValues = "";

		try
		{
			System.out.println("generateTranId() called...");

			selSql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
			pstmt = conn.prepareStatement(selSql);
			pstmt.setString( 1, windowName );
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				keyString = rs.getString("KEY_STRING");
				keyCol = rs.getString("TRAN_ID_COL");
				tranSer = rs.getString("REF_SER");
			}
//			close(pstmt, rs);
			pstmt.close();
			pstmt=null;
			rs.close();
			rs=null;
			
			System.out.println("keyString :"+keyString);
			System.out.println("keyCol :"+keyCol);
			System.out.println("tranSer :"+tranSer);

			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +		"<tran_id></tran_id>";
			xmlValues = xmlValues +		"<site_code>" + siteCode + "</site_code>";
			xmlValues = xmlValues +		"<tran_date>" + tranDateStr + "</tran_date>"; 
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator transIDGenerator = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			tranId = transIDGenerator.generateTranSeqID(tranSer, keyCol, keyString, conn);
			System.out.println("tranId :"+tranId);
		}
		catch (SQLException ex)
		{
			System.out.println("Exception :EmpMaritalStatusConf :generateTranId :SQLException ::" +selSql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			System.out.println("Exception :EmpMaritalStatusConf :generateTranId :Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return tranId;
	}
	private String errorType(Connection conn, String errorCode) throws ITMException 
	{
		String msgType = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try 
		{
			String sql = " SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO = ? ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, errorCode);
			rs = pstmt.executeQuery();
			while (rs.next()) 
			{
				msgType = rs.getString("MSG_TYPE");
			}
		} 
		catch (Exception ex) 
		{
			ex.printStackTrace();
			throw new ITMException(ex);
		} 
		finally 
		{
			try 
			{
				if (rs != null) 
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return msgType;
	}
	
	private String saveData(String siteCode,String xmlString, Connection conn) throws ITMException
	{
		System.out.println("saving data...........");
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; // for ejb3
		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
			masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");
			System.out.println("-----------masterStateful------- " + masterStateful);
			String [] authencate = new String[2];
			authencate[0] = "";
			authencate[1] = "";
			System.out.println("xmlString to masterstateful [" + xmlString + "]");
			retString = masterStateful.processRequest(authencate, siteCode, true, xmlString,true,conn);
			System.out.println("--retString - -"+retString);
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException :CreateDistOrder :saveData :==>");
			throw itme;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception :CreateDistOrder :saveData :==>");
			throw new ITMException(e);
		}
		return retString;
	}
//	private String generateTranId( String windowName, String siteCode, String tranDateStr, Connection conn) throws ITMException
//	{
//		PreparedStatement pstmt = null;
//		ResultSet rs = null;
//		String selSql = "";
//		String tranId = "";
//		String tranSer = "";
//		String keyString = "";
//		String keyCol = "";
//		String xmlValues = "";
//
//		try
//		{
//			System.out.println("generateTranId() called...");
//
//			selSql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
//			pstmt = conn.prepareStatement(selSql);
//			pstmt.setString( 1, windowName );
//			rs = pstmt.executeQuery();
//			if (rs.next())
//			{
//				keyString = rs.getString("KEY_STRING");
//				keyCol = rs.getString("TRAN_ID_COL");
//				tranSer = rs.getString("REF_SER");
//			}
//			pstmt.close();
//			pstmt=null;
//			rs.close();
//			rs=null;
//			
//			System.out.println("keyString :"+keyString);
//			System.out.println("keyCol :"+keyCol);
//			System.out.println("tranSer :"+tranSer);
//
//			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
//			xmlValues = xmlValues + "<Header></Header>";
//			xmlValues = xmlValues + "<Detail1>";
//			xmlValues = xmlValues +		"<tran_id></tran_id>";
//			xmlValues = xmlValues +		"<site_code>" + siteCode + "</site_code>";
//			xmlValues = xmlValues +		"<tran_date>" + tranDateStr + "</tran_date>"; 
//			xmlValues = xmlValues + "</Detail1></Root>";
//			System.out.println("xmlValues  :["+xmlValues+"]");
//			TransIDGenerator transIDGenerator = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
//			tranId = transIDGenerator.generateTranSeqID(tranSer, keyCol, keyString, conn);
//			System.out.println("tranId :"+tranId);
//		}
//		catch (SQLException ex)
//		{
//			System.out.println("Exception :EmpMaritalStatusConf :generateTranId :SQLException ::" +selSql+ ex.getMessage() + ":");
//			ex.printStackTrace();
//			throw new ITMException(ex);
//		}
//		catch (Exception e)
//		{
//			System.out.println("Exception :EmpMaritalStatusConf :generateTranId :Exception ::" + e.getMessage() + ":");
//			e.printStackTrace();
//			throw new ITMException(e);
//		}
//		finally
//		{
//			try
//			{
//				if (rs != null)
//				{
//					rs.close();
//					rs = null;
//				}
//				if (pstmt != null)
//				{
//					pstmt.close();
//					pstmt = null;
//				}
//			}
//			catch(Exception e)
//			{
//				e.printStackTrace();
//				throw new ITMException(e);
//			}
//		}
//		return tranId;
//	}
	private String checkNull(String input)
	{
		if (input == null || ("null").equalsIgnoreCase(input.trim()))
		{
			input = "";
		}
		else
		{
			input = input.trim();
		}
		return input;
	}
	
	private String replaceNull(String input)
	{
		if (input == null)
		{
			input = "";
		}
		return input;
	}
}
