package ibase.webitm.ejb.dis;

import java.math.BigDecimal;
import java.math.RoundingMode;
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.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

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

public class ReqForQuotationIC extends ValidatorEJB {
	E12GenericUtility genericUtility = new E12GenericUtility();

	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null,
				">>>>>>>>>>>>>>>>>>ReqForQuotationIC validation called>>>>>>>>>>>>>>>>>>>:::");

		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = null;
		BaseLogger.log("3", null, null, "xmlString ReqForQuotationIC [" + xmlString + "]");
		BaseLogger.log("3", null, null, "xmlString1 ReqForQuotationIC [" + xmlString1 + "]");
		BaseLogger.log("3", null, null, "xmlString2 ReqForQuotationIC [" + xmlString2 + "]");
		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) {
				dom2 = genericUtility.parseString(xmlString2);
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
			BaseLogger.log("3", null, null, "ErrString: " + errString);

		} catch (Exception e) {
			System.out.println("Exception: ReqForQuotationIC: wfValData(String xmlString): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		BaseLogger.log("3", null, null, "Returning from ReqForQuotationIC wfValData");

		return (errString);
	}
	public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null, "9>>>>>>>>>>>>>>>>>>ReqForQuotationIC validation called >>>>>>>>>>>>>>>>>>>");
		BaseLogger.log("3", null, null, "Inside ReqForQuotationIC validation");


		GenericUtility genericUtility = GenericUtility.getInstance();
        try {
			BaseLogger.log("3", getUserInfo(), null,  "dom case2*>>>> Elements>>["+genericUtility.serializeDom(dom).toString()+"]");//added for testing
            BaseLogger.log("3", getUserInfo(), null,  "dom2 case2*>>>> Elements>>["+genericUtility.serializeDom(dom2).toString()+"]");//added for testing
			BaseLogger.log("3", getUserInfo(), null,  "dom1 case2*>>>> Elements>>["+genericUtility.serializeDom(dom1).toString()+"]");
		} catch (BaseException e1) {
			e1.printStackTrace();
		}


		String userId = "";

		String requestId = "";
		String sql="";
		String errString = "";

		Connection connection = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;

		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = null;

		int noOfChilds = 0;
		int currentFormNo = 0;

		try
		{
			SimpleDateFormat DOB = new SimpleDateFormat(getApplDateFormat());
			connection = getConnection(); 

			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch ( currentFormNo )
			{
			case 1:
			{
				parentList = dom.getElementsByTagName("Detail"+ currentFormNo);
				int parentNodeListLength = parentList.getLength();
				System.out.println("parentNodeListLength["+parentNodeListLength+"]");

				for (int prntCtr = 0; prntCtr < parentNodeListLength; prntCtr++ )
				{
					parentNode = parentList.item(prntCtr);
					System.out.println("value of parentNode"+parentNode);
					childList = parentNode.getChildNodes();
					noOfChilds = childList.getLength();
					System.out.println("value of noOfChilds"+noOfChilds);
					for (int ctr = 0; ctr < noOfChilds; ctr++)
					{
						childNode = childList.item(ctr);
						System.out.println("childNode"+childNode);
						if( childNode.getNodeType() != Node.ELEMENT_NODE )
						{
							continue;
						}

						childNodeName = childNode.getNodeName();

						
						if( childNodeName.equalsIgnoreCase("cust_code") )
						{
							String custCode = checkNull(genericUtility.getColumnValue("cust_code", dom));
							BaseLogger.log("3", null, null, "ReqForQuotationIC custCode wfValData case 1 [" + custCode + "]");
							String checkCustCodeSql = "select count(cust_code) as custCodeCount from customer where cust_code = ?";
							PreparedStatement checkCustCodePs = connection.prepareStatement(checkCustCodeSql);
							checkCustCodePs.setString(1, custCode);
							ResultSet checkCustCodeRs = checkCustCodePs.executeQuery();
							while(checkCustCodeRs.next()) {
								int custCodeCont = checkCustCodeRs.getInt("custCodeCount");
								BaseLogger.log("3", null, null, "ReqForQuotationIC custCode wfValData case 1 custCodeCont::[" + custCodeCont + "]");
                                if(custCodeCont<=0) {
							        errString = getErrorString("cust_code", "VTCUST1", userId);
							        break;
                                }
								
							}
							if(checkCustCodeRs != null)
							{
								checkCustCodeRs.close();
								checkCustCodeRs = null;
							}
							if(checkCustCodePs != null)
							{
								checkCustCodePs.close();
								checkCustCodePs = null;
							}
						}
						
						
						if( childNodeName.equalsIgnoreCase("valid_upto") )
						{
							
							String validUptoStr = checkNull(genericUtility.getColumnValue("valid_upto", dom));
							BaseLogger.log("3", null, null, "ReqForQuotationIC validUptoStr wfValData case 1 [" + validUptoStr + "]");
							   if(isDateInvalid(validUptoStr))
							    {
							        errString = getErrorString("valid_upto", "VTINUPTO", userId);
                                    break;
							    }							

						}
						
						if( childNodeName.equalsIgnoreCase("site_code") )
						{
							String siteCode = checkNull(genericUtility.getColumnValue("site_code", dom));
							BaseLogger.log("3", null, null, "ReqForQuotationIC siteCode wfValData case 1 [" + siteCode + "]");
							String checkSiteCodeSql = "select count(site_code) as siteCodeCount from site where site_code = ?";
							PreparedStatement checkSiteCodePs = connection.prepareStatement(checkSiteCodeSql);
							checkSiteCodePs.setString(1, siteCode);
							ResultSet checkSiteCodeRs = checkSiteCodePs.executeQuery();
							while(checkSiteCodeRs.next()) {
								int siteCodeCont = checkSiteCodeRs.getInt("siteCodeCount");
								BaseLogger.log("3", null, null, "ReqForQuotationIC siteCode wfValData case 1 siteCodeCont::[" + siteCodeCont + "]");
                                if(siteCodeCont<=0) {
							        errString = getErrorString("site_code", "VTSITCD1", userId);
							        break;
                                }
								
							}
							if(checkSiteCodeRs != null)
							{
								checkSiteCodeRs.close();
								checkSiteCodeRs = null;
							}
							if(checkSiteCodePs != null)
							{
								checkSiteCodePs.close();
								checkSiteCodePs = null;
							}
						}
						
						
						if( childNodeName.equalsIgnoreCase("item_ser") )
						{
							String itemSerStr = checkNull(genericUtility.getColumnValue("item_ser", dom));
							BaseLogger.log("3", null, null, "ReqForQuotationIC itemSerStr wfValData case 1 [" + itemSerStr + "]");
							   if (itemSerStr != null && itemSerStr.length() > 0) {
		                            String[] itemSerArr = itemSerStr.split(",");
		                            for (String itemSer : itemSerArr) {
		    							BaseLogger.log("3", null, null, "ReqForQuotationIC item_ser wfValData case 1 itemSer [" + itemSer + "]");

		                                sql = "SELECT count(1) FROM itemser WHERE item_ser = ?";
		                                pstmt = connection.prepareStatement(sql);
		                                pstmt.setString(1, itemSer.trim());
		                                rs = pstmt.executeQuery();
		                                long count = 0;
		                                if (rs.next()) {
		                                    count = rs.getLong(1);
		                                }
		                                rs.close();
		                                rs = null;
		                                pstmt.close();
		                                pstmt = null;
		                                if (count == 0) {
									        errString = getErrorString("item_ser", "VTITEMSER1", userId);
		                                    break;
		                                }
		                                
		                            }
		                        }

								if(pstmt != null)
								{
									pstmt.close();
									pstmt = null;
								}
								if(rs != null)
								{
									rs.close();
									rs = null;
								}
						}
					}
				}
				break;
			}
			
			case 2:
				{
					parentList = dom.getElementsByTagName("Detail"+ currentFormNo);
					int parentNodeListLength = parentList.getLength();
					System.out.println("parentNodeListLength["+parentNodeListLength+"]");

					for (int prntCtr = 0; prntCtr < parentNodeListLength; prntCtr++ )
					{
						parentNode = parentList.item(prntCtr);
						System.out.println("value of parentNode"+parentNode);
						childList = parentNode.getChildNodes();
						noOfChilds = childList.getLength();
						System.out.println("value of noOfChilds"+noOfChilds);
						for (int ctr = 0; ctr < noOfChilds; ctr++)
						{
							childNode = childList.item(ctr);
							System.out.println("childNode"+childNode);
							if( childNode.getNodeType() != Node.ELEMENT_NODE )
							{
								continue;
							}

							childNodeName = childNode.getNodeName();
							if( childNodeName.equalsIgnoreCase("item_code") )
							{
								String itemCode = checkNull(genericUtility.getColumnValue("item_code", dom));
								BaseLogger.log("3", null, null, "ReqForQuotationWiz itemCode wfValData case 1 [" + itemCode + "]");
								String checkItemCodeSql = "select count(item_code) as itemCodeCount from item where item_code = ?";
								PreparedStatement checkItemCodePs = connection.prepareStatement(checkItemCodeSql);
								checkItemCodePs.setString(1, itemCode);
								ResultSet checkItemCodeRs = checkItemCodePs.executeQuery();
								while(checkItemCodeRs.next()) {
									int itemCodeCont = checkItemCodeRs.getInt("itemCodeCount");
									BaseLogger.log("3", null, null, "ReqForQuotationWiz itemCode wfValData case 1 itemCodeCont::[" + itemCodeCont + "]");
	                                if(itemCodeCont<=0) {
								        errString = getErrorString("item_code", "STKVALITNE", userId);
								        break;
	                                }
									
								}
								if(checkItemCodeRs != null)
								{
									checkItemCodeRs.close();
									checkItemCodeRs = null;
								}
								if(checkItemCodePs != null)
								{
									checkItemCodePs.close();
									checkItemCodePs = null;
								}
							}
							
							if( childNodeName.equalsIgnoreCase("ptr_flag") )
							{
								String ptrFlag = checkNull(genericUtility.getColumnValue("ptr_flag", dom));
								String competitorRate = checkNull(genericUtility.getColumnValue("competitor_rate", dom));
								String competitorItem = checkNull(genericUtility.getColumnValue("competitor_item", dom));
								String competitorName = checkNull(genericUtility.getColumnValue("competitor_name", dom));
								BaseLogger.log("3", null, null, "ReqForQuotationIC ptrFlag wfValData [" + ptrFlag + "]");
								BaseLogger.log("3", null, null, "ReqForQuotationIC competitorRate wfValData [" + competitorRate + "]");
								BaseLogger.log("3", null, null, "ReqForQuotationIC competitorItem wfValData [" + competitorItem + "]");
								BaseLogger.log("3", null, null, "ReqForQuotationIC competitorNane wfValData [" + competitorName + "]");


								if (ptrFlag.equalsIgnoreCase("N") || ptrFlag.trim().isEmpty()) {
								    BaseLogger.log("3", null, null, "ReqForQuotationIC in condition ptrFlag wfValData::: [" + ptrFlag + "]");

								    // Check if any of the competitor fields are null or blank
								    if ((competitorRate == null || competitorRate.trim().isEmpty()) 
								            || (competitorItem == null || competitorItem.trim().isEmpty()) 
								            || (competitorName == null || competitorName.trim().isEmpty())) { 
								        BaseLogger.log("3", null, null, "ReqForQuotationIC in competitor details null [" + ptrFlag + "]");
								        errString = getErrorString("ptr_flag", "COMPDETM", userId);
								        BaseLogger.log("3", null, null, "ReqForQuotationIC in competitor details null errString:: [" + errString + "]");
								        break;
								    }
								}

							}
							if( childNodeName.equalsIgnoreCase("rate_quot") )
							{
								String phyAttrVal = "";
								String itemCode = checkNull(genericUtility.getColumnValue("item_code", dom));
							    BaseLogger.log("3", null, null, "ReqForQuotationIC in condition itemCode wfValData itemCode::: [" + itemCode + "]");
                                String phyAttrValSql = "select PHY_ATTRIB_19 from item where item_code = ?";
                                PreparedStatement phyAttrValPs = connection.prepareStatement(phyAttrValSql);
                                phyAttrValPs.setString(1, itemCode);
                                ResultSet phyAttrValRs = phyAttrValPs.executeQuery();
                                while(phyAttrValRs.next()) {
                                	 phyAttrVal = checkNull(phyAttrValRs.getString("PHY_ATTRIB_19"));
                                }
							    BaseLogger.log("3", null, null, "ReqForQuotationIC in condition itemCode wfValData phyAttrVal::: [" + phyAttrVal + "]");
                                if(phyAttrVal.equalsIgnoreCase("SRNA")) {
							        errString = getErrorString("rate_quot", "INVALRC", userId);
							        BaseLogger.log("3", null, null, "ReqForQuotationIC in PHY_ATTRIB_19 details null errString:: [" + errString + "]");

                                    break;
							       
                                }

							}
							//End elseif
						}//End for loop
					}//End for loop
					break;
				}//case1
			}//switch
		
		}//try
		catch (Exception e)
		{
			System.out.println ("Exception: wfValData(Document dom): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			throw new ITMException(e); 
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(connection != null)
				{
					connection.close();
					connection = null;
				}
            }
			catch(Exception e)
			{
				errString = genericUtility.createErrorString(e);
			}
		}
		return (errString);
	
	}
	
	
	public String itemChanged(String xmlString, String xmlString1, String xmlString2, String objContext,
			String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null,
				">>>>>>>>>>>>>>>>>> ReqForQuotationIC itemchange called Ajit>>>>>>>>>>>>>>>>>>>");
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = null;
		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) {
				dom2 = genericUtility.parseString(xmlString2);
			}
			BaseLogger.log("3", null, null, "xmlString ReqForQuotationIC [" + xmlString + "]");
			BaseLogger.log("3", null, null, "xmlString1 ReqForQuotationIC [" + xmlString1 + "]");
			BaseLogger.log("3", null, null, "xmlString2 ReqForQuotationIC [" + xmlString2 + "]");
			errString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
			BaseLogger.log("3", null, null, "ErrString :" + errString);

		} catch (Exception e) {
			BaseLogger.log("3", null, null, "Exception :ReqForQuotationIC :itemChanged(String,String):" + e.getMessage() + ":");

			errString = genericUtility.createErrorString(e);
		}
		BaseLogger.log("3", null, null, "returning from ReqForQuotationIC itemChanged");

		return errString;
	}
	
	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn,
			String editFlag, String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null, ">>>>>>>>>>>>>>>>>> ReqForQuotationIC itemchange called Ajit>>>>>>>>>>>>>>>>>>>");
		System.out.println("Inside itemchange");
		Connection con = null;
		PreparedStatement psSiteCustomer = null;
		PreparedStatement psCustomer = null;
		PreparedStatement psPriceList = null;
		PreparedStatement psFinEntity = null;
		String reStr = "";
		ResultSet rs = null;
		StringBuffer valueXmlString = null;
		int currentFormNo = 0;
		String userId = "";
		String sql = "";
		String priceList = "";
		int rate= 0;
		String finEntity = "";
		List<String> itemCodeList = new ArrayList<>();

		try {
			 UserInfoBean userInfo = getUserInfo(); 
			 String siteCode = checkNull(userInfo.getSiteCode());
			 String userCode = checkNull(userInfo.getLoginCode());
				BaseLogger.log("3", null, null, "ReqForQuotationIC in siteCodeFromUserInfo:: "+siteCode);
				BaseLogger.log("3", null, null, "ReqForQuotationIC in userCodeFromUserInfo:: "+userCode);

			con = getConnection();
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode"); // To get user details after login
			if (objContext != null && objContext.trim().length() > 0) {
				currentFormNo = Integer.parseInt(objContext);
			}

			// start creating xml
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			String ptrFlag = checkNull(genericUtility.getColumnValue("ptr_flag", dom));

			BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flat condition ptrFlag:: "+ptrFlag);

			BaseLogger.log("3", null, null, "ReqForQuotationIC currentFormNo "+currentFormNo);

			
			
			
			switch (currentFormNo) {
			case 1:
			{
				valueXmlString.append("<Detail1>");
				if ("itm_default".equalsIgnoreCase(currentColumn.trim())) {
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm_default case 1");

					// Set tran_date to current date
					SimpleDateFormat dtFormat = new SimpleDateFormat(getApplDateFormat());
					String currDate = dtFormat.format(Calendar.getInstance().getTime());
					valueXmlString.append("<tran_date>").append("<![CDATA[" + currDate + "]]>").append("</tran_date>\r\n");

					// Set req_date to current date
					valueXmlString.append("<req_date>").append("<![CDATA[" + currDate + "]]>").append("</req_date>\r\n");

					// Set site_code to logged in user's site code
					valueXmlString.append("<site_code>").append("<![CDATA[" + siteCode + "]]>").append("</site_code>\r\n");
					valueXmlString.append("<quot_type>").append("<![CDATA[C]]>").append("</quot_type>");

					// Set sales_pers to logged in user's code
					valueXmlString.append("<sales_pers>").append("<![CDATA[" + userCode + "]]>").append("</sales_pers>\r\n");
				}
				if ("cust_code".equalsIgnoreCase(currentColumn.trim())) {
					BaseLogger.log("3", null, null, "ReqForQuotationIC in item change case 1 cust_code condition");

					String custName = "", addr1 = "", addr2="", addr3="";
					String custCode = checkNull(genericUtility.getColumnValue("cust_code", dom));
					BaseLogger.log("3", null, null, "ReqForQuotationIC in case 1 cust_code:: "+custCode);
					String custDetilsSql = "select cust_name, addr1 , addr2 , addr3 from customer where cust_code = ?";
					PreparedStatement custDetailsPs = con.prepareStatement(custDetilsSql);
					custDetailsPs.setString(1, custCode);
					ResultSet custDetailsRs = custDetailsPs.executeQuery();
					while(custDetailsRs.next()) {
						custName = custDetailsRs.getString("cust_name");
						addr1 = custDetailsRs.getString("addr1");
						addr2 = custDetailsRs.getString("addr2");
						addr3 = custDetailsRs.getString("addr3");

					}
					BaseLogger.log("3", null, null, "ReqForQuotationIC in case 1 custName:: "+custName);
					valueXmlString.append("<cust_name>").append("<![CDATA["+custName+"]]>").append("</cust_name>\r\n");
					valueXmlString.append("<addr1>").append("<![CDATA["+addr1+"]]>").append("</addr1>\r\n");
					valueXmlString.append("<addr2>").append("<![CDATA["+addr2+"]]>").append("</addr2>\r\n");
					valueXmlString.append("<addr3>").append("<![CDATA["+addr3+"]]>").append("</addr3>\r\n");

				}
				
				if ("item_ser".equalsIgnoreCase(currentColumn.trim())) 
				{
				    String itemSerDescr = "";
				    String itemSerForIC = checkNull(genericUtility.getColumnValue("item_ser", dom, "1"));

				    BaseLogger.log("0", null, userId, "case 1::: item_ser");
				    System.out.println("case 1---------itemSerForIC05M------[" + itemSerForIC + "]");

				    if(itemSerForIC != null && itemSerForIC.trim().length() > 0)
				    {
				        String[] itemSerArr = itemSerForIC.split(",");

				        String itemSerSql = "select descr from itemser where item_ser = ?";
				        
				        try (PreparedStatement itemSerPs = con.prepareStatement(itemSerSql))
				        {
				            for(String itemSer : itemSerArr)
				            {
				                itemSerPs.setString(1, itemSer.trim());

				                try (ResultSet itemSerRs = itemSerPs.executeQuery())
				                {
				                    if(itemSerRs.next())
				                    {
				                        if(itemSerDescr.length() > 0)
				                        {
				                            itemSerDescr += ", ";
				                        }
				                        itemSerDescr += checkNull(itemSerRs.getString("descr"));
				                    }
				                }
				            }
				        }
				    }
				    setNodeValue(dom, "descr", itemSerDescr);
				    BaseLogger.log("0", null, userId, "case 1::: item_ser descr::"+itemSerDescr);
					valueXmlString.append("<descr>").append("<![CDATA["+itemSerDescr+"]]>").append("</descr>\r\n");
				}
				valueXmlString.append("</Detail1>");
                break;
			}
			case 2:
			{
				valueXmlString.append("<Detail2>");
				if ("itm_default".equalsIgnoreCase(currentColumn.trim())) {
					String custCode = checkNull(genericUtility.getColumnValue("cust_code", dom1));
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default ");
					//Management rate block[Start]
					String finEntityQuery = "select fin_entity from site where site_code = ?";
					psFinEntity = con.prepareStatement(finEntityQuery);
					psFinEntity.setString(1, siteCode);
					rs = psFinEntity.executeQuery();
					if(rs.next()) {
						finEntity = checkNull(rs.getString("fin_entity"));
					}
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default finEntity:: "+finEntity);

					rs.close();
					psFinEntity.close();
					
					// Now, use finEntity to fetch VAR_VALUE from finparm
					String varValueQuery = "select VAR_VALUE from finparm where ADDL_VALUE = ?";
					PreparedStatement psVarValue = con.prepareStatement(varValueQuery);
					psVarValue.setString(1, finEntity);
					ResultSet rsVarValue = psVarValue.executeQuery();
					String varValue = null;
					if (rsVarValue.next()) {
					    varValue = checkNull(rsVarValue.getString("VAR_VALUE"));
					}
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default varValue:: " + varValue);

					// Clean up the result set and prepared statement for the varValue query
					rsVarValue.close();
					psVarValue.close();

					// Finally, use varValue to fetch the rate from pricelist
					String rateQuery = "select rate from pricelist where price_list = ?";
					PreparedStatement psRate = con.prepareStatement(rateQuery);
					psRate.setString(1, varValue);
					ResultSet rsRate = psRate.executeQuery();
					int MngmntAprvRate = 0;
					if (rsRate.next()) {
						MngmntAprvRate = rsRate.getInt("rate");
					}
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default rate:: " + rate);

					// Clean up the result set and prepared statement for the rate query
					rsRate.close();
					psRate.close();
					
					
					String priceSql =
					        "SELECT fp.VAR_NAME, pl.rate " +
					        "FROM finparm fp " +
					        "JOIN site s ON s.fin_entity = fp.ADDL_VALUE " +
					        "JOIN pricelist pl ON pl.price_list = fp.VAR_VALUE " +
					        "WHERE s.site_code = ? " +
					        "AND fp.VAR_NAME IN ('RFQ_PTS','RFQ_PTD')";


					PreparedStatement psPrice = con.prepareStatement(priceSql);
					psPrice.setString(1, siteCode);

					ResultSet rsPrice = psPrice.executeQuery();

					BigDecimal pts = null;
					BigDecimal ptd = null;
					BigDecimal PriceRate = null;
					while (rsPrice.next()) {
						
					    String varName = checkNull(rsPrice.getString("VAR_NAME"));
					     PriceRate = rsPrice.getBigDecimal("rate");

					    if ("RFQ_PTS".equals(varName)) {
					        pts = PriceRate;
					    } else if ("RFQ_PTD".equals(varName)) {
					        ptd = PriceRate;
					    }
					}

					
					//PTR calculation start
				    String siteCustomerQuery = 
					        "SELECT PRICE_LIST FROM SITE_CUSTOMER " +
					        "WHERE SITE_CODE = ? AND CUST_CODE = ?";

					    psSiteCustomer = con.prepareStatement(siteCustomerQuery);
					    psSiteCustomer.setString(1, siteCode);
					    psSiteCustomer.setString(2, custCode);

					    rs = psSiteCustomer.executeQuery();

					    if (rs.next()) {
					        priceList = rs.getString("PRICE_LIST");
					    }

					    rs.close();
					    psSiteCustomer.close();

					    // Step 2: If not found in SITE_CUSTOMER, fetch from CUSTOMER
					    if (priceList == null || priceList.trim().isEmpty()) {

					        String customerQuery =
					            "SELECT PRICE_LIST FROM CUSTOMER WHERE CUST_CODE = ?";

					        psCustomer = con.prepareStatement(customerQuery);
					        psCustomer.setString(1, custCode);

					        rs = psCustomer.executeQuery();

					        if (rs.next()) {
					            priceList = rs.getString("PRICE_LIST");
					        }

					        rs.close();
					        psCustomer.close();
					    }

					    // Step 3: Fetch RATE from PRICELIST table
					    if (priceList != null && !priceList.trim().isEmpty()) {

					        String priceListQuery =
					            "SELECT RATE FROM PRICELIST WHERE PRICE_LIST = ?";

					        psPriceList = con.prepareStatement(priceListQuery);
					        psPriceList.setString(1, priceList);

					        rs = psPriceList.executeQuery();

					        if (rs.next()) {
					            rate = rs.getInt("RATE");
					        }

					        rs.close();
					        psPriceList.close();
					    }

					//PTR calculation end
					    
					    
					
					    
					
					valueXmlString.append("<rate_apprv>").append("<![CDATA["+MngmntAprvRate+"]]>").append("</rate_apprv>\r\n");
					valueXmlString.append("<ptd>").append("<![CDATA["+ptd+"]]>").append("</ptd>\r\n");
					valueXmlString.append("<pts>").append("<![CDATA["+pts+"]]>").append("</pts>\r\n");
					valueXmlString.append("<ptr>").append("<![CDATA["+rate+"]]>").append("</ptr>\r\n");

					//Management rate block[End]
				}
				if ("itm_defaultedit".equalsIgnoreCase(currentColumn.trim())) {
					String custCode = checkNull(genericUtility.getColumnValue("cust_code", dom1));
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default ");
					//Management rate block[Start]
					String finEntityQuery = "select fin_entity from site where site_code = ?";
					psFinEntity = con.prepareStatement(finEntityQuery);
					psFinEntity.setString(1, siteCode);
					rs = psFinEntity.executeQuery();
					if(rs.next()) {
						finEntity = checkNull(rs.getString("fin_entity"));
					}
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default finEntity:: "+finEntity);

					rs.close();
					psFinEntity.close();
					
					// Now, use finEntity to fetch VAR_VALUE from finparm
					String varValueQuery = "select VAR_VALUE from finparm where ADDL_VALUE = ?";
					PreparedStatement psVarValue = con.prepareStatement(varValueQuery);
					psVarValue.setString(1, finEntity);
					ResultSet rsVarValue = psVarValue.executeQuery();
					String varValue = null;
					if (rsVarValue.next()) {
					    varValue = checkNull(rsVarValue.getString("VAR_VALUE"));
					}
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default varValue:: " + varValue);

					// Clean up the result set and prepared statement for the varValue query
					rsVarValue.close();
					psVarValue.close();

					// Finally, use varValue to fetch the rate from pricelist
					String rateQuery = "select rate from pricelist where price_list = ?";
					PreparedStatement psRate = con.prepareStatement(rateQuery);
					psRate.setString(1, varValue);
					ResultSet rsRate = psRate.executeQuery();
					int MngmntAprvRate = 0;
					if (rsRate.next()) {
						MngmntAprvRate = rsRate.getInt("rate");
					}
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default rate:: " + rate);

					// Clean up the result set and prepared statement for the rate query
					rsRate.close();
					psRate.close();
					
					
					String priceSql =
					        "SELECT fp.VAR_NAME, pl.rate " +
					        "FROM finparm fp " +
					        "JOIN site s ON s.fin_entity = fp.ADDL_VALUE " +
					        "JOIN pricelist pl ON pl.price_list = fp.VAR_VALUE " +
					        "WHERE s.site_code = ? " +
					        "AND fp.VAR_NAME IN ('RFQ_PTS','RFQ_PTD')";


					PreparedStatement psPrice = con.prepareStatement(priceSql);
					psPrice.setString(1, siteCode);

					ResultSet rsPrice = psPrice.executeQuery();

					BigDecimal pts = null;
					BigDecimal ptd = null;
					BigDecimal PriceRate = null;
					while (rsPrice.next()) {
						
					    String varName = checkNull(rsPrice.getString("VAR_NAME"));
					     PriceRate = rsPrice.getBigDecimal("rate");

					    if ("RFQ_PTS".equals(varName)) {
					        pts = PriceRate;
					    } else if ("RFQ_PTD".equals(varName)) {
					        ptd = PriceRate;
					    }
					}

					
					//PTR calculation start
				    String siteCustomerQuery = 
					        "SELECT PRICE_LIST FROM SITE_CUSTOMER " +
					        "WHERE SITE_CODE = ? AND CUST_CODE = ?";

					    psSiteCustomer = con.prepareStatement(siteCustomerQuery);
					    psSiteCustomer.setString(1, siteCode);
					    psSiteCustomer.setString(2, custCode);

					    rs = psSiteCustomer.executeQuery();

					    if (rs.next()) {
					        priceList = rs.getString("PRICE_LIST");
					    }

					    rs.close();
					    psSiteCustomer.close();

					    // Step 2: If not found in SITE_CUSTOMER, fetch from CUSTOMER
					    if (priceList == null || priceList.trim().isEmpty()) {

					        String customerQuery =
					            "SELECT PRICE_LIST FROM CUSTOMER WHERE CUST_CODE = ?";

					        psCustomer = con.prepareStatement(customerQuery);
					        psCustomer.setString(1, custCode);

					        rs = psCustomer.executeQuery();

					        if (rs.next()) {
					            priceList = rs.getString("PRICE_LIST");
					        }

					        rs.close();
					        psCustomer.close();
					    }

					    // Step 3: Fetch RATE from PRICELIST table
					    if (priceList != null && !priceList.trim().isEmpty()) {

					        String priceListQuery =
					            "SELECT RATE FROM PRICELIST WHERE PRICE_LIST = ?";

					        psPriceList = con.prepareStatement(priceListQuery);
					        psPriceList.setString(1, priceList);

					        rs = psPriceList.executeQuery();

					        if (rs.next()) {
					            rate = rs.getInt("RATE");
					        }

					        rs.close();
					        psPriceList.close();
					    }

					//PTR calculation end
					
					valueXmlString.append("<rate_apprv>").append("<![CDATA["+MngmntAprvRate+"]]>").append("</rate_apprv>\r\n");
					valueXmlString.append("<ptd>").append("<![CDATA["+ptd+"]]>").append("</ptd>\r\n");
					valueXmlString.append("<pts>").append("<![CDATA["+pts+"]]>").append("</pts>\r\n");
					valueXmlString.append("<ptr>").append("<![CDATA["+rate+"]]>").append("</ptr>\r\n");

					//Management rate block[End]
				}
				if ("item_code".equalsIgnoreCase(currentColumn.trim())) {
					String itemDescr = "";
					BaseLogger.log("3", null, null, "ReqForQuotationIC in item_code ");
					String itemCode = checkNull(genericUtility.getColumnValue("item_code", dom));
					String itemDescrSql = "select descr from item where item_code = ?";
				    PreparedStatement itemDescrPs = con.prepareStatement(itemDescrSql);
				    itemDescrPs.setString(1, itemCode);
				    ResultSet itemDescrRs = itemDescrPs.executeQuery();
				    while(itemDescrRs.next()) {
				    	itemDescr = itemDescrRs.getString("descr");
				    }
					valueXmlString.append("<descr>").append("<![CDATA["+itemDescr+"]]>").append("</descr>\r\n");

				}
				
				if ("ptr_flag".equalsIgnoreCase(currentColumn.trim())) {
					BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flag ");
					String custCode = checkNull(genericUtility.getColumnValue("cust_code", dom1));
					 String rateStr = checkNull(genericUtility.getColumnValue("ptr", dom));	

					BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flat condition:: "+ptrFlag);
					BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flat condition siteCode:: "+siteCode);
					BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flat condition custCode:: "+custCode);
					BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flat condition ptr:: "+rateStr);

					if(ptrFlag.equalsIgnoreCase("Y")) {
											
						BaseLogger.log("3", getUserInfo(), null, "Final RATE : " + rate);
						valueXmlString.append("<rate_quot protect='1'>").append("<![CDATA["+rateStr+"]]>").append("</rate_quot>\r\n");

						
					}else if(ptrFlag.equalsIgnoreCase("N")) {
						valueXmlString.append("<rate_quot protect='0'>").append("<![CDATA[]]>").append("</rate_quot>\r\n");
					}
				}
				if ("rate_quot".equalsIgnoreCase(currentColumn.trim())) {
					BaseLogger.log("3", null, null, "ReqForQuotationIC in rate_quot ::");
					String rateQuot = checkNull(genericUtility.getColumnValue("rate_quot", dom));
					String itemCode = checkNull(genericUtility.getColumnValue("item_code", dom));
					String rateApprv = checkNull(genericUtility.getColumnValue("rate_apprv", dom));
					String ratePtr = checkNull(genericUtility.getColumnValue("ptr", dom));

					BaseLogger.log("3", null, null, "ReqForQuotationIC in rate_quot:: "+rateQuot+" rateApprv::"+rateApprv+ " ratePtr::"+ratePtr+" itemCode::"+itemCode);
					

					if (!rateQuot.isEmpty() && !rateApprv.isEmpty()) {
					    BigDecimal rateApprvVal = new BigDecimal(rateApprv);
					    BigDecimal rateQuotVal = new BigDecimal(rateQuot);
					    BigDecimal ratePtrVal = new BigDecimal(ratePtr);

						BaseLogger.log("3", null, null, "ReqForQuotationIC after conversion rateQuotVal:: "+rateQuotVal+" rateApprvVal::"+rateApprvVal+ " ratePtrVal::"+ratePtrVal);

					    
					    
					    
					    
					    if (rateApprvVal.compareTo(rateQuotVal) > 0) {
					        BaseLogger.log("3", null, null, "in rateApprvVal greater condition");
					        BaseLogger.log("3", null, null, "in rateApprvVal greater condition valueXmlString::"+ valueXmlString);

					        String detail1Xml = "<Detail1><mgmnt_apprv><![CDATA[Y]]></mgmnt_apprv><wf_status><![CDATA[P]]></wf_status></Detail1>";

					        int pos = valueXmlString.indexOf("</header>");

					        if (pos != -1) {
					            pos += "</header>".length();   // move after </header>
					            valueXmlString.insert(pos, detail1Xml);
					        }

					        BaseLogger.log("3", null, null, "in rateApprvVal greater condition updatedXml ::"+valueXmlString);

					        
					    }
					    if (rateQuotVal.compareTo(rateApprvVal) > 0) {
					        BaseLogger.log("3", null, null, "in rateQuotVal greater condition");
					        BaseLogger.log("3", null, null, "in rateQuotVal greater condition valueXmlString::"+ valueXmlString);

					        String detail1Xml = "<Detail1><mgmnt_apprv><![CDATA[]]></mgmnt_apprv><wf_status><![CDATA[]]></wf_status></Detail1>";

					        int pos = valueXmlString.indexOf("</header>");

					        if (pos != -1) {
					            pos += "</header>".length();   // move after </header>
					            valueXmlString.insert(pos, detail1Xml);
					        }

					        BaseLogger.log("3", null, null, "in rateApprvVal greater condition updatedXml ::"+valueXmlString);

					        
					    }
					    
					    
					   
					}
					


					 //Calculating Revised PTR,PTD and PTS [Start]
						
						/*
						 * String resvisedRateSql =
						 * "select PHY_ATTRIB_13,PHY_ATTRIB_14,PHY_ATTRIB_15 from item where item_code = ?"
						 * ; PreparedStatement resvisedRatePstmt =
						 * conn.prepareStatement(resvisedRateSql); resvisedRatePstmt.setString(1,
						 * itemCode); ResultSet resvisedRateRs = resvisedRatePstmt.executeQuery(); while
						 * (resvisedRateRs.next()) { String distMarginStr =
						 * checkNull(resvisedRateRs.getString("PHY_ATTRIB_13")); String stockMarginStr =
						 * checkNull(resvisedRateRs.getString("PHY_ATTRIB_14")); String retailMarginStr
						 * = checkNull(resvisedRateRs.getString("PHY_ATTRIB_15"));
						 * 
						 * int distMargin = 0; int stockMargin = 0; int retailMargin = 0;
						 * 
						 * try { distMargin = (distMarginStr != null && distMarginStr.trim().length() >
						 * 0) ? Integer.parseInt(distMarginStr.trim()) : 0;
						 * 
						 * stockMargin = (stockMarginStr != null && stockMarginStr.trim().length() > 0)
						 * ? Integer.parseInt(stockMarginStr.trim()) : 0;
						 * 
						 * retailMargin = (retailMarginStr != null && retailMarginStr.trim().length() >
						 * 0) ? Integer.parseInt(retailMarginStr.trim()) : 0;
						 * 
						 * } catch (Exception e) { BaseLogger.log("3", null, null,
						 * "Error parsing margin values"); } BigDecimal rateBD = new
						 * BigDecimal(rateQuot);
						 * 
						 * BigDecimal hundred = new BigDecimal(100);
						 * 
						 * BigDecimal retailMarginBD = new BigDecimal(retailMargin); BigDecimal
						 * stockMarginBD = new BigDecimal(stockMargin); BigDecimal distMarginBD = new
						 * BigDecimal(distMargin);
						 * 
						 * BaseLogger.log("3", null, null, "distMargin::" + distMargin +
						 * " stockMargin::" + stockMargin + " revisedPtd:: " + retailMargin + "rate:: "
						 * + rate + "]");
						 * 
						 * BigDecimal revisedPtr =
						 * rateBD.divide(hundred.multiply(hundred.subtract(retailMarginBD)), 6,
						 * RoundingMode.HALF_UP);
						 * 
						 * BigDecimal revisedPts =
						 * rateBD.divide(hundred.multiply(hundred.subtract(stockMarginBD)), 6,
						 * RoundingMode.HALF_UP);
						 * 
						 * BigDecimal revisedPtd =
						 * rateBD.divide(hundred.multiply(hundred.subtract(distMarginBD)), 6,
						 * RoundingMode.HALF_UP);
						 * 
						 * BaseLogger.log("3", null, null, "revisedPtr::" + revisedPtr + " revisedPts::"
						 * + revisedPts + " revisedPtd::" + revisedPtd); BaseLogger.log("3", null, null,
						 * "revisedPtr::" + revisedPtr + " revisedPts::" + revisedPts + " revisedPtd:: "
						 * + revisedPtd + "]");
						 * valueXmlString.append("<revised_ptr>").append("<![CDATA[" + revisedPtr +
						 * "]]>") .append("</revised_ptr>\r\n");
						 * valueXmlString.append("<revised_pts>").append("<![CDATA[" + revisedPts +
						 * "]]>") .append("</revised_pts>\r\n");
						 * valueXmlString.append("<revised_ptd>").append("<![CDATA[" + revisedPtd +
						 * "]]>") .append("</revised_ptd>\r\n");
						 * 
						 * }
						 */
				  //Calculating Revised PTR,PTD and PTS [End]
					
				}
				valueXmlString.append("</Detail2>\r\n");
				break;
			}
			}
	        BaseLogger.log("3", null, null, "in rateApprvVal greater condition reStr>>>>> "+reStr);
			valueXmlString.append("</Root>\r\n");
		} catch (Exception e) {
			BaseLogger.log("3", getUserInfo(), null, "Exception :ReqForQuotationIC :itemChanged(Document,String):" + e.getMessage() + ":");

			e.printStackTrace();
		} finally {
			closeResources(rs, psSiteCustomer, conn);
			closeResources(rs, psCustomer, conn);
			closeResources(rs, psPriceList, conn);

		}
		BaseLogger.log("3", getUserInfo(), null, "ReqForQuotationIC valueXmlString::"+valueXmlString.toString());
		return valueXmlString.toString();
	}
	
	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 = "";
		} else {
			input = input.trim();
		}
		return input;
	}
	private static void setNodeValue( Document dom, String nodeName, String nodeVal ) throws Exception
	   {
	       Node tempNode = dom.getElementsByTagName( nodeName ).item(0);

	       if( tempNode != null )
	       {
	           if( tempNode.getFirstChild() == null )
	           {
	               CDATASection cDataSection = dom.createCDATASection( nodeVal );
	               tempNode.appendChild( cDataSection );
	           }
	           else
	           {
	               tempNode.getFirstChild().setNodeValue(nodeVal);
	           }
	       }
	       tempNode = null;
	   }
	public static boolean isDateInvalid(String validUptoStr)
	{
	    try
	    {
	        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yy");

	        LocalDate validDate = LocalDate.parse(validUptoStr, formatter);
	        LocalDate currentDate = LocalDate.now();

	        if(validDate.isBefore(currentDate))
	        {
	            return true;
	        }
	    }
	    catch(Exception e)
	    {
	        BaseLogger.log("3", null, null, "Exception in date validation [" + e + "]");
	    }

	    return false;
	}
}
