/*
 * Author: Gagan B., Ajit D.
 * Date: 11-NOV-2025
 * Purpose: Logic for activities to be done Post Manage SQL Transaction
 * */

package ibase.webitm.ejb.sys;

import java.rmi.RemoteException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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 org.w3c.dom.Document;

import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.utility.EMail;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

public class ManageSQLAprv extends ValidatorEJB {

	E12GenericUtility genericUtility = new E12GenericUtility();

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

	public String updateWFStatus(String domString, Connection conn) throws RemoteException, ITMException {
		String refSer = "";
		String tranID = "";
		String signStatus = "";
		boolean isLocalConn = false;
		String empCode = "";
		String allocatedTo = "";
		String signRemarks = "";
		String retString = "";
		String reviewYn = "";
		String empCodeMerge = "";
		String deptCode = "";

		PreparedStatement updPstmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			UserInfoBean userInfo = getUserInfo();
			BaseLogger.log("3", null, null, "userInfo 91::" + userInfo.toString() + "]");
			System.out.println("ManageSQLAprv.updateWFStatus() domString testtttttttt[" + domString + "]");
			if (conn == null) {
				ConnDriver connDriver = new ConnDriver();
				conn = connDriver.getConnectDB(userInfo.getTransDB());
				isLocalConn = true;
			}

			Document dom = genericUtility.parseString(domString);

			signStatus = checkNull(genericUtility.getColumnValue("sign_status", dom, "1"));
			signRemarks = checkNull(genericUtility.getColumnValue("sign_remarks", dom, "1"));
			refSer = genericUtility.getColumnValue("ref_ser", dom, "1");
			tranID = genericUtility.getColumnValue("ref_id", dom, "1");
			empCode = genericUtility.getColumnValue("emp_code", dom, "1");
			allocatedTo = checkNull(genericUtility.getColumnValue("allocated_to", dom, "1"));

			System.out.println("tran_id::" + tranID + " signStatus::" + signStatus);

			// ===== UPDATE =====
			String updSql = "UPDATE sql_changes SET wf_status = ?, wf_remarks = ?, aprv_level = ? WHERE tran_id = ?";
			updPstmt = conn.prepareStatement(updSql);

			if ("R".equalsIgnoreCase(signStatus)) {
				updPstmt.setString(1, "R");
				updPstmt.setString(2, signRemarks);
				updPstmt.setNull(3, java.sql.Types.INTEGER);
			} else if ("S".equalsIgnoreCase(signStatus)) {
				updPstmt.setString(1, "A");
				updPstmt.setString(2, signRemarks);
				updPstmt.setInt(3, 2);
			}

			updPstmt.setString(4, tranID);
			int updCnt = updPstmt.executeUpdate();

			System.out.println("Updated count:: " + updCnt);

			// STOP if rejected
			if ("R".equalsIgnoreCase(signStatus)) {
				System.out.println("Workflow rejected");
				return "";
			}

			// ===== FETCH XML ===== //Added By Saburi
			String sql = "select OST.TRANS_INFO_XML.getClobval() XML_DATA from obj_sign_trans OST where ref_id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranID);

			rs = pstmt.executeQuery();

			if (rs.next()) {
				String xmlData = rs.getString("XML_DATA");
				BaseLogger.log("3", null, null, "ManageSQLAprv in xmlData:: " + xmlData);

				if (xmlData != null && xmlData.trim().length() > 0) {
					Document detailDom = genericUtility.parseString(xmlData);
					BaseLogger.log("3", null, null, "ManageSQLAprv in detailDom:: " + detailDom);
					reviewYn = genericUtility.getColumnValue("review_yn", detailDom);
					empCodeMerge = genericUtility.getColumnValue("emp_code__merge", detailDom);
					BaseLogger.log("3", null, null, "ManageSQLAprv in reviewYn:: " + reviewYn);
					BaseLogger.log("3", null, null, "ManageSQLAprv in empCodeMerge:: " + empCodeMerge);

					if ("Y".equalsIgnoreCase(reviewYn) && "S".equalsIgnoreCase(signStatus)) 
					{
						sendReviewMail(tranID, reviewYn, userInfo, detailDom, conn);
					}
				}
			}


			//Cheking the department of the user who make the transaction
			//If its from SUPPORT/IMPLEMENTATION then update the Execution Rights to "A"
			String fetchDeptCodeSql = "select dept_code from employee where TRIM(emp_code) in TRIM(( select emp_code from users where code = ? ))";
			PreparedStatement fetchDeptCodePs = conn.prepareStatement(fetchDeptCodeSql);
			fetchDeptCodePs.setString(1, empCodeMerge);
			ResultSet fetchDeptCodeRs = fetchDeptCodePs.executeQuery();
			while (fetchDeptCodeRs.next()) {
				deptCode = checkNull(fetchDeptCodeRs.getString("dept_code"));
			}

			BaseLogger.log("3", null, null, "ManageSQLAprv in deptCode:: " + deptCode);

			//Updating the Execution Rights if the department code is from support/implementation.
			if(deptCode.trim().equalsIgnoreCase("0110") || deptCode.trim().equalsIgnoreCase("0120")){
			BaseLogger.log("3", null, null, "Transaction done by support/implemenation department user");

			String updateExecRights = "update sql_changes set exec_rights = 'A' where tran_id = ?";
			PreparedStatement updateExecRightsPs = conn.prepareStatement(updateExecRights);
			updateExecRightsPs.setString(1, tranID);
			int updateExecRightsCount = updateExecRightsPs.executeUpdate();
			BaseLogger.log("3", null, null, "ManageSQLAprv in updateExecRightsCount:: " + updateExecRightsCount);
			}


		} catch (Exception e) {
			e.printStackTrace();
			throw new ITMException(e);
		} finally {
			try {
				if (rs != null)
					rs.close();
			} catch (Exception e) {
			}
			try {
				if (pstmt != null)
					pstmt.close();
			} catch (Exception e) {
			}
			try {
				if (updPstmt != null)
					updPstmt.close();
			} catch (Exception e) {
			}

			try {
				if (conn != null && isLocalConn) {
					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;
	}

	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;
	}

	private void closeResources(ResultSet rs, PreparedStatement pstmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

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

	//Added By Saburi-24Apr2026 for sending email for sql review request	
	private void sendReviewMail(String tranID, String reviewYn, UserInfoBean userInfo, Document detailDom, Connection conn) 
	{
		try {
			BaseLogger.log("3", null, null, "===== sendReviewMail START =====");
			BaseLogger.log("3", null, null, "tranID:: " + tranID);
			BaseLogger.log("3", null, null, "reviewYn:: " + reviewYn);

			if (detailDom == null) {
				BaseLogger.log("3", null, null, "ERROR: detailDom is NULL");
				return;
			}

			EMail email = new EMail();

			String mailSubject = "Request for Approval: SQL Execution [" + tranID + "]";

			// ===== Fetch values from XML =====
			String reqId = checkNull(genericUtility.getColumnValue("req_id", detailDom)).trim();
			String reqDescr = checkNull(genericUtility.getColumnValue("req_descr", detailDom));
			String addedBy = checkNull(genericUtility.getColumnValue("name", detailDom));
			String custName = checkNull(genericUtility.getColumnValue("cust_name", detailDom));
			String tranDate = checkNull(genericUtility.getColumnValue("tran_date", detailDom));
			String enterprise = checkNull(genericUtility.getColumnValue("enterprises", detailDom));

			String sql = "SELECT ORA_STMNT FROM SQL_CHANGES_DET WHERE TRAN_ID = ?";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranID);

			ResultSet rs = pstmt.executeQuery();

			StringBuilder sqlBuilder = new StringBuilder();

			while (rs.next()) 
			{
				String sqlStmt = checkNull(rs.getString("ORA_STMNT"));

				BaseLogger.log("3", null, null, "Fetched SQL:: " + sqlStmt);

				if (sqlStmt != null && sqlStmt.trim().length() > 0) {
					sqlBuilder.append(sqlStmt);
					sqlBuilder.append("\n\n----------------------------------------\n\n"); // separator
				}
			}

			String finalSql = sqlBuilder.toString();

			// ===== HTML Body =====
			StringBuilder body = new StringBuilder();

			body.append("<html><body style='font-family: Arial, sans-serif; font-size: 13px;'>");

			body.append("<p>Dear Piyush Sir / SM Sir,</p>");

			body.append(
					"<p>KB Sir has requested your review for the below Transaction SQL.</p>");

			// ===== Transaction Summary Box =====
			body.append("<div style='border:1px solid #d3d3d3; background-color:#f5f5f5; padding:15px; width:600px;'>");

			body.append("<h4 style='margin-top:0;'>Transaction Summary:</h4>");
			body.append("<table style='width:100%;'>");

			String labelStyle = "style='padding:4px 8px; font-weight:bold; width:40%;'";
			String valueStyle = "style='padding:4px 8px;'";

			body.append(
					"<tr><td " + labelStyle + ">Transaction ID:</td><td " + valueStyle + ">" + tranID + "</td></tr>");
			body.append("<tr><td " + labelStyle + ">Request ID / Ticket ID:</td><td " + valueStyle + ">" + reqId
					+ "</td></tr>");
			body.append("<tr><td " + labelStyle + ">Request Description:</td><td " + valueStyle + ">" + reqDescr
					+ "</td></tr>");
			body.append("<tr><td " + labelStyle + ">Added By:</td><td " + valueStyle + ">" + addedBy + "</td></tr>");
			body.append(
					"<tr><td " + labelStyle + ">Customer Name:</td><td " + valueStyle + ">" + custName + "</td></tr>");
			body.append("<tr><td " + labelStyle + ">Initiation Date:</td><td " + valueStyle + ">" + tranDate
					+ "</td></tr>");
			body.append(
					"<tr><td " + labelStyle + ">Enterprises:</td><td " + valueStyle + ">" + enterprise + "</td></tr>");

			body.append("</table>");
			body.append("</div>");

			// =========================
			// ✅ ADD THIS BLOCK (SQL UI)
			// =========================

			body.append("<div style='margin-top:25px;'>");

			body.append("<h4 style='margin-bottom:10px; font-size:14px; color:#333;'>SQL Details:</h4>");

			body.append(
					"<table style='width:600px; border:1px solid #dcdcdc; border-collapse:collapse; background-color:#fafafa;'>");

			body.append("<tr>");
			body.append(
					"<td style='padding:0; border:1px solid #dcdcdc;'>");

			body.append(
					"<div style='background-color:#2b2b2b; color:#f8f8f2; " +
							"padding:15px; font-family:Courier New, monospace; " +
							"font-size:12px; line-height:1.6; " +
							"white-space:pre-wrap; word-wrap:break-word;'>");

			body.append(finalSql);

			body.append("</div>");

			body.append("</td>");
			body.append("</tr>");
			body.append("</table>");

			body.append("</div>");

			// =========================

			body.append("</body></html>");

			String mailBody = body.toString();

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

			// ===== Emails =====
			// String toEmails = "saburi.patekar@proteustech.in";
			String toEmail1 = getSysparmValue(conn, "MS_REV_EMAIL_1");
			String toEmail2 = getSysparmValue(conn, "MS_REV_EMAIL_2");
			String ccEmail = getSysparmValue(conn, "MS_REV_EMAIL_EXEC");

			// Combine TO emails
			String toEmails = toEmail1;
			if (toEmail2 != null && toEmail2.length() > 0) 
			{
				toEmails = toEmails + "," + toEmail2;
				BaseLogger.log("3", null, null, "toEmails::@@@ " + toEmails);
			}

			String mailXml = "<ROOT>" +
					"<MAIL>" +
					"<EMAIL_TYPE>page</EMAIL_TYPE>" +
					"<ENTITY_CODE>BASE</ENTITY_CODE>" +
					"<ENTITY_TYPE>E</ENTITY_TYPE>" +
					"<MESSAGE_TYPE><![CDATA[text/html]]></MESSAGE_TYPE>" +
					"<SUBJECT><![CDATA[" + mailSubject + "]]></SUBJECT>" +
					"<BODY_TEXT><![CDATA[" + mailBody + "]]></BODY_TEXT>" +
					"<TO_ADD>" + toEmails + "</TO_ADD>" +
					"<CC_ADD>" + ccEmail + "</CC_ADD>" +
					"<BCC_ADD></BCC_ADD>" +
					"<ATTACHMENT><BODY></BODY><LOCATION></LOCATION></ATTACHMENT>" +
					"</MAIL>" +
					"</ROOT>";

			BaseLogger.log("3", null, null, "Mail XML:: " + mailXml);

			String result = email.sendMail(mailXml, "ITM", userInfo);

			BaseLogger.log("3", null, null, "Mail sent result:: " + result);

		} catch (Exception e) {
			BaseLogger.log("3", null, null, "Error sending review mail:: " + e.getMessage());
		}
	}

	private String getSysparmValue(Connection conn, String varName) throws SQLException {
    String value = "";
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        String sql = "SELECT var_value FROM sysparm WHERE var_name = ?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, varName);

        rs = pstmt.executeQuery();

        if (rs.next()) {
            value = checkNull(rs.getString("var_value")).trim();
        }
    } finally {
        if (rs != null) rs.close();
        if (pstmt != null) pstmt.close();
    }

    return value;
}
}
