package ibase.webitm.ejb.dis;


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

import org.w3c.dom.Document;

import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

public class ReqForQuotationPostSave extends ValidatorEJB {

	String objName = "", detailNode = "";
	E12GenericUtility genericUtility = new E12GenericUtility();

	public String postSave(String xmlString, String tranId, String editFlag, String xtraParams, Connection conn)
			throws RemoteException, ITMException {

		Document dom = null;
		String errString = "";

		try {
			if (xmlString != null && xmlString.trim().length() > 0) {
				dom = parseString(xmlString);
				errString = postSave(dom, tranId, xtraParams, conn);
			}

		} catch (Exception e) {
			BaseLogger.log("0", null, null, "Exception : ReqForQuotationPostSave : postSave : ==>\n" + e.getMessage());
			throw new ITMException(e);
		}
		return errString;
	}

	
	
	
	public String postSave(Document dom, String tranId, String xtraParams, Connection conn) throws ITMException {

	    BaseLogger.log("3", getUserInfo(), null, "tran_id---->>[" + tranId + "]");
	    BaseLogger.log("3", getUserInfo(), null, "in ReqForQuotationPostSave postSave tran_id---->>[" + tranId + "]");
		BaseLogger.log("3", getUserInfo(), null, "in ReqForQuotationPostSave postSave xtraParams---->>[" + xtraParams.toString() + "]");
		tranId = checkNull(genericUtility.getColumnValue("tran_id", dom));
		BaseLogger.log("3", getUserInfo(), null, "in ReqForQuotationPostSave postSave tran_id---->>[" + tranId + "]");
		BaseLogger.log("3", getUserInfo(), null,  "dom ReqForQuotationPostSave*>>>> Elements>>["+genericUtility.serializeDom(dom).toString()+"]");//added for testing
		
	    PreparedStatement ps = null;
	    ResultSet rs = null;
	    String errorString = "";

	    try {

	        if (conn == null) {
	            conn = getConnection(); // only fallback
	        }

	        String sql = "SELECT PTR, RATE_QUOT FROM SALES_QUOT_REQ_DET WHERE TRAN_ID = ?";
	        ps = conn.prepareStatement(sql);
	        ps.setString(1, tranId);
	        rs = ps.executeQuery();

	        boolean allEqual = true;

	        while (rs.next()) {

	            BigDecimal ptrVal = rs.getBigDecimal("PTR") != null ? rs.getBigDecimal("PTR") : BigDecimal.ZERO;
	            BigDecimal rateVal = rs.getBigDecimal("RATE_QUOT") != null ? rs.getBigDecimal("RATE_QUOT") : BigDecimal.ZERO;

	            BaseLogger.log("3", null, null, "Comparing PTR: " + ptrVal + " with RATE_QUOT: " + rateVal);

	            if (rateVal.compareTo(ptrVal) != 0) {
	                allEqual = false;
	                break;
	            }
	        }

	        // ✅ Update ONLY AFTER loop
	        if (allEqual) {

	            BaseLogger.log("3", null, null, "All values matched → Updating mgmnt_apprv");

	            String updateSql = "UPDATE SALES_QUOT_REQ SET mgmnt_apprv = 'D' WHERE TRAN_ID = ?";
	            PreparedStatement updPs = conn.prepareStatement(updateSql);
	            updPs.setString(1, tranId);

	            int count = updPs.executeUpdate();
	            BaseLogger.log("3", null, null, "Rows updated: " + count);

	            if (updPs != null) updPs.close();
	        }

	    } catch (Exception e) {

	        BaseLogger.log("0", null, null, "Exception : " + e.getMessage());
	        throw new ITMException(e);

	    } finally {

	        try {
	            if (rs != null) rs.close();
	            if (ps != null) ps.close();

	            // ❌ DO NOT CLOSE CONNECTION HERE
	            // ❌ DO NOT COMMIT / ROLLBACK

	        } catch (Exception e) {
	            BaseLogger.log("0", null, null, "Error closing resources: " + e.getMessage());
	        }
	    }

	    return errorString;
	}

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

}

