/**
 * 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.ejb.sys.UtilMethods;
//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 confDtTimestamp=null,prvStatDtTimestamp=null;
		Timestamp tranDate=null;
		Timestamp chgDate=null;
		Timestamp frDate=null;
		Timestamp toDate=null;
		Timestamp confDate=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;
		String empMStatus="",empNamePrefix="",empFname="",empMname="",empLname="",empShortName="",empStatus="";
		String tempEmpFname="",tempEmpMname="",tempEmpLname="",tempEmpShortName="",cnfStat="",statusDateStr="";
		
		Timestamp vouchDate=null,effDate=null,reffDate=null,refDate=null,empMStatusDate=null;
		String winName = "w_payr_voucher";
		int lineNo=0;
		int updateEmployeeCount=0;
		long dayDiff=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");
	        
	        UtilMethods uMth=new UtilMethods();
	        
	        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");

			
	        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,CONF_DATE,STATUS_DATE__O" +
					" 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"));
				System.out.println("prvFNAME"+prvEmpFname);
				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"));
				confDtTimestamp = rs.getTimestamp("CONF_DATE");
				prvStatDtTimestamp = rs.getTimestamp("STATUS_DATE__O");
			}
			pstmt.close();
			pstmt=null;
			rs.close();
			rs=null;
			
			if(statusDateTimeStamp!=null){
				String statuscheck=statusDateTimeStamp.toString();
				try {
					statuscheck="";
				} catch (Exception e) {
					statuscheck="";
				}
			statusDateStr=genericUtility.getValidDateString(statusDateTimeStamp.toString(), genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
			System.out.println("@V@ Status date str :- ["+statusDateStr+"]");
			}
			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+"]");        
			
			
			/**
			 * Check un-confirmed transaction exist
			 * for employee 
			 * */
			sql = "select count(*) as cnt from emp_maritalchg" +
					" where (case when confirm is null then 'N' else confirm END ='N') and emp_code=? and tran_date <> ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			pstmt.setTimestamp(2, tranDateTimestamp);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				cnt = rs.getInt("cnt");
			}
			pstmt.close();
			pstmt=null;
			rs.close();
			rs=null;
			
			System.out.println("@V@ Un confirm transaction count :- ["+cnt+"]");
			if(cnt>0)
			{
				errList.add("VTUNCFEXT");
				errFields.add("confirm");
			}
			
			/**
			 * Select all confirm date
			 * */
//			ArrayList<Timestamp> tranDateAll=new ArrayList<Timestamp>();
			ArrayList<Timestamp> confDateAll=new ArrayList<Timestamp>();
			sql = "SELECT CASE WHEN CONFIRM IS NULL THEN 'N' ELSE CONFIRM END AS CONFIRM_STAT,CONF_DATE" +
					" FROM EMP_MARITALCHG WHERE EMP_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				cnfStat = rs.getString("CONFIRM_STAT");
				confDate = rs.getTimestamp("CONF_DATE");
				if("Y".equalsIgnoreCase(cnfStat))
				{
					confDateAll.add(confDate);
				}
			}
			pstmt.close();
			pstmt=null;
			rs.close();
			rs=null;
			
			if(confDtTimestamp!=null)
			{
				for(Timestamp tempDate:confDateAll)
				{
					if(confDtTimestamp.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 FN_CHECK_ACCOUNTING_YEAR(?,?,?,?) as err_code from dual";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, empCode);
				pstmt.setString(2, voucherNo);
				pstmt.setString(3, chgUser);
				pstmt.setString(4, tranDateStr);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					errString = rs.getString("err_code");
				}							
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				
				if(errString!=null && errString.trim().length()>0)
				{
					errList.add(errString);
					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";
				
				tempEmpFname=empFName;
				tempEmpMname=empMName;
				tempEmpLname=empLName;
				tempEmpShortName=shortName;
				
				empFName=prvEmpFname;
				empMName=prvEmpMname;
				empLName=prvEmpLname;
				shortName=prvShortName;
				
			}
			else
			{
				tempEmpFname=empFName;
				tempEmpMname=empMName;
				tempEmpLname=empLName;
				tempEmpShortName=shortName;
			}
			
			/**
			 * Select employee details
			 * */
			sql="select M_STATUS , M_STATUS_DATE , NAME_PREFIX , EMP_FNAME , EMP_MNAME , EMP_LNAME , SHORT_NAME, STATUS" +
					" from employee WHERE EMP_CODE = ?";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1,empCode);
			rs=pstmt.executeQuery();
			if(rs.next())
			{
				empMStatus=checkNull(rs.getString("M_STATUS"));
				empMStatusDate=rs.getTimestamp("M_STATUS_DATE");
				empNamePrefix=checkNull(rs.getString("NAME_PREFIX"));
				//modified by Santosh Gupta to check whether Fname,Lname,Mname are same EMP_MARITALCHG and employee(10/4/17)   
				//empFname=checkNull(rs.getString("EMP_FNAME"));
				//empMname=checkNull(rs.getString("EMP_MNAME"));
				//empLname=checkNull(rs.getString("EMP_LNAME"));
				empFname=replaceNull(rs.getString("EMP_FNAME"));
				empMname=replaceNull(rs.getString("EMP_MNAME"));
				empLname=replaceNull(rs.getString("EMP_LNAME"));
				//empShortName=checkNull(rs.getString("SHORT_NAME"));
				empShortName=replaceNull(rs.getString("SHORT_NAME"));
				empStatus=checkNull(rs.getString("STATUS"));
			}
			pstmt.close();
			pstmt=null;
			rs.close();
			rs=null;
			
			/**
			 * Check status date
			 * from EMPLOYEE and EMP_MARITALCHG
			 * are matching
			 * */
			System.out.println("@V@ Emp status date :- ["+empMStatusDate+"]");
			System.out.println("@V@ Marital status date :- ["+statusDateTimeStamp+"]");
			if("Y".equalsIgnoreCase(confirmStatus))
			{
				if((empMStatusDate!=null && statusDateTimeStamp!=null))
				{
					dayDiff=uMth.DaysAfter(empMStatusDate, statusDateTimeStamp);
					System.out.println("@V@ Days diffrence :- ["+dayDiff+"]");
					
					if(dayDiff!=0)
					{
						errString = itmDBAccess.getErrorString("", "VTSTDTDIFF", "", "", conn);
						return errString;
					}
				}
			}
			
			if("S".equalsIgnoreCase(empStatus))
			{
				errString = itmDBAccess.getErrorString("", "VTEMPSEPRT", "", "", conn);
				return errString;
			}
			
				/**
				 * 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));
					autoPost=getAutoPostValue(empCode,"AUTO_POST",conn);
					if("NULLFOUND".equalsIgnoreCase(autoPost))
					{
						errString = itmDBAccess.getErrorString("", "VSENVAR1", "", "", conn);
						return errString;
					}
					
					System.out.println("@V@ At cancelation AutoPost value :- ["+autoPost+"]");
					
					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"));					
	
					}
					pstmt.close();
					pstmt=null;
					rs.close();
					rs=null;
					
					System.out.println("@V@ Inserting Payer_voucher");
					//Modified by Santosh Gupta START
					String refId="";
					if(statusDateStr==null || statusDateStr.length()==0)
					{
						refId="RV-"+newVouchNo;
					}else
					{
						refId="RV-"+statusDateStr;
					}
					//Modified by Santosh Gupta END
					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, refId);
					pstmt.setTimestamp(7, chgDate);
					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*-1);
						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;

						
						if("Y".equalsIgnoreCase(autoPost))
						{
							payrollVoucherConf = (PayrollVoucherConfLocal)initialCtx.lookup("ibase/PayrollVoucherConf/local");
							retString = checkNull(payrollVoucherConf.confirm(newVouchNo, forcedFlag, xtraParams, conn));
						}
						//Changed By Santosh Gupta purposed  to retrive old data of employee (10/4/17)
						//if(retString.length() > 0 && retString.indexOf("VTMCONF2") == -1 )
						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)
				{
					if("Y".equalsIgnoreCase(confirmStatus))
					{
						
						if(empFname.equalsIgnoreCase(tempEmpFname) && empMname.equalsIgnoreCase(tempEmpMname)
								&& empLname.equalsIgnoreCase(tempEmpLname) && empShortName.equalsIgnoreCase(tempEmpShortName))
						{
							/**
							 * 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.setTimestamp(2, prvStatDtTimestamp);
							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);
							updateEmployeeCount = pstmt.executeUpdate();
							pstmt.close();
							pstmt=null;
							
							System.out.println("@V@ UpdateEmployee :- [" + updateEmployeeCount+"]");
						}
						else
						{
//							System.out.println("@V@ Name not matching NOT update Employee");
							sql = "UPDATE EMPLOYEE SET M_STATUS = ?, M_STATUS_DATE = ?, NAME_PREFIX = ?, CHG_USER = ?, CHG_DATE = ?, CHG_TERM = ? " +
									"WHERE EMP_CODE = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, oldStatus);
//							pstmt.setTimestamp(2, statusDateTimeStamp);
							pstmt.setTimestamp(2, prvStatDtTimestamp);
							pstmt.setString(3, namePrefix);
							pstmt.setString(4, chgUser);
							pstmt.setTimestamp(5, chgDate);
							pstmt.setString(6, chgTerm);
							pstmt.setString(7, empCode);
							updateEmployeeCount = pstmt.executeUpdate();
							pstmt.close();
							pstmt=null;
							
							System.out.println("@V@ Name not matcching UpdateEmployee :- [" + updateEmployeeCount+"]");
						}
					}
					else
					{
						System.out.println("@V@ Un confirm transaction NOT update Employee");
					}
					
						/**
						 * 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 getAutoPostValue(String empCode, String varName, Connection conn) throws ITMException 
    {
		// TODO Auto-generated method stub
    	String autoPost="",sql="";
    	PreparedStatement pstmt=null;
    	ResultSet rs=null;
    	
    	try {
			sql="select ddf_hr_site_env_value(?,SYSDATE,?)as var_value from dual";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, empCode);
			pstmt.setString(2, varName);
			rs=pstmt.executeQuery();
			if(rs.next())
			{
				autoPost=rs.getString("var_value");
			}
			pstmt.close();
			pstmt=null;
			rs.close();
			rs=null;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ITMException(e);
		}
    	finally
    	{
    		try {
				if(pstmt!=null)
				{
					pstmt.close();
					pstmt=null;
				}
				if(rs!=null)
				{
					rs.close();
					rs=null;
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new ITMException(e);
			}
    	}
		return autoPost;
	}
	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 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;
	}
}
