/**
 * PURPOSE : Post Save to create loans against adhoc advance given to employee
 * AUTHOR : Abhishek Jaiswal
 * DATE : 20/02/2015
 */
package ibase.webitm.ejb.adm;

import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.adm.AdmCommon;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.fin.FinCommon;
import ibase.webitm.ejb.sys.CreateRCPXML;
import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;
import java.rmi.RemoteException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;

import org.w3c.dom.*;


@javax.ejb.Stateless
public class AdvanceAddPos extends ValidatorEJB implements AdvanceAddPosLocal, AdvanceAddPosRemote
{
	public String postSave()throws RemoteException,ITMException
	{
		return "";
	}
	public String postSave(String tranId, String editFlag, String xtraParams, Connection conn ) throws RemoteException,ITMException
	{

		String empCode = "";
		String loginEmpCode = "";
		String schemeCode = "";
		String loanAdCode = "";
		String prdCodeAdj = "";
		String prdCodeDed = "";
		String loanRemarks = "";
		String paySite = "";
		String errString = "";
		String keyString = "";
		String sql = "";
		String errCode = "";
		String intTerm = "";
		String acctCodeLoan = "";
		String cctrCodeLoan = "";
		String acctCodePay = "";
		String cctrCodePay = "";
		String adCodeDedn = "";
		String userId = "";
		String chgTerm = "";
		String loanNo = "";
		
		Timestamp tranDate = null ;
		Timestamp frDate = null ;
		Timestamp toDate = null ;
		Timestamp loanRecoDate = null ;
		Timestamp loanExpDate = null ;
		Timestamp  currDate = null;

		double loanAmount = 0d;

		int empAdCnt = 0;
		int empAdRowUpdCnt = 0;
		int empAdRowInsCnt = 0;
		int loanExistCnt = 0;
		int loansInsCnt = 0;
		int loansSchInsCnt = 0;
		int aldBalInsCnt = 0;

		boolean schemeCodeExist = false;

		PreparedStatement pstmt = null;		
		ResultSet rs = null;

		ITMDBAccessEJB itmDBAccess = new ITMDBAccessEJB();		
		AdmCommon admCommon = new AdmCommon();
		GenericUtility genericUtility = GenericUtility.getInstance();

		SimpleDateFormat sdfAppl = null;
		String tranDateStr = "";

		try
		{

			currDate = new java.sql.Timestamp(System.currentTimeMillis());
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "chgTerm" );
			loginEmpCode  = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");

			sql = "SELECT KEY_STRING FROM TRANSETUP WHERE UPPER(TRAN_WINDOW) = 'W_LOAN'";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				keyString = checkNullAndTrim(rs.getString("KEY_STRING"));
			}
			if (rs != null)
			{
				rs.close();
				rs = null;
			}
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (keyString.length() == 0)
			{
				errCode = "VTSEQ";
				errString = itmDBAccess.getErrorString("" , errCode , "" , "" , conn);
				return errString;
			}
			
			sql = "SELECT A.TRAN_DATE AS TRAN_DATE, A.EMP_CODE AS EMP_CODE , A.LOAN_AMOUNT AS LOAN_AMOUNT , A.PRD_CODE__ADJ AS PRD_CODE__ADJ, A.PRD_CODE__DED AS PRD_CODE__DED, A.REMARKS AS REMARKS , B.PAY_SITE AS PAY_SITE , C.FR_DATE AS FR_DATE , C.TO_DATE AS TO_DATE , D.FR_DATE AS LOAN_RECO_DATE , D.TO_DATE AS LOAN_EXP_DATE FROM EMPLOAN_ADD A , EMPLOYEE B , PERIOD C , PERIOD D WHERE B.EMP_CODE = A.EMP_CODE AND C.CODE = A.PRD_CODE__DED AND D.CODE = A.PRD_CODE__ADJ AND A.TRAN_ID = ?";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				tranDate = rs.getTimestamp("TRAN_DATE");
				empCode = rs.getString("EMP_CODE");
				loanAmount = rs.getDouble("LOAN_AMOUNT");
				prdCodeAdj = rs.getString("PRD_CODE__ADJ");
				prdCodeDed = rs.getString("PRD_CODE__DED");
				loanRemarks = rs.getString("REMARKS");
				paySite = rs.getString("PAY_SITE");
				frDate = rs.getTimestamp("FR_DATE");
				toDate = rs.getTimestamp("TO_DATE");
				loanRecoDate = rs.getTimestamp("LOAN_RECO_DATE");
				loanExpDate = rs.getTimestamp("LOAN_EXP_DATE");
			}
			if (rs != null)
			{
				rs.close();
				rs = null;
			}
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}

			sdfAppl = new SimpleDateFormat(genericUtility.getApplDateFormat());
			tranDateStr = sdfAppl.format(tranDate);

			schemeCode = checkNullAndTrim(admCommon.getEnv("999999" , "ADHOC_SCHEME" , conn));
			if (schemeCode.length() == 0 || schemeCode.equals("NULLFOUND"))
			{
				errCode = "VSENVAR1";
				errString = itmDBAccess.getErrorString("" , errCode , "" , "" , conn);
				return errString;
			}
			loanAdCode = checkNullAndTrim(admCommon.getEnv("999999" , "ADHOC_ADV" , conn));
			if (loanAdCode.length() == 0 || loanAdCode.equals("NULLFOUND"))
			{
				errCode = "VSENVAR1";
				errString = itmDBAccess.getErrorString("" , errCode , "" , "" , conn);
				return errString;
			}

			sql = "SELECT COUNT(*) AS LOAN_CNT FROM LOANS WHERE EMP_CODE = ? AND SCHEME_NO = ? AND STATUS = 'A'"; 

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1 , empCode);
			pstmt.setString(2 , schemeCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				loanExistCnt = rs.getInt("LOAN_CNT");
			}
			if (rs != null)
			{
				rs.close();
				rs = null;
			}
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (loanExistCnt > 0)
			{
				errCode = "VTLOANSAN2";
				errString = itmDBAccess.getErrorString("" , errCode , "" , "" , conn);
				return errString;
			}


			sql = "SELECT INT_TERM, ACCT_CODE__LOAN, CCTR_CODE__LOAN, ACCT_CODE__PAY,CCTR_CODE__PAY, AD_CODE__DED FROM LOAN_SCHEME WHERE SCHEME_NO  = ?";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1 , schemeCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				intTerm = checkNullAndTrim(rs.getString("INT_TERM"));
				acctCodeLoan = checkNullAndTrim(rs.getString("ACCT_CODE__LOAN"));
				cctrCodeLoan = checkNullAndTrim(rs.getString("CCTR_CODE__LOAN"));
				acctCodePay = checkNullAndTrim(rs.getString("ACCT_CODE__PAY"));
				cctrCodePay = checkNullAndTrim(rs.getString("CCTR_CODE__PAY"));
				adCodeDedn = checkNullAndTrim(rs.getString("AD_CODE__DED"));
				schemeCodeExist = true;
			}
			if (rs != null)
			{
				rs.close();
				rs = null;
			}
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (!schemeCodeExist)
			{
				errCode = "VTADVADD03";
				errString = itmDBAccess.getErrorString("" , errCode , "" , "" , conn);
				return errString;
			}


			sql = "SELECT COUNT(1) AS EMPAD_CNT FROM EMPLOYEE_AD WHERE EMP_CODE = ? AND AD_CODE = ? AND EFF_DATE = ? AND EXP_DATE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1 , empCode);
			pstmt.setString(2 , loanAdCode);
			pstmt.setTimestamp(3 , frDate);
			pstmt.setTimestamp(4 , toDate);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				empAdCnt = rs.getInt("EMPAD_CNT");
			}
			if (rs != null)
			{
				rs.close();
				rs = null;
			}
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (empAdCnt > 0)
			{
				sql = "UPDATE EMPLOYEE_AD SET AMOUNT = ? , REF_TYPE = 'O' , CHG_DATE = ? , CHG_USER = ? , CHG_TERM = ? WHERE EMP_CODE = ? AND AD_CODE = ? AND EFF_DATE = ? AND EXP_DATE = ?";
				pstmt = conn.prepareStatement(sql);

				pstmt.setDouble(1 , loanAmount);
				pstmt.setTimestamp(2 , currDate);
				pstmt.setString(3 , userId);
				pstmt.setString(4, chgTerm);
				pstmt.setString(5 , empCode);
				pstmt.setString(6 , loanAdCode);
				pstmt.setTimestamp(7 , frDate);
				pstmt.setTimestamp(8 , toDate);

				empAdRowUpdCnt = pstmt.executeUpdate();
				System.out.println("AdvanceAddPos - EMPLOYEE_AD UPDATE COUNT [" + empAdRowUpdCnt + "]");
			}
			else
			{
				sql = "INSERT INTO EMPLOYEE_AD (EMP_CODE , AD_CODE , EFF_DATE , EXP_DATE , TYPE, AMOUNT , CHG_DATE , CHG_USER , CHG_TERM , REF_TYPE , PROP_YN , CONFIRMED) VALUES (? , ? , ? , ? , 'F' , ? , ? , ? , ? , 'O', 'N', 'Y')";
				pstmt = conn.prepareStatement(sql);

				pstmt.setString(1 , empCode);
				pstmt.setString(2 , loanAdCode);
				pstmt.setTimestamp(3 , frDate);
				pstmt.setTimestamp(4 , toDate);
				pstmt.setDouble(5 , loanAmount);
				pstmt.setTimestamp(6 , currDate);
				pstmt.setString(7 , userId);
				pstmt.setString(8, chgTerm);

				empAdRowInsCnt = pstmt.executeUpdate();
				System.out.println("AdvanceAddPos - EMPLOYEE_AD INSERT COUNT [" + empAdRowInsCnt + "]");
			}
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (empAdCnt > 0 && empAdRowUpdCnt == 0)
			{
				errCode = "VTADVADD01";
				errString = itmDBAccess.getErrorString("" , errCode , "" , "" , conn);
				return errString;
			}
			if (empAdCnt == 0 && empAdRowInsCnt == 0)
			{
				errCode = "VTADVADD02";
				errString = itmDBAccess.getErrorString("" , errCode , "" , "" , conn);
				return errString;
			}
			loanNo = checkNullAndTrim(generateTranId( "W_LOAN", paySite, tranDateStr, conn ));
			System.out.println("AdvanceAddPos - loanNo for Advance [" + loanNo + "]");

			if(loanNo.length() == 0)
			{
				errString = itmDBAccess.getErrorString("","VTTRANID","","",conn);
				return errString;
			}

			sql = "INSERT INTO LOANS (LOAN_NO , SANCTION_NO , SCHEME_NO , EMP_CODE , ISSUE_DATE, START_RECO , START_DEDN , LOAN_AMT , TERM , INTEREST , MON_INST , INT_TERM , INTEREST_AMT , RECOVER_AMT , EMP_CODE__APPR , APPR_DATE , BANK_CODE , ACCT_CODE__LOAN ,	CCTR_CODE__LOAN , ACCT_CODE__PAY , CCTR_CODE__PAY , ADJUSTABLE , ADJ_PERC , ALL_MONTHS , BALANCE_AMT , DATE__BALANCE , STATUS , CHG_DATE , CHG_USER , CHG_TERM , REMARKS , ACCRUAL_AMT , DATE__INTEREST) VALUES (? , NULL , ? , ? , ? , ? , 'Y', ? , 1, 0, ? , ? , 0, ? , ? , ? , '', ? , ? , ? , ? , 'N', 0, 'Y', ? , ? , 'A', ? , ?, ? , ? , 0, ?)";
			pstmt = conn.prepareStatement(sql);

			pstmt.setString(1 , loanNo);
			pstmt.setString(2 , schemeCode);
			pstmt.setString(3 , empCode);
			pstmt.setTimestamp(4 , tranDate);
			pstmt.setTimestamp(5 , loanRecoDate);
			pstmt.setDouble(6 , loanAmount);
			pstmt.setDouble(7 , loanAmount);
			pstmt.setString(8 , intTerm);
			pstmt.setDouble(9 , loanAmount);
			pstmt.setString(10 , loginEmpCode);
			pstmt.setTimestamp(11 , currDate);
			pstmt.setString(12 , acctCodeLoan);
			pstmt.setString(13 , cctrCodeLoan);
			pstmt.setString(14 , acctCodePay);
			pstmt.setString(15 , cctrCodePay);
			pstmt.setDouble(16 , loanAmount);
			pstmt.setTimestamp(17 , loanRecoDate);
			pstmt.setTimestamp(18 , currDate);
			pstmt.setString(19 , userId);
			pstmt.setString(20, chgTerm);
			pstmt.setString(21, loanRemarks);
			pstmt.setTimestamp(22 , loanRecoDate);

			loansInsCnt = pstmt.executeUpdate();
			System.out.println("AdvanceAddPos - LOANS INSERT COUNT [" + loansInsCnt + "]");
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (loansInsCnt == 0)
			{
				errCode = "VTADVADD04";
				errString = itmDBAccess.getErrorString("" , errCode , "" , "" , conn);
				return errString;
			}

			sql = "INSERT INTO LOANS_SCHEDULE ( LOAN_NO, LINE_NO, NO_INST, AMOUNT, NO_INST_DED, CHG_DATE, CHG_USER, CHG_TERM ) VALUES ( ?, 1, null, ?, 0 , ?, ?, ?)"  ;

			pstmt = conn.prepareStatement(sql);

			pstmt.setString(1 , loanNo);
			pstmt.setDouble(2 , loanAmount);
			pstmt.setTimestamp(3 , currDate);
			pstmt.setString(4 , userId);
			pstmt.setString(5, chgTerm);

			loansSchInsCnt = pstmt.executeUpdate();
			System.out.println("AdvanceAddPos - LOANS_SCHEDULE INSERT COUNT [" + loansSchInsCnt + "]");
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (loansSchInsCnt == 0)
			{
				errCode = "VTADVADD05";
				errString = itmDBAccess.getErrorString("" , errCode , "" , "" , conn);
				return errString;
			}

			sql = "INSERT INTO ALLOWDEDN_BAL (EMP_CODE, AD_CODE, START_DATE, END_DATE, AMOUNT, AMT_ADJ, AMT_BAL, CHG_DATE, CHG_USER, CHG_TERM,REF_TYPE,REF_NO) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?,'L',?)";

			pstmt = conn.prepareStatement(sql);

			pstmt.setString(1 , empCode);
			pstmt.setString(2 , adCodeDedn);
			pstmt.setTimestamp(3 , loanRecoDate);
			pstmt.setTimestamp(4 , loanExpDate);
			pstmt.setDouble(5 , loanAmount);
			pstmt.setDouble(6 , loanAmount);
			pstmt.setTimestamp(7 , currDate);
			pstmt.setString(8 , userId);
			pstmt.setString(9, chgTerm);
			pstmt.setString(10 , loanNo);

			aldBalInsCnt = pstmt.executeUpdate();
			System.out.println("AdvanceAddPos - ALLOWDEDN_BAL INSERT COUNT [" + aldBalInsCnt + "]");
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (aldBalInsCnt == 0)
			{
				errCode = "VTADVADD06";
				errString = itmDBAccess.getErrorString("" , errCode , "" , "" , conn);
				return errString;
			}

		}
		catch(Exception e)
		{
			try
			{

				System.out.println("Exception IN AdvanceAddPos::::"+e.getMessage());
				e.printStackTrace();			
				throw new ITMException(e);
			}
			catch (Exception e1)
			{
				e1.printStackTrace();
				throw new ITMException(e1);
			}
		}
		finally
		{
			try
			{	
				if(errString != null && errString.trim().length() > 0)
				{
					{
						conn.rollback();
					}
				}

				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception "+e.getMessage());
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return errString;
	}

	private String checkNull( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		return inputVal;
	}
	private String checkNullAndTrim( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		return inputVal.trim();
	}

	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 = "";
		String paySiteCode = "";
		String effectiveDate = "";
		java.sql.Date effDate = null;

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

			selSql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE UPPER(TRAN_WINDOW) = UPPER(?) ";
			//System.out.println("selSql :"+selSql);
			pstmt = conn.prepareStatement(selSql);
			pstmt.setString( 1, windowName );
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				keyString = checkNullAndTrim(rs.getString("KEY_STRING"));
				keyCol = checkNullAndTrim(rs.getString("TRAN_ID_COL"));
				tranSer = checkNullAndTrim(rs.getString("REF_SER"));
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;
			if (tranSer.length() == 0)
			{
				tranSer = "E-LOAN";
			}
			if (keyCol.length() == 0)
			{
				keyCol = "LOAN_NO";
			}
			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 +		"<emp_site>" + siteCode + "</emp_site>";
			xmlValues = xmlValues +		"<work_site>" + siteCode + "</work_site>";
			xmlValues = xmlValues +		"<pay_site>" + siteCode + "</pay_site>";
			xmlValues = xmlValues +		"<tran_date>" + tranDateStr + "</tran_date>"; 
			xmlValues = xmlValues +		"<issue_date>" + tranDateStr + "</issue_date>"; 
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer, keyCol, keyString, conn);
			System.out.println("AdvanceAddPos - trnidgenerater - LOAN_NO [" + tranId + "]");

		}
		catch (SQLException ex)
		{
			System.out.println("Exception :AdvanceAddPos :generateTranId :SQLException ::" +selSql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			System.out.println("Exception :AdvanceAddPos :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)
			{
				//errString = e.getMessage();
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return tranId;
	}
}

