package ibase.webitm.ejb.dis;

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

import javax.naming.InitialContext;

import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.utility.ITMException;

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

		try {
			userInfo = getUserInfo();

			BaseLogger.log("3", getUserInfo(), null, "SalesQuotationAcknowledge --> tranID [" + tranID + "]");

			conn = getConnection();

			// 🔹 Update status
			String updateStatusSql = "update sales_quot set status = 'A' where QUOT_NO = ?";
			PreparedStatement updateStatusPs = conn.prepareStatement(updateStatusSql);
			updateStatusPs.setString(1, tranID);
			int updateStatusCnt = updateStatusPs.executeUpdate();

			// 🔹 Fetch header data
			String fetchSQuotDetSql = "select quot_type, cust_code from sales_quot where quot_no = ?";
			PreparedStatement fetchSQuotDetPs = conn.prepareStatement(fetchSQuotDetSql);
			fetchSQuotDetPs.setString(1, tranID);
			ResultSet fetchSQuotDetRs = fetchSQuotDetPs.executeQuery();

			while (fetchSQuotDetRs.next()) {
				quotType = checkNull(fetchSQuotDetRs.getString("quot_type"));
				custCode = checkNull(fetchSQuotDetRs.getString("cust_code"));
			}
			if (quotType.trim().equalsIgnoreCase("G")) {

			    String fetchHospitalMappingSql = "select CUST_CODE__STK, CUST_CODE__DIST from CUSTOMER_PREF_DIST where CUST_CODE = ?";
			    PreparedStatement fetchHospitalMappingPs = conn.prepareStatement(fetchHospitalMappingSql);
			    fetchHospitalMappingPs.setString(1, custCode);
			    fetchHospitalMappingRs = fetchHospitalMappingPs.executeQuery();

			    // Get max line_no
			    String lineSql = "SELECT NVL(MAX(line_no), 0) FROM sales_quot_stockist WHERE quot_no = ?";
			    PreparedStatement linePs = conn.prepareStatement(lineSql);
			    linePs.setString(1, tranID);
			    ResultSet lineRs = linePs.executeQuery();

			    if (lineRs.next()) {
			        lineNo = lineRs.getInt(1);
			    }

			    String insertSql = "INSERT INTO sales_quot_stockist (line_no, cust_code, cust_code__stk, cust_code__dist, quot_no) VALUES (?, ?, ?, ?, ?)";
			    insertPs = conn.prepareStatement(insertSql);

			    while (fetchHospitalMappingRs.next()) {

			        lineNo++;

			        String custCodeStk = fetchHospitalMappingRs.getString("CUST_CODE__STK");
			        String custCodeDist = fetchHospitalMappingRs.getString("CUST_CODE__DIST");

			        insertPs.setInt(1, lineNo);
			        insertPs.setString(2, custCode);
			        insertPs.setString(3, custCodeStk);
			        insertPs.setString(4, custCodeDist);
			        insertPs.setString(5, tranID);

			        insertPs.addBatch();
			    }

			    insertPs.executeBatch();

			    // close extra resources
			    if (lineRs != null) lineRs.close();
			    if (linePs != null) linePs.close();
			    if (fetchHospitalMappingPs != null) fetchHospitalMappingPs.close();
			}

		
			if (updateStatusCnt > 0) {
				conn.commit();
				return itmDBAccessEJB.getErrorString("", "SALESACK", "", "", conn);
			}


			if (fetchSQuotDetPs != null) {
				fetchSQuotDetPs.close();
				fetchSQuotDetPs = null;
			}
			if (fetchSQuotDetRs != null) {
				fetchSQuotDetRs.close();
				fetchSQuotDetRs = null;
			}

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

		return " ";
	}

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