package ibase.webitm.ejb.sys;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import javax.naming.InitialContext;

import org.w3c.dom.Document;

import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
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.MasterStatefulEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.utility.ITMException;

public class ManageSqlReleaseFromQC extends ActionHandlerEJB {

	E12GenericUtility genericUtility = new E12GenericUtility();

	public String updateStatus() throws RemoteException, ITMException {
		return "";
	}

	public String updateStatus(String tranID, String xtraParams, String forcedFlag)
			throws RemoteException, ITMException {
		BaseLogger.log("3", null, null, " ManageSqlReleaseFromQC tranID::" + tranID + "]");
		BaseLogger.log("3", null, null, "ManageSqlReleaseFromQC xtraParams::" + xtraParams + "]");
		BaseLogger.log("3", null, null, "ManageSqlReleaseFromQC forcedFlag::" + forcedFlag + "]");

		String action = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "actionTitle");
		BaseLogger.log("3", null, null, "ManageSqlReleaseFromQC action::" + action + "]");

		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

		String retVal = "";
		String refSer = "";
		String signStatus = "";
		String enterprises1 = "";
		boolean isLocalConn = false;
		PreparedStatement mSqlPstmt = null;
		ResultSet mSqlRs = null;
		PreparedStatement mSqlDetPstmt = null;
		ResultSet mSqlDetRs = null;
		String empCode = "";
		String entityCode = "", reportTo = "", allocatedTo;
		LocalDate tranDate = LocalDate.now();// for tranDate
		LocalTime tranTime = LocalTime.now();
		String tranDateStr = formatDateTime(tranDate, tranTime);
		String tranId = "";
		String reqId = "";
		String custCode = "";
		String empCodeGiven = "";
		String empCodeMerge = "";
		String executed = "";
		String tranIdOrg = "";
		String activeYn = "";
		String itmVer = "";
		String chgUser = "";
		String chgTerm = "";
		String confirmed = "";
		String empCodeAprv = "";
		String enterprises = "";
		String applDb = "";
		String execRights = "";
		String tranIdRef = "";
		String signRemarks = "";
		String db2Statement = "";
		String lineNo = "";
		String oracleStatement = "";
		String statementType = "";
		// InitialContext ctx = null;
		String retString = null;
		String executionRights = "";
		String remarks = "";

		Connection conn = null;
		// MasterStatefulLocal masterStateful = null; // for ejb3

		try {
			UserInfoBean userInfo = getUserInfo();
			BaseLogger.log("3", null, null, "userInfo 91::" + userInfo.toString() + "]");
			String profileIds = userInfo.getProfileId();
			BaseLogger.log("3", null, null, "userInfo 91::profileIds:: " + profileIds + "]");

			String[] profileIdArr = profileIds.split(",");

			boolean QcProfileIdFlag = false;

			for (String id : profileIdArr) {
				if (id != null && id.trim().equals("MSQC")) {
					QcProfileIdFlag = true;
					break;
				}
			}
			BaseLogger.log("3", null, null, "QcProfileIdFlag::: " + QcProfileIdFlag);

			if (!QcProfileIdFlag) {
				BaseLogger.log("3", null, null, "Not contain");
				return itmDBAccessEJB.getErrorString("", "INVPROF", "", "", conn);

			}

			// CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
			// AppConnectParm appConnect = new AppConnectParm();
			// ctx = new InitialContext(appConnect.getProperty());
			// masterStateful =
			// (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");

			AppConnectParm appConnect = new AppConnectParm();
			InitialContext initialContext = new InitialContext(appConnect.getProperty());

			if (conn == null) {
				ConnDriver connDriver = new ConnDriver();
				conn = connDriver.getConnectDB(userInfo.getTransDB());
			}

			String qcConfirmed = "";
			String tranIdReference = "";
			String getAprvLvlSql = "select confirmed from sql_changes where tran_id = ? and exec_rights = 'Q'";
			PreparedStatement getAprvLvlPs = conn.prepareStatement(getAprvLvlSql);
			getAprvLvlPs.setString(1, tranID);
			ResultSet getAprvLvlRs = getAprvLvlPs.executeQuery();
			while (getAprvLvlRs.next()) {
				qcConfirmed = checkNull(getAprvLvlRs.getString("confirmed"));

			}
			String getTranIdRef = "select tran_id__ref, exec_rights from sql_changes where tran_id = ?";
			PreparedStatement getTranIdRefPs = conn.prepareStatement(getTranIdRef);
			getTranIdRefPs.setString(1, tranID);
			ResultSet getTranIdRefPsRs = getTranIdRefPs.executeQuery();
			while (getTranIdRefPsRs.next()) {
				tranIdReference = checkNull(getTranIdRefPsRs.getString("tran_id__ref"));
				execRights = checkNull(getTranIdRefPsRs.getString("exec_rights"));

			}
			BaseLogger.log("3", null, null, "tranID::: " + tranID);

			String tranIdRedForAll = "";
			int countOfAllTran = 0;
			String checkTranIdRefSqlForAll = "select exec_rights from sql_changes where tran_id = ?";
				PreparedStatement checkTranIdRefForAllPs = conn.prepareStatement(checkTranIdRefSqlForAll);
				checkTranIdRefForAllPs.setString(1, tranID);
				ResultSet checkTranIdRefForAllRs = checkTranIdRefForAllPs.executeQuery();
				while (checkTranIdRefForAllRs.next()) {
					executionRights = checkNull(checkTranIdRefForAllRs.getString("exec_rights"));

				}
				BaseLogger.log("3", null, null, " :: executionRights:: " + executionRights);
				if (checkTranIdRefForAllPs != null) {
					checkTranIdRefForAllPs.close();
				}
				if (checkTranIdRefForAllRs != null) {
					checkTranIdRefForAllRs.close();
				}

				if (!executionRights.trim().equalsIgnoreCase("Q")) {
					return itmDBAccessEJB.getErrorString("", "MSQLARRS", "", "", conn);

				}

			tranID = tranIdReference;

				if (!qcConfirmed.trim().equalsIgnoreCase("Y")) {
				return itmDBAccessEJB.getErrorString("", "QCNOTC", "", "", conn);

				
			}

			String msqlDetSql = "SELECT TRAN_ID, TRAN_DATE, REQ_ID, REQ_DATE, CUST_CODE, EMP_CODE__GIVEN, EMP_CODE__MERGE, "
					+ "EXECUTED, TRAN_ID__ORG, ACTIVE_YN, ITM_VER, CHG_USER, CHG_TERM, CHG_DATE, CONFIRMED, CONF_DATE, "
					+ "EMP_CODE_APRV, ENTERPRISES, APPL_DB, EXEC_RIGHTS, TRAN_ID__REF, REMARKS "
					+ "FROM sql_changes where tran_id = ?";

			mSqlPstmt = conn.prepareStatement(msqlDetSql);
			mSqlPstmt.setString(1, tranID);
			mSqlRs = mSqlPstmt.executeQuery();

			while (mSqlRs.next()) {
				// Directly fetching and using values from result set without declaring
				// variables
				tranId = checkNull(mSqlRs.getString("TRAN_ID"));
				reqId = checkNull(mSqlRs.getString("REQ_ID"));
				custCode = checkNull(mSqlRs.getString("CUST_CODE"));
				empCodeGiven = checkNull(mSqlRs.getString("EMP_CODE__GIVEN"));
				empCodeMerge = checkNull(mSqlRs.getString("EMP_CODE__MERGE"));
				executed = checkNull(mSqlRs.getString("EXECUTED"));
				tranIdOrg = checkNull(mSqlRs.getString("TRAN_ID__ORG"));
				activeYn = checkNull(mSqlRs.getString("ACTIVE_YN"));
				itmVer = checkNull(mSqlRs.getString("ITM_VER"));
				chgUser = checkNull(mSqlRs.getString("CHG_USER"));
				chgTerm = checkNull(mSqlRs.getString("CHG_TERM"));
				confirmed = checkNull(mSqlRs.getString("CONFIRMED"));
				empCodeAprv = checkNull(mSqlRs.getString("EMP_CODE_APRV"));
				enterprises = checkNull(mSqlRs.getString("ENTERPRISES"));
				applDb = checkNull(mSqlRs.getString("APPL_DB"));
				execRights = checkNull(mSqlRs.getString("EXEC_RIGHTS"));
				tranIdRef = checkNull(mSqlRs.getString("TRAN_ID__REF"));
				remarks = checkNull(mSqlRs.getString("REMARKS"));

				// Do something with these values directly (e.g., use them in logic, or store in
				// a collection)

				System.out.println("TRAN_ID: " + tranId + ", " +
						"TRAN_DATE: " + tranDate + ", " +
						"REQ_ID: " + reqId + ", " +
						"CUST_CODE: " + custCode + ", " +
						"EMP_CODE__GIVEN: " + empCodeGiven + ", " +
						"EMP_CODE__MERGE: " + empCodeMerge + ", " +
						"EXECUTED: " + executed + ", " +
						"TRAN_ID__ORG: " + tranIdOrg + ", " +
						"ACTIVE_YN: " + activeYn + ", " +
						"ITM_VER: " + itmVer + ", " +
						"CHG_USER: " + chgUser + ", " +
						"CHG_TERM: " + chgTerm + ", " +
						"CONFIRMED: " + confirmed + ", " +
						"EMP_CODE_APRV: " + empCodeAprv + ", " +
						"ENTERPRISES: " + enterprises + ", " +
						"APPL_DB: " + applDb + ", " +
						"EXEC_RIGHTS: " + execRights + ", " +
						"REMAKRS: " + remarks + ", " +
						"TRAN_ID__REF: " + tranIdRef);
			}

			StringBuffer processDynXmlString = new StringBuffer();

			// Start building the XML string
			processDynXmlString.append("<DocumentRoot><description>Datawindow Root</description><group0>");
			processDynXmlString.append(
					"<description>Group0 description</description><Header0><description>Header0 members</description>");
			processDynXmlString.append("<objName><![CDATA[sql_changes]]></objName>");
			processDynXmlString.append("<pageContext><![CDATA[1]]></pageContext>");
			processDynXmlString.append("<objContext><![CDATA[1]]></objContext>");
			processDynXmlString.append("<editFlag><![CDATA[A]]></editFlag>");
			processDynXmlString.append("<focusedColumn><![CDATA[]]></focusedColumn>");
			processDynXmlString.append("<action><![CDATA[SAVE]]></action>");
			processDynXmlString.append("<elementName><![CDATA[]]></elementName>");
			processDynXmlString.append("<keyValue><![CDATA[1]]></keyValue>");
			processDynXmlString.append("<saveLevel><![CDATA[1]]></saveLevel>");
			processDynXmlString.append("<forcedSave><![CDATA[false]]></forcedSave>");
			processDynXmlString.append("<Detail1 dbID='' domID='1'  objContext='1'  objName='sql_changes'>");
			processDynXmlString
					.append("<attribute IS_CHANGE='Y' pkNames='TRAN_ID' selected='N' status='N' updateFlag='A'/>");

			// processDynXmlString.append("<tran_id/>");
			processDynXmlString.append("<tran_date><![CDATA[" + dateFormatter(tranDateStr) + "]]></tran_date>");
			processDynXmlString.append("<req_id><![CDATA[" + reqId + "]]></req_id>");
			processDynXmlString.append("<req_date><![CDATA[" + dateFormatter(tranDateStr) + "]]></req_date>");
			processDynXmlString.append("<emp_code__given><![CDATA[" + empCodeGiven + "]]></emp_code__given>");
			processDynXmlString.append("<emp_code__merge><![CDATA[" + empCodeMerge + "]]></emp_code__merge>");
			processDynXmlString.append("<executed><![CDATA[N]]></executed>");
			processDynXmlString.append("<tran_id__org><![CDATA[" + tranIdOrg + "]]></tran_id__org>");
			processDynXmlString.append("<active_yn><![CDATA[" + activeYn + "]]></active_yn>");
			processDynXmlString.append("<chg_user><![CDATA[" + chgUser + "]]></chg_user>");
			processDynXmlString.append("<chg_term><![CDATA[" + chgTerm + "]]></chg_term>");
			processDynXmlString.append("<confirmed><![CDATA[N]]></confirmed>");
			processDynXmlString.append("<conf_date><![CDATA[]]></conf_date>");
			processDynXmlString.append("<itm_ver><![CDATA[]]></itm_ver>");
			processDynXmlString.append("<enterprises><![CDATA[{{enterprises}}]]></enterprises>");
			processDynXmlString.append("<emp_code_aprv><![CDATA[]]></emp_code_aprv>");
			processDynXmlString.append("<chg_date><![CDATA[" + dateFormatter(tranDateStr) + "]]></chg_date>");
			processDynXmlString.append("<appl_db><![CDATA[" + applDb + "]]></appl_db>");
			processDynXmlString.append("<exec_rights><![CDATA[{{executionRights}}]]></exec_rights>");
			processDynXmlString.append("<tran_id__ref><![CDATA[" + tranId + "]]></tran_id__ref>");
			processDynXmlString.append("<remarks><![CDATA[" + remarks + "]]></remarks>");
			processDynXmlString.append("</Detail1>");

			String msqlDet1Sql = "SELECT LINE_NO, ORA_STMNT, DB2_STMNT, STMNT_TYPE FROM sql_changes_det WHERE tran_id = ?";
			mSqlDetPstmt = conn.prepareStatement(msqlDet1Sql);
			mSqlDetPstmt.setString(1, tranID);
			mSqlDetRs = mSqlDetPstmt.executeQuery();

			while (mSqlDetRs.next()) {
				lineNo = checkNull(mSqlDetRs.getString("LINE_NO"));
				oracleStatement = checkNull(mSqlDetRs.getString("ORA_STMNT"));
				db2Statement = checkNull(mSqlDetRs.getString("DB2_STMNT"));
				statementType = checkNull(mSqlDetRs.getString("STMNT_TYPE"));

				processDynXmlString.append("<Detail2 dbID=':' domID='2' objName=\"sql_changes\" objContext=\"2\">");
				processDynXmlString.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
				processDynXmlString.append("<line_no><![CDATA[").append(lineNo).append("]]></line_no>");
				processDynXmlString.append("<ora_stmnt><![CDATA[").append(oracleStatement).append("]]></ora_stmnt>");
				processDynXmlString.append("<db2_stmnt><![CDATA[").append(db2Statement).append("]]></db2_stmnt>");
				processDynXmlString.append("<stmnt_type><![CDATA[").append(statementType).append("]]></stmnt_type>");
				processDynXmlString.append("</Detail2>");
			}

			if (mSqlDetRs != null) {
				mSqlDetRs.close();
				mSqlDetRs = null;
			}
			if (mSqlDetPstmt != null) {
				mSqlDetPstmt.close();
				mSqlDetPstmt = null;
			}

			processDynXmlString.append("</Header0></group0></DocumentRoot>");

			// Now, processDynXmlString contains the dynamically generated XML with the
			// values from your query
			System.out.println(processDynXmlString.toString());
			//

			// Added for PILOT transaction -- START
			// Fetch DB_PILOT from ENTERPRISE table to use as the enterprise for the PILOT
			// transaction
			if (action.trim().equalsIgnoreCase("Release to Pilot")) {
				BaseLogger.log("3", null, null, "In DB_PILOT condition.........");
				int countOfPilotTran = 0;
				String tranIdRedForPilot = "";
				String checkEntryForPilotSql = "select count(tran_id) as DevTranCount  from sql_changes where tran_id__ref = ? and exec_rights = 'P'";
				PreparedStatement checkEntryForPilotPs = conn.prepareStatement(checkEntryForPilotSql);
				checkEntryForPilotPs.setString(1, tranID);
				ResultSet checkEntryForPilotRs = checkEntryForPilotPs.executeQuery();
				while (checkEntryForPilotRs.next()) {
					countOfPilotTran = checkEntryForPilotRs.getInt("DevTranCount");

				}
				BaseLogger.log("3", null, null, "In DB_PILOT condition :: countOfDevTran:: " + countOfPilotTran);
				if (checkEntryForPilotRs != null) {
					checkEntryForPilotRs.close();
				}
				if (checkEntryForPilotPs != null) {
					checkEntryForPilotPs.close();
				}

				String checkTranIdRefSql = "select tran_id__ref  from sql_changes where tran_id = ? and exec_rights = 'P'";
				PreparedStatement checkTranIdRefPs = conn.prepareStatement(checkTranIdRefSql);
				checkTranIdRefPs.setString(1, tranID);
				ResultSet checkTranIdRefRs = checkTranIdRefPs.executeQuery();
				while (checkTranIdRefRs.next()) {
					tranIdRedForPilot = checkNull(checkTranIdRefRs.getString("tran_id__ref"));

				}
				BaseLogger.log("3", null, null, "In DB_PILOT condition :: tranIdRedForPilot:: " + tranIdRedForPilot);
				if (checkTranIdRefPs != null) {
					checkTranIdRefPs.close();
				}
				if (checkTranIdRefRs != null) {
					checkTranIdRefRs.close();
				}

				if (countOfPilotTran > 0) {
					return itmDBAccessEJB.getErrorString("", "MSQLAPP", "", "", conn);

				}
				// if(tranIdRedForPilot.trim().length()==0) {
				// BaseLogger.log("3", null, null, "In DB_PILOT condition :: tran_id__ref is
				// blank:: ");
				// return itmDBAccessEJB.getErrorString("", "MSQLAPP", "", "", conn);

				// }
				String dbPilotEnterprise = "";
				Connection pilotEntConn = null;
				PreparedStatement pilotPstmt = null;
				ResultSet pilotRs = null;
				StringBuilder dbPilotBuilder = new StringBuilder();

				try {
					ConnDriver pilotConnDriver = new ConnDriver();
					pilotEntConn = pilotConnDriver.getConnectDB("Driver");

					String[] entArray = enterprises.split(",");

					String pilotSql = "SELECT DB_PILOT FROM ENTERPRISE WHERE ENTERPRISE = ?";
					pilotPstmt = pilotEntConn.prepareStatement(pilotSql);

					for (String ent : entArray) {
						ent = ent.trim();

						pilotPstmt.setString(1, ent);
						pilotRs = pilotPstmt.executeQuery();

						if (pilotRs.next()) {
							String dbPilot = checkNull(pilotRs.getString("DB_PILOT"));

							if (dbPilot != null && !dbPilot.isEmpty()) {
								if (dbPilotBuilder.length() > 0) {
									dbPilotBuilder.append(",");
								}
								dbPilotBuilder.append(dbPilot);
							}
						}

						if (pilotRs != null)
							pilotRs.close(); // important inside loop
					}

					dbPilotEnterprise = dbPilotBuilder.toString();

				} catch (Exception e) {
					e.printStackTrace();
				} finally {

					if (pilotRs != null) {
						pilotRs.close();
					}
					if (pilotPstmt != null) {
						pilotPstmt.close();
					}
					if (pilotEntConn != null) {
						pilotEntConn.close();
					}
				}

				BaseLogger.log("3", null, null, "DB_PILOT enterprise fetched: [" + dbPilotEnterprise + "]");

				if (!dbPilotEnterprise.isEmpty()) {
					// Create PILOT XML with exec_rights = "P" and enterprise from DB_PILOT column
					String xmlWithP = processDynXmlString.toString().replace("{{executionRights}}", "P");
					xmlWithP = xmlWithP.replace("{{enterprises}}", dbPilotEnterprise);
					BaseLogger.log("3", null, null, "xmlWithP XML:::" + xmlWithP + "]");

					MasterStatefulLocal masterStateful = null;
					appConnect = null;
					initialContext = null;

					appConnect = new AppConnectParm();
					initialContext = new InitialContext(appConnect.getProperty());
					masterStateful = (MasterStatefulLocal) initialContext
							.lookup("ibase/MasterStatefulEJB/local");

					String processRequestResultPilot = masterStateful.processRequest(userInfo, xmlWithP, false, conn);
					BaseLogger.log("3", null, null,
							"processRequest processRequestResultPilot" + processRequestResultPilot + "]");
					Document dom = genericUtility.parseString(processRequestResultPilot);
					String tranSuccessFlag = checkNull(genericUtility.getColumnValue("Detail", dom));
					if (tranSuccessFlag.trim().equalsIgnoreCase("Success")) {
						BaseLogger.log("3", null, null, "Transaction created on pilot succesfully");

						Connection conn1 = getConnection();
						String updateTxnStatusSql = "update sql_changes set TXN_STATUS = 'P' where tran_id = ?";
						PreparedStatement updateTxnStatusPs = conn1.prepareStatement(updateTxnStatusSql);
						updateTxnStatusPs.setString(1, tranID);
						int updateAprvLvlCnt = updateTxnStatusPs.executeUpdate();
						conn1.commit();

						BaseLogger.log("3", null, null, "updateAprvLvlCnt::" + updateAprvLvlCnt + "]");
						if (updateTxnStatusPs != null) {
							updateTxnStatusPs.close();
							updateTxnStatusPs = null;
						}
						if (conn1 != null) {
							conn1.close();
							conn1 = null;
						}

						return itmDBAccessEJB.getErrorString("", "MSQLRP", "", "", conn);
					}

					else {
						BaseLogger.log("3", null, null, "Transaction creation failed on pilot");
						return itmDBAccessEJB.getErrorString("", "MSQLFP", "", "", conn);

					}
				}
			}
			// Added for PILOT transaction -- END

			// Added for Client Dev transaction -- START
			// Fetch DB_DEV from ENTERPRISE table to use as the enterprise for the Client
			// Dev transaction
			if (action.trim().equalsIgnoreCase("Release Clients Dev")) {
				BaseLogger.log("3", null, null, "In DB_DEV condition.........");
				int countOfDevTran = 0;
				String tranIdRedForClientDev = "";
				String checkEntryForDevSql = "select count(tran_id) as DevTranCount from sql_changes where tran_id__ref = ? and exec_rights = 'C'";
				PreparedStatement checkEntryForDevPs = conn.prepareStatement(checkEntryForDevSql);
				checkEntryForDevPs.setString(1, tranID);
				ResultSet checkEntryForDevRs = checkEntryForDevPs.executeQuery();
				while (checkEntryForDevRs.next()) {
					countOfDevTran = checkEntryForDevRs.getInt("DevTranCount");
				}
				BaseLogger.log("3", null, null, "In DB_DEV condition :: countOfDevTran:: " + countOfDevTran);
				if (checkEntryForDevPs != null) {
					checkEntryForDevPs.close();
				}
				if (checkEntryForDevRs != null) {
					checkEntryForDevRs.close();
				}

				String checkTranIdRefSql = "select tran_id__ref  from sql_changes where tran_id__ref = ? and exec_rights = 'C'";
				PreparedStatement checkTranIdRefPs = conn.prepareStatement(checkTranIdRefSql);
				checkTranIdRefPs.setString(1, tranID);
				ResultSet checkTranIdRefRs = checkTranIdRefPs.executeQuery();
				while (checkTranIdRefRs.next()) {
					tranIdRedForClientDev = checkNull(checkTranIdRefRs.getString("tran_id__ref"));

				}
				BaseLogger.log("3", null, null, "In DB_DEV condition :: tranIdRedForPilot:: " + tranIdRedForClientDev);
				if (checkTranIdRefPs != null) {
					checkTranIdRefPs.close();
				}
				if (checkTranIdRefRs != null) {
					checkTranIdRefRs.close();
				}

				if (countOfDevTran > 0) {
					return itmDBAccessEJB.getErrorString("", "MSQLAPCD", "", "", conn);

				}
				// if(tranIdRedForClientDev.trim().length()==0) {
				// BaseLogger.log("3", null, null, "In DB_DEV condition :: tran_id__ref is
				// blank:: ");
				// return itmDBAccessEJB.getErrorString("", "MSQLAPCD", "", "", conn);

				// }
				String dbClientDevEnterprise = "";
				Connection clientDevEntConn = null;
				PreparedStatement clientDevPstmt = null;
				ResultSet clientDevRs = null;
				StringBuilder dbClientDevBuilder = new StringBuilder();

				try {
					ConnDriver clientDevConnDriver = new ConnDriver();
					clientDevEntConn = clientDevConnDriver.getConnectDB("Driver");

					String[] entArray = enterprises.split(",");

					String clientDevSql = "SELECT DB_DEV FROM ENTERPRISE WHERE ENTERPRISE = ?";
					clientDevPstmt = clientDevEntConn.prepareStatement(clientDevSql);

					for (String ent : entArray) {
						ent = ent.trim();

						clientDevPstmt.setString(1, ent);
						clientDevRs = clientDevPstmt.executeQuery();

						if (clientDevRs.next()) {
							String dbDev = checkNull(clientDevRs.getString("DB_DEV"));

							if (dbDev != null && !dbDev.isEmpty()) {
								if (dbClientDevBuilder.length() > 0) {
									dbClientDevBuilder.append(",");
								}
								dbClientDevBuilder.append(dbDev);
							}
						}

						if (clientDevRs != null)
							clientDevRs.close(); // close inside loop
					}

					dbClientDevEnterprise = dbClientDevBuilder.toString();

				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (clientDevRs != null) {
						clientDevRs.close();
					}
					if (clientDevPstmt != null) {
						clientDevPstmt.close();
					}
					if (clientDevEntConn != null) {
						clientDevEntConn.close();
					}
				}

				BaseLogger.log("3", null, null, "DB_PILOT enterprise fetched: [" + dbClientDevEnterprise + "]");

				if (!dbClientDevEnterprise.isEmpty()) {
					// Create Client Dev XML with exec_rights = "C" and enterprise from DB_DEV
					// column
					String xmlWithC = processDynXmlString.toString().replace("{{executionRights}}", "C");
					xmlWithC = xmlWithC.replace("{{enterprises}}", dbClientDevEnterprise);
					BaseLogger.log("3", null, null, "xmlWithP XML:::" + xmlWithC + "]");

					MasterStatefulLocal masterStateful = null;
					appConnect = null;
					initialContext = null;

					appConnect = new AppConnectParm();
					initialContext = new InitialContext(appConnect.getProperty());
					masterStateful = (MasterStatefulLocal) initialContext
							.lookup("ibase/MasterStatefulEJB/local");

					String processRequestResultClientDev = masterStateful.processRequest(userInfo, xmlWithC, false,
							conn);
					BaseLogger.log("3", null, null,
							"processRequest processRequestResultClientDev" + processRequestResultClientDev + "]");
					Document dom = genericUtility.parseString(processRequestResultClientDev);
					String tranSuccessFlag = checkNull(genericUtility.getColumnValue("Detail", dom));
					if (tranSuccessFlag.trim().equalsIgnoreCase("Success")) {
						BaseLogger.log("3", null, null, "Transaction created on client Dev succesfully");
						Connection conn1 = getConnection();
						String updateTxnStatusSql = "update sql_changes set TXN_STATUS = 'D' where tran_id = ?";
						PreparedStatement updateTxnStatusPs = conn1.prepareStatement(updateTxnStatusSql);
						updateTxnStatusPs.setString(1, tranID);
						int updateAprvLvlCnt = updateTxnStatusPs.executeUpdate();
						conn1.commit();

						BaseLogger.log("3", null, null, "updateAprvLvlCnt::" + updateAprvLvlCnt + "]");
						if (updateTxnStatusPs != null) {
							updateTxnStatusPs.close();
							updateTxnStatusPs = null;
						}
						if (conn1 != null) {
							conn1.close();
							conn1 = null;
						}
						return itmDBAccessEJB.getErrorString("", "MSQLRCD", "", "", conn);
					}

					else {
						BaseLogger.log("3", null, null, "Transaction creation failed on client dev");
						return itmDBAccessEJB.getErrorString("", "MSQLFCD", "", "", conn);

					}
				}
			}
			// Added for PILOT transaction -- END

			// Added for Live transaction -- START
			// Fetch DB_MAIN from ENTERPRISE table to use as the enterprise for the Live
			// transaction
			if (action.trim().equalsIgnoreCase("Release to Live")) {
				BaseLogger.log("3", null, null, "In DB_MAIN condition.........");

				String pilotConfirmedFlag = "";
				String checkPilotConfirmed = "select confirmed from sql_changes where tran_id__ref = ? and exec_rights = 'P'";
				PreparedStatement checkPilotConfirmedPs = conn.prepareStatement(checkPilotConfirmed);
				checkPilotConfirmedPs.setString(1, tranID);
				ResultSet checkPilotConfirmedRs = checkPilotConfirmedPs.executeQuery();
				while (checkPilotConfirmedRs.next()) {

					pilotConfirmedFlag = checkNull(checkPilotConfirmedRs.getString("confirmed"));
				}
				if (checkPilotConfirmedPs != null) {
					checkPilotConfirmedPs.close();
				}
				if (checkPilotConfirmedRs != null) {
					checkPilotConfirmedRs.close();
				}
				if (!pilotConfirmedFlag.trim().equalsIgnoreCase("Y")) {
					return itmDBAccessEJB.getErrorString("", "MSQLNCP", "", "", conn);
				}
				int countOfLiveTran = 0;
				String tranIdRedForLive = "";
				String checkEntryForLiveSql = "select count(tran_id) as LiveTranCount from sql_changes where tran_id__ref = ? and exec_rights = 'A'";
				PreparedStatement checkEntryForLivePs = conn.prepareStatement(checkEntryForLiveSql);
				checkEntryForLivePs.setString(1, tranID);
				ResultSet checkEntryForLiveRs = checkEntryForLivePs.executeQuery();
				while (checkEntryForLiveRs.next()) {
					countOfLiveTran = checkEntryForLiveRs.getInt("LiveTranCount");
				}
				BaseLogger.log("3", null, null, "In DB_MAIN condition :: countOfLiveTran:: " + countOfLiveTran);
				if (checkEntryForLivePs != null) {
					checkEntryForLivePs.close();
				}
				if (checkEntryForLiveRs != null) {
					checkEntryForLiveRs.close();
				}

				String checkTranIdRefSql = "select tran_id__ref  from sql_changes where tran_id__ref = ? and exec_rights = 'P'";
				PreparedStatement checkTranIdRefPs = conn.prepareStatement(checkTranIdRefSql);
				checkTranIdRefPs.setString(1, tranID);
				ResultSet checkTranIdRefRs = checkTranIdRefPs.executeQuery();
				while (checkTranIdRefRs.next()) {
					tranIdRedForLive = checkNull(checkTranIdRefRs.getString("tran_id__ref"));

				}
				BaseLogger.log("3", null, null, "In DB_MAIN condition :: tranIdRedForLive:: " + tranIdRedForLive);
				if (checkTranIdRefPs != null) {
					checkTranIdRefPs.close();
				}
				if (checkTranIdRefRs != null) {
					checkTranIdRefRs.close();
				}

				if (tranIdRedForLive.trim().length() == 0) {
					BaseLogger.log("3", null, null, "In DB_MAIN condition :: tran_id__ref is blank:: ");
					return itmDBAccessEJB.getErrorString("", "MSQLAPL", "", "", conn);

				}
				if (countOfLiveTran > 0) {
					return itmDBAccessEJB.getErrorString("", "MSQLAPL", "", "", conn);

				}
				String dbLiveEnterprise = "";
				Connection liveEntConn = null;
				PreparedStatement livePstmt = null;
				ResultSet liveRs = null;
				StringBuilder dbLiveBuilder = new StringBuilder();

				try {
					ConnDriver liveEntConnConnDriver = new ConnDriver();
					liveEntConn = liveEntConnConnDriver.getConnectDB("Driver");

					String[] entArray = enterprises.split(",");

					String liveSql = "SELECT DB_MAIN FROM ENTERPRISE WHERE ENTERPRISE = ?";
					livePstmt = liveEntConn.prepareStatement(liveSql);

					for (String ent : entArray) {
						ent = ent.trim();

						livePstmt.setString(1, ent);
						liveRs = livePstmt.executeQuery();

						if (liveRs.next()) {
							String dbMain = checkNull(liveRs.getString("DB_MAIN"));

							if (dbMain != null && !dbMain.isEmpty()) {
								if (dbLiveBuilder.length() > 0) {
									dbLiveBuilder.append(",");
								}
								dbLiveBuilder.append(dbMain);
							}
						}

						if (liveRs != null)
							liveRs.close(); // close inside loop
					}

					dbLiveEnterprise = dbLiveBuilder.toString();

				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (liveRs != null) {
						liveRs.close();
					}
					if (livePstmt != null) {
						livePstmt.close();
					}
					if (liveEntConn != null) {
						liveEntConn.close();
					}
				}

				BaseLogger.log("3", null, null, "DB_PILOT enterprise fetched: [" + dbLiveEnterprise + "]");

				if (!dbLiveEnterprise.isEmpty()) {
					// Create PILOT XML with exec_rights = "P" and enterprise from DB_DEV column
					String xmlWithA = processDynXmlString.toString().replace("{{executionRights}}", "A");
					xmlWithA = xmlWithA.replace("{{enterprises}}", dbLiveEnterprise);
					BaseLogger.log("3", null, null, "xmlWithA XML:::" + xmlWithA + "]");

					MasterStatefulLocal masterStateful = null;
					appConnect = null;
					initialContext = null;

					appConnect = new AppConnectParm();
					initialContext = new InitialContext(appConnect.getProperty());
					masterStateful = (MasterStatefulLocal) initialContext
							.lookup("ibase/MasterStatefulEJB/local");

					String processRequestResultLive = masterStateful.processRequest(userInfo, xmlWithA, false, conn);
					BaseLogger.log("3", null, null,
							"processRequest processRequestResultLive" + processRequestResultLive + "]");
					Document dom = genericUtility.parseString(processRequestResultLive);
					String tranSuccessFlag = checkNull(genericUtility.getColumnValue("Detail", dom));
					if (tranSuccessFlag.trim().equalsIgnoreCase("Success")) {

						BaseLogger.log("3", null, null, "Transaction created on Live succesfully");
						Connection conn1 = getConnection();
						String updateTxnStatusSql = "update sql_changes set TXN_STATUS = 'L' where tran_id = ?";
						PreparedStatement updateTxnStatusPs = conn1.prepareStatement(updateTxnStatusSql);
						updateTxnStatusPs.setString(1, tranID);
						int updateAprvLvlCnt = updateTxnStatusPs.executeUpdate();
						conn1.commit();

						BaseLogger.log("3", null, null, "updateAprvLvlCnt::" + updateAprvLvlCnt + "]");
						if (updateTxnStatusPs != null) {
							updateTxnStatusPs.close();
							updateTxnStatusPs = null;
						}
						if (conn1 != null) {
							conn1.close();
							conn1 = null;
						}
						return itmDBAccessEJB.getErrorString("", "MSQLRTL", "", "", conn);
					}

					else {
						BaseLogger.log("3", null, null, "Transaction creation failed on Live");
						return itmDBAccessEJB.getErrorString("", "MSQLFTL", "", "", conn);

					}
				}
			}
			// Added for Live transaction -- END
		} catch (Exception e) {
			e.printStackTrace();
			throw new ITMException(e);
		} finally {
			try {
				if (conn != null) {
					conn.close();
					conn = null;

				}
			} catch (Exception e) {
			}
		}
		return retString;
	}

	public static String formatDateTime(LocalDate tranDate, LocalTime tranTime) {
		LocalDateTime tranDateTime = LocalDateTime.of(tranDate, tranTime);
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String formattedDateTime = tranDateTime.format(formatter);
		return formattedDateTime;
	}

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

	public static String dateFormatter(String inputDateString) {
		String result = "";
		String inputFormat = "yyyy-MM-dd HH:mm:ss";
		String outputFormat = "dd/MM/yy HH:mm:ss";

		try {
			// Parse input date string
			SimpleDateFormat inputFormatter = new SimpleDateFormat(inputFormat);
			Date date = inputFormatter.parse(inputDateString);

			// Format the date in the desired output format
			SimpleDateFormat outputFormatter = new SimpleDateFormat(outputFormat);
			String outputDateString = outputFormatter.format(date);

			System.out.println("Input Date: " + inputDateString);
			System.out.println("Formatted Date: " + outputDateString);
			result = outputDateString;

		} catch (Exception e) {
			BaseLogger.log("3", null, null, "Exception in dateFormatter. [" + E12GenericUtility.getStackTrace(e) + "]");
		}
		return result;
	}
}
