package ibase.webitm.ejb.sys;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

public class ManageSqlProceed extends ActionHandlerEJB {
	public String updateStatus(String tranID, String xtraParams, String forcedFlag)
			throws RemoteException, ITMException {
					E12GenericUtility genericUtility = new E12GenericUtility();
		Connection conn = null;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		String quotType = "", custCode = "";
		StringBuffer processDynXmlString = new StringBuffer();
		int domId = 0;
		int lineNo = 0;
		UserInfoBean userInfo = null;
		ResultSet fetchHospitalMappingRs = null;
		PreparedStatement insertPs = null;
		ValidatorEJB validatorEJB;
		String errString = "";

		try {
			userInfo = getUserInfo();
			validatorEJB = new ValidatorEJB();
			BaseLogger.log("3", getUserInfo(), null, "ManageSqlProceed --> tranID [" + tranID + "]");
			String action = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "actionTitle");


			conn = getConnection();
			String userId = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			String tranIdRef = "";
			int existingAprvLvl = 0;
			String wfStatus = "";
			String reviewed = "";
			String executionAprv = "";
			
			
			String getAprvLvlSql = "select APRV_LEVEL, TRAN_ID__REF, WF_STATUS, REVIEW_YN, EXEC_APRV from sql_changes where tran_id = ?";
			PreparedStatement getAprvLvlPs = conn.prepareStatement(getAprvLvlSql);
			getAprvLvlPs.setString(1, tranID);
			ResultSet getAprvLvlRs = getAprvLvlPs.executeQuery();
			while(getAprvLvlRs.next()) {
				existingAprvLvl = getAprvLvlRs.getInt("APRV_LEVEL");
				tranIdRef = checkNull(getAprvLvlRs.getString("TRAN_ID__REF"));
				wfStatus = checkNull(getAprvLvlRs.getString("WF_STATUS"));
				reviewed = checkNull(getAprvLvlRs.getString("REVIEW_YN"));
				executionAprv = checkNull(getAprvLvlRs.getString("EXEC_APRV"));
			}

            if (action.trim().equalsIgnoreCase("Reviewed")) {
				BaseLogger.log("3", null, null, "In Reviewed condition.........");

				if (!executionAprv.trim().equalsIgnoreCase("Y")) {
					BaseLogger.log("3", getUserInfo(), null, "Execution Approval is not Y");
					return itmDBAccessEJB.getErrorString("", "MSQLCNR", "", "", conn);
				}

				if (executionAprv.trim().equalsIgnoreCase("Y")) {
					if (!wfStatus.trim().equalsIgnoreCase("A")) {
						BaseLogger.log("3", getUserInfo(), null, "Workflow not approved");
						return itmDBAccessEJB.getErrorString("", "MSQLCNR", "", "", conn);
					}
				}

				if (executionAprv.trim().equalsIgnoreCase("Y") && wfStatus.trim().equalsIgnoreCase("A")) {
					if (!reviewed.trim().equalsIgnoreCase("Y")) {
						BaseLogger.log("3", getUserInfo(), null, "Not send for review");
						return itmDBAccessEJB.getErrorString("", "MSQLCNR", "", "", conn);
					}
				}

				String updateStatusForReviewed = "update sql_changes set txn_status = 'N' where tran_id = ?";
				PreparedStatement updateStatusForReviewedPs = conn.prepareStatement(updateStatusForReviewed);
				updateStatusForReviewedPs.setString(1, tranID);
				int updateStatusForReviewedCount = updateStatusForReviewedPs.executeUpdate();
				BaseLogger.log("3", getUserInfo(), null, "updateStatusForReviewedCount:: "+updateStatusForReviewedCount);
				if (updateStatusForReviewedCount>0) {
						BaseLogger.log("3", getUserInfo(), null, "Reviewed succesfully");
						return itmDBAccessEJB.getErrorString("", "MSQLRS", "", "", conn);
					}

			}
			
			if (action.trim().equalsIgnoreCase("Proceed")) {
				BaseLogger.log("3", null, null, "In Proceed condition.........");
			if(tranIdRef.trim().length()!=0){
				BaseLogger.log("3", getUserInfo(), null, "MSQLPAE Proceed already completed.");
				return itmDBAccessEJB.getErrorString("", "MSQLPAE", "", "", conn);

			}
			if(existingAprvLvl<1) {
				int updatedAprvLvl = existingAprvLvl+1;
			    BaseLogger.log("3", getUserInfo(), null, "ManageSqlProceed.updateStatus: updatedAprvLvl[" +updatedAprvLvl + "]");

				// 🔹 Update APRV_LEVEL
				String updateAprvLvlSql = "update sql_changes set APRV_LEVEL = ?, TXN_STATUS = 'T' where tran_id = ?";
				PreparedStatement updateAprvLvlPs = conn.prepareStatement(updateAprvLvlSql);
				updateAprvLvlPs.setInt(1, updatedAprvLvl);
				updateAprvLvlPs.setString(2, tranID);

				int updateAprvLvlCnt = updateAprvLvlPs.executeUpdate();


			
				if (updateAprvLvlCnt > 0 && updatedAprvLvl == 1) {
					conn.commit();
					return itmDBAccessEJB.getErrorString("", "MSQLPROC", "", "", conn);
				}


				if (updateAprvLvlPs != null) {
					updateAprvLvlPs.close();
					updateAprvLvlPs = null;
				}
			}
			else if(existingAprvLvl >= 1) {
				return itmDBAccessEJB.getErrorString("", "MSQLAPROC", "", "", conn);
			}

		}
		
		} catch (Exception e) {
		    if (conn != null) {
		        try {
		            conn.rollback();
		        } catch (Exception ex) {
		            ex.printStackTrace();
		        }
		    }
		    BaseLogger.log("3", getUserInfo(), null, "Exception in ManageSqlProceed.updateStatus: [" + e.getMessage() + "]");
		}
		finally {
		    try {
		        if (insertPs != null) insertPs.close();
				if (conn != null) conn.close();
		        if (fetchHospitalMappingRs != null) fetchHospitalMappingRs.close();
		    } catch (Exception e) {
		    }
		}

		return " ";
	}

	private String checkNull(String input) {
		if (input == null) {
			input = "";
		}
		return input;
	}
}
