/**
 * 
 */
package ibase.webitm.ejb.afsal;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.HashMap;

import javax.ejb.Stateless;
import javax.naming.InitialContext;

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

import ibase.system.config.AppConnectParm;
import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.utility.EMail;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.ejb.dis.DistStkUpdLocal;
import ibase.webitm.ejb.dis.InvAllocTraceBean;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

/**
 * @author base
 *
 */
@Stateless
public class SerReqFeedbksSave extends ValidatorEJB implements SerReqFeedbksSaveLocal, SerReqFeedbksSaveRemote
{
	public String preSaveRec(String xmlString,String domID,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		String errString = "";
		System.out.println("SerReqFeedbksSave : preSaveRec called");
		E12GenericUtility genericUtility = new  E12GenericUtility();
		try
		{
			Document dom = null;
			System.out.println( "xmlString - ["+ xmlString +"]" );
			if ( xmlString != null && xmlString.trim().length() > 0 )
			{
				dom = genericUtility.parseString( xmlString );
				errString = executePreSaveRec( dom, domID, objContext, editFlag, xtraParams, conn );
			}			
		}
	   	catch(Exception e)
		{
			System.out.println("Exception : SerReqFeedbksSave : preSaveRec() : [" + e.getMessage() + "]");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;
	}
	
	private String executePreSaveRec(Document dom, String domID,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		HashMap hashMap = new HashMap(); 
		String errString = "";
		String lineNo = "";
		String tranSer = "S-FBK";
		String line = "";
		String siteCode = "", itemCode = "", quantity = "", locCode = "", lotNo = "", lotSl = "";
		double allocQty = 0d;
		//DistStkUpdLocal distStkUpd = null; 
		String updateStatus = "",tranId = "";
		PreparedStatement pstmt = null , pstmtUpd= null;
		NodeList hdrDom = null;
		Node currDetail = null;
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "";
		try
		{	
			stmt = conn.createStatement();
			//distStkUpd = getComponent("DistStkUpd");		
			E12GenericUtility genericUtility = new  E12GenericUtility();	
			hdrDom = dom.getElementsByTagName( "Detail1" );
			siteCode = genericUtility.getColumnValueFromNode( "site_code", hdrDom.item(0) );
			tranId = genericUtility.getColumnValueFromNode( "feedbk_id", hdrDom.item(0) );

			System.out.println( "tran_id : ["+ tranId +"]" );
			System.out.println( "site_code : ["+ siteCode +"]" );
			
			siteCode = genericUtility.checkNull( siteCode );
			System.out.println( "after site_code : ["+ siteCode +"]" );
			
			System.out.println( "domID : ["+ domID +"]" );
			currDetail = getCurrentDetailFromDom( dom, domID );		
			updateStatus = getCurrentUpdateFlag( currDetail );
			System.out.println( "updateStatus : ["+ updateStatus +"]" );
			
			//added by Satish 02-JUN-23
			String title = "", objBrowName= "";
			sql = "select  title , obj_brow_name from obj_forms where win_name= 'w_ser_req_feedbks' and form_no = 2";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				title = rs.getString("title");
				objBrowName = rs.getString("obj_brow_name");
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;
			
			if(title != null && !title.equals("Feedback Detail"))
			{

				//	if ( currDetail != null && ! updateStatus.equalsIgnoreCase("A"))
				if ( currDetail != null && ! updateStatus.equalsIgnoreCase("A") && ! updateStatus.equalsIgnoreCase("N") ) //Changed By PriyankaC on 28MAY2018..
				{
					itemCode	= genericUtility.getColumnValueFromNode( "item_code", currDetail );
					locCode		= genericUtility.getColumnValueFromNode( "loc_code", currDetail );
					lotNo		= genericUtility.getColumnValueFromNode( "lot_no", currDetail );
					lotSl		= genericUtility.getColumnValueFromNode( "lot_sl", currDetail );
					quantity	= genericUtility.getColumnValueFromNode( "quantity", currDetail );
					lineNo		= genericUtility.getColumnValueFromNode( "line_no", currDetail );
					
					if ( updateStatus.equalsIgnoreCase("E") || updateStatus.equalsIgnoreCase("D") )
					{
						sql = " SELECT ITEM_CODE, LOC_CODE, LOT_NO, LOT_SL, QUANTITY "
								+ " FROM SER_REQ_FEEDBK_ITEM "
								+ " WHERE FEEDBK_ID = '"+tranId+"' AND LINE_NO = '"+lineNo+"' ";
						rs = stmt.executeQuery(sql);
						if (rs.next())
						{
							itemCode	= rs.getString("ITEM_CODE");
							locCode		= rs.getString("LOC_CODE");
							lotNo		= rs.getString("LOT_NO");
							lotSl		= rs.getString("LOT_SL");
							quantity	= rs.getString("QUANTITY");
						}
					}
					System.out.println("lineNo :"+lineNo+" itemCode :"+itemCode+" locCode :"+locCode+" lotNo :"+lotNo+" lotSl :"+lotSl+" quantity :"+quantity);
					allocQty = -1 * Double.parseDouble(quantity);
					
					System.out.println("lineNo: "+lineNo);
					line = "   " + lineNo;
					hashMap.put("tran_date", new java.sql.Date(System.currentTimeMillis()));
					hashMap.put("ref_ser",tranSer);
					hashMap.put("ref_id", tranId);
					hashMap.put("ref_line", line.substring(line.length()-3));
					hashMap.put("item_code", itemCode);
					hashMap.put("site_code", siteCode);
					hashMap.put("loc_code",locCode);
					hashMap.put("lot_no",lotNo);
					hashMap.put("lot_sl",lotSl);
					hashMap.put("alloc_qty", new Double(allocQty));
					hashMap.put("chg_win","W_SER_REQ_FEEDBKS");
					hashMap.put("chg_user", genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode"));
					hashMap.put("chg_term", genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId"));
	
					System.out.println( "Calling InvAllocTraceBean....." );
					//Changed by Prasad on 26/04/18 [changes in calling component of stockAllocation] START
					/*if ( distStkUpd.updAllocTrace( hashMap, conn ) > 0 )
					{
						System.out.println("distStkUpd.UpdAllocTrace(HashMap, Connection) : Successful!");
					}*/
					InvAllocTraceBean invBean = new InvAllocTraceBean();
	                errString = invBean.updateInvallocTrace( hashMap, conn );
	                if ( errString == null || errString.trim().length() == 0 )
					{
						System.out.println( "invAllocTrace.updateInvallocTrace : Successful!" );
					}
					else
					{
						ITMDBAccessEJB itmDBAccess = new ITMDBAccessEJB();
						errString = itmDBAccess.getErrorString( "", errString, "", "", conn );
					}
	                //Changed by Prasad on 26/04/18 [changes in calling component of stockAllocation] START
				}	
		   }//end of title-----------
		}
		catch(SQLException e)
		{
			System.out.println( "Exception : SerReqFeedbksSave : actionStock : ["+ e.getMessage() +"]" );
			throw new ITMException(e);
		}
		catch(Exception e)
		{
			System.out.println( "Exception : SerReqFeedbksSave : actionHandler :"+ e.getMessage() +"]" );
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (stmt !=null)
				{
					stmt.close();
				}
				if (rs != null)
				{
					rs.close();
				}
			}catch(Exception e){}	 
		}
		return errString;
	}
	
	public String postSaveRec( String xmlString,String domId,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		String errString = "";
		System.out.println("SerReqFeedbksSave : postSaveRec called");
		E12GenericUtility genericUtility = new E12GenericUtility();
		try
		{
			Document dom = null;
			System.out.println( "xmlString - ["+ xmlString +"]" );
			if ( xmlString != null && xmlString.trim().length() > 0 )
			{
				dom = genericUtility.parseString( xmlString );
				errString = executePostSaveRec(dom,domId,objContext,editFlag,xtraParams,conn);
			}			
		}
	   	catch(Exception e)
		{
			System.out.println( "Exception : SerReqFeedbksSave :: [" + e.getMessage() + "]" );
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;
	}
	
	private String executePostSaveRec(Document dom, String domID,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		HashMap hashMap = new HashMap();
		String errString = "";
		String lineNo = "";
		String tranSer = "S_FBK";
		String clientEmailId="", custName="", mailSubject="",mailBody="";
		String line = "", custCode="",userId="";
		String siteCode = "", itemCode = "", quantity = "", locCode = "", lotNo = "", lotSl = "";
		//DistStkUpdLocal distStkUpd = null;
		NodeList hdrDom = null , detDom= null;
		Node currDetail = null;
		String updateStatus = "",tranId = "", sql ="", actionStatus = "", ticketStatus= "",remarks = "", executeDT = "", ReqId= "";
		PreparedStatement pstmt = null , pstmtUpd= null;
		ResultSet rs = null;
		java.sql.Timestamp tranDate = null , resolveDate= null;
		int updCnt = 0;
		try
		{		
			//distStkUpd = getComponent("DistStkUpd");
			E12GenericUtility genericUtility = new  E12GenericUtility();
			hdrDom = dom.getElementsByTagName( "Detail1" );
			detDom = dom.getElementsByTagName( "Detail2" );
			siteCode = genericUtility.getColumnValueFromNode( "site_code", hdrDom.item(0) );
			tranId = genericUtility.getColumnValueFromNode( "feedbk_id", hdrDom.item(0) );
			executeDT = genericUtility.getColumnValueFromNode( "execut_dt", hdrDom.item(0) );
			System.out.println( "tran_id : ["+ tranId +"]" );
			System.out.println( "site_code : ["+ siteCode +"]" );
			
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			actionStatus = checkNull(genericUtility.getColumnValueFromNode( "action_status", detDom.item(0) ));
			remarks  = checkNull(genericUtility.getColumnValueFromNode( "action_detls", detDom.item(0)) );
			tranDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateString(executeDT, genericUtility.getApplDateFormat(),
					genericUtility.getDBDateFormat())+ " 00:00:00.0");
			System.out.println( "Execute Date: ["+ tranDate +"]" );
			System.out.println( "after action status : ["+ actionStatus +"]" );
			ReqId = genericUtility.getColumnValueFromNode( "req_id", hdrDom.item(0) );
			
			siteCode = genericUtility.checkNull( siteCode );
			System.out.println( "after site_code : ["+ siteCode +"]" );
			
			System.out.println( "domID : ["+ domID +"]" );
			currDetail = getCurrentDetailFromDom( dom, domID );
			updateStatus = getCurrentUpdateFlag( currDetail );
			System.out.println( "updateStatus : ["+ updateStatus +"]" );
			
			//added by Satish 02-JUN-23  condition will no work for Feedback Detail for Service Feedback
			String title = "", objBrowName= "";
			sql = "select  title , obj_brow_name from obj_forms where win_name= 'w_ser_req_feedbks' and form_no = 2";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				title = checkNull(rs.getString("title"));
				objBrowName = rs.getString("obj_brow_name");
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;
			
			if(title != null && !title.equals("Feedback Detail"))
			{
			
				if ( currDetail != null && !updateStatus.equalsIgnoreCase("D") )
				{
					itemCode = genericUtility.getColumnValueFromNode( "item_code", currDetail );
					locCode = genericUtility.getColumnValueFromNode( "loc_code", currDetail );
					lotNo = genericUtility.getColumnValueFromNode( "lot_no", currDetail );
					lotSl = genericUtility.getColumnValueFromNode( "lot_sl", currDetail );
					quantity = genericUtility.getColumnValueFromNode( "quantity", currDetail );
					lineNo = genericUtility.getColumnValueFromNode( "line_no", currDetail );
					System.out.println("lineNo: "+lineNo);
	
					line = "   "+lineNo.trim();
					hashMap.put("tran_date", new java.sql.Date(System.currentTimeMillis()));			
					hashMap.put("ref_ser",tranSer);
					hashMap.put("ref_id", tranId);
					hashMap.put("ref_line", line.substring(line.length()-3));
					hashMap.put("item_code", itemCode);
					hashMap.put("site_code", siteCode);
					hashMap.put("loc_code",locCode);
					hashMap.put("lot_no",lotNo);
					hashMap.put("lot_sl",lotSl);
					hashMap.put("alloc_qty", new Double(quantity.trim().length() == 0? "0" :quantity));
					hashMap.put("chg_win","W_SER_REQ_FEEDBKS");
					hashMap.put("chg_user", genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode"));
					hashMap.put("chg_term", genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId"));
					System.out.println("Calling InvAllocTraceBean.....");
					//Changed by Prasad on 26/04/18 [changes in calling component of stockAllocation] START
					/*if ( distStkUpd.updAllocTrace( hashMap, conn ) > 0 )
					{
						System.out.println("distStkUpd.UpdAllocTrace(HashMap, Connection) : Sucessuful!");
					}*/
					InvAllocTraceBean invBean = new InvAllocTraceBean();
	                errString = invBean.updateInvallocTrace( hashMap, conn );
	                if ( errString == null || errString.trim().length() == 0 )
					{
						System.out.println( "invAllocTrace.updateInvallocTrace : Successful!" );
					}
					else
					{
						ITMDBAccessEJB itmDBAccess = new ITMDBAccessEJB();
						errString = itmDBAccess.getErrorString( "", errString, "", "", conn );
					}
	              //Changed by Prasad on 26/04/18 [changes in calling component of stockAllocation] END
				}
			}//end of title-------------------
			
			//added by Satish 04-JUL-23 Update Status and details in Service Ticket  
			
			String ticketNo = genericUtility.getColumnValueFromNode( "ticket_no", hdrDom.item(0) );
			if(ticketNo != null && ticketNo.trim().length() > 0)
			{
				if(actionStatus.trim().equals("A"))
				{
					ticketStatus = "E";//Attended
				}
				else if(actionStatus.trim().equals("P"))
				{
					ticketStatus = "W";
				}
				else if(actionStatus.trim().equals("C"))
				{
					ticketStatus = "C";
				}
				else if(actionStatus.trim().equals("W"))
				{
					ticketStatus = "A";
				}
				else
				{
					System.out.println(" : SerReqFeedbksSave : actionStatus  : null");
				}
				String resolveDateStr = "";
				sql = "select resolve_date1 from service_complaint where ticket_no = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, ticketNo);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					resolveDate = rs.getTimestamp("resolve_date1");
					resolveDateStr = rs.getString("resolve_date1");
					BaseLogger.log("3", getUserInfo(), null,"Resolution Date :" + resolveDate);
					BaseLogger.log("3", getUserInfo(), null,"Resolution Date String:" + resolveDateStr);
				}
				rs.close();rs = null;
				pstmt.close();pstmt = null;
				BaseLogger.log("3", getUserInfo(), null,"Resolution Date :" + resolveDate);
				//if execute date is less then resolve date 
				if(resolveDate != null)
				{
					BaseLogger.log("3", getUserInfo(), null,"ticketStatus ---------- :" + ticketStatus);
					if(resolveDate.compareTo(tranDate) <= 0)
					{
						  sql = "UPDATE SERVICE_COMPLAINT SET STATUS = ? , RESOLVE_DATE1 = ?, RES_DATE1_DESC = ?  WHERE TICKET_NO = ? ";
						  pstmtUpd = conn.prepareStatement(sql);
						  pstmtUpd.setString(1, ticketStatus);
				          pstmtUpd.setTimestamp(2,tranDate);//executeDate   
				          pstmtUpd.setString(3, remarks.trim());
						  pstmtUpd.setString(4, ticketNo);
						  updCnt = pstmtUpd.executeUpdate();
						  BaseLogger.log("3", getUserInfo(), null,"update if close Feedbacks:" + updCnt);
						  pstmtUpd.close();pstmtUpd = null;
						  
						  if(actionStatus.trim().equals("W"))
						  {							  
							  if ( updCnt > 0 )
							  {	
								  errString = sendMailOnAwaiting(ticketNo, userId, conn);
							  }
						  }
						  //if feedback is close , then close service request
						  if(actionStatus.trim().equals("C"))
						  {
							  sql = "UPDATE SER_REQUEST SET COMP_STAT = 'C' ,COMP_STAT_DT = ?   WHERE REQ_ID = ? ";
							  pstmtUpd = conn.prepareStatement(sql);
							  pstmtUpd.setTimestamp(1,tranDate);//executeDate 
							  pstmtUpd.setString(2, ReqId);
							  updCnt = pstmtUpd.executeUpdate();
							  BaseLogger.log("3", getUserInfo(), null,"update if close Feedbacks:" + updCnt);
							  pstmtUpd.close();pstmtUpd = null;
							  
							  if ( updCnt > 0 )
							  {	
								  errString = sendMailOnClose(ticketNo, userId, conn);
							  }
						  }
					}
					
				 
				}
				else
				{
					 sql = "UPDATE SERVICE_COMPLAINT SET STATUS = ? ,RESOLVE_DATE1 = ?,RES_DATE1_DESC = ?  WHERE TICKET_NO = ? ";
					  pstmtUpd = conn.prepareStatement(sql);
					  pstmtUpd.setString(1, ticketStatus);
			          pstmtUpd.setTimestamp(2,tranDate);//executeDate   
			          pstmtUpd.setString(3, remarks.trim());
					  pstmtUpd.setString(4, ticketNo);
					  updCnt = pstmtUpd.executeUpdate();
					  
					  if(actionStatus.trim().equals("W"))
					  {							  
						  if ( updCnt > 0 )
						  {	
							  errString = sendMailOnAwaiting(ticketNo, userId, conn);
						  }
					  }
					  
					  BaseLogger.log("3", getUserInfo(), null,"update else successful Feedbacks:" + updCnt);
					  if(actionStatus.trim().equals("C"))
					  {
						  sql = "UPDATE SER_REQUEST SET COMP_STAT = 'C'  ,COMP_STAT_DT = ?   WHERE REQ_ID = ? ";
						  pstmtUpd = conn.prepareStatement(sql);
						  pstmtUpd.setTimestamp(1,tranDate);//executeDate 
						  pstmtUpd.setString(2, ReqId);
						  updCnt = pstmtUpd.executeUpdate();
						  BaseLogger.log("3", getUserInfo(), null,"update if close Feedbacks:" + updCnt);
						  pstmtUpd.close();pstmtUpd = null;
						  if ( updCnt > 0 )
						  {	
							  errString = sendMailOnClose(ticketNo, userId, conn);
						  }
					  }
				}
			}//end ticket
			
			
			//Added by Ajit D. on 04-April-2025 Condtion if request ID value is not null and actionStatus value is "C" call the  sendMailOnReqClose method[Start]
			
			if(ReqId != null && ReqId.trim().length() > 0 && ticketNo == null && checkNull(ticketNo).trim().length() <= 0)
			{
				 BaseLogger.log("3", getUserInfo(), null,"If request Id  condition::");
				if(actionStatus.trim().equals("C"))
				{
					ticketStatus = "C";
				}
				else
				{
					System.out.println(" : SerReqFeedbksSave : actionStatus  : null");
				}
				if(actionStatus.trim().equals("C"))
				  {
					  sql = "UPDATE SER_REQUEST SET COMP_STAT = 'C' ,COMP_STAT_DT = ?   WHERE REQ_ID = ? ";
					  pstmtUpd = conn.prepareStatement(sql);
					  pstmtUpd.setTimestamp(1,tranDate);//executeDate 
					  pstmtUpd.setString(2, ReqId);
					  updCnt = pstmtUpd.executeUpdate();
					  BaseLogger.log("3", getUserInfo(), null,"update if close Feedbacks:" + updCnt);
					  pstmtUpd.close();pstmtUpd = null;
					  
					  if ( updCnt > 0 )
					  {	
						  errString = sendMailOnReqClose(ReqId, userId, conn);
					  }
				  }
			}
			//Added by Ajit D. on 04-April-2025 Condtion if request ID value is not null and actionStatus value is "C" call the  sendMailOnReqClose method[End]

			
		}
		catch(SQLException e)
		{
			System.out.println("Exception : SerReqFeedbksSave : actionStock  : ["+ e.getMessage() +"]");
			throw new ITMException(e);
		}
		catch(Exception e)
		{
			System.out.println("Exception : SerReqFeedbksSave : actionHandler : ["+ e.getMessage() +"]" );
			throw new ITMException(e);
		}
		return errString;
	}

	private String sendMailOnClose(String ticketNo, String userId, Connection conn) throws ITMException
	{
		String clientEmailId="", custName="", mailSubject="",mailBody="",mailToClient="";
		PreparedStatement pstmt = null;
		ResultSet rs = null;		
		String sql="",custCode="",errString="",ticketDetail="",changeUser = "";
		java.sql.Timestamp ticketDate=null;    
		
		try
		{
			DBAccessEJB dbAccess = new DBAccessEJB();	
		    ibase.utility.UserInfoBean userInfo = dbAccess.createUserInfo(userId);	
		      
			sql = "select cust_code, ticket_detail, ticket_date,submitted_by from service_complaint where ticket_no= ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, ticketNo);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				custCode = checkNull(rs.getString("cust_code"));
				ticketDetail = checkNull(rs.getString("ticket_detail"));
				ticketDate = rs.getTimestamp("ticket_date");
				changeUser = checkNull(rs.getString("submitted_by"));
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;
			
			sql = "select email_id, contact_pers_name from entity_contact where entity_type = 'C' and entity_code = ?  and role_code='SUPP' and user_id__portal = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, custCode);
			pstmt.setString(2, changeUser);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				clientEmailId = checkNull(rs.getString("email_id"));
				custName = checkNull(rs.getString("contact_pers_name"));
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;													
			
			BaseLogger.log("3", getUserInfo(), null,  "shName::custName:: "+custName);
			  
			if(clientEmailId == null || clientEmailId.trim().length() == 0)
			{	
				ITMDBAccessEJB itmDBAccess = new ITMDBAccessEJB();
				errString = itmDBAccess.getErrorString("","VTCLENTID","");
				return errString;
			}
			GenericUtility genericUtility = GenericUtility.getInstance();
			String applDateFormat = genericUtility.getApplDateFormat();
	        SimpleDateFormat sdf = new SimpleDateFormat(applDateFormat);
			String ticketDateStr = sdf.format(ticketDate);
			
			EMail email = new EMail();
			mailSubject = "Your Ticket "+ticketNo+" has been resolved.";
			
			mailBody = "Dear "+ custName + ","+
					"\n\nWe hope this email finds you well. We are writing to inform you that your ticket with the below issue details has been successfully resolved and closed."+
					"\n\nTicket No :"+ticketNo+
					"\nDate Logged: "+ticketDateStr+
					"\nIssue details: "+ticketDetail+
					"\n\nWe appreciate your patience throughout the process." + 
					"\n\nShould you experience any further difficulties or have any additional questions, please don't hesitate to reach out to our customer support team."+
					"\n\nOnce again, we would like to express our gratitude for choosing our services and for giving us the opportunity to assist you. We value your business and look forward to serving you in the future."+
					"\n\nThank you for your cooperation."+
					"\n\nRegards,"+
					"\nCustomer Support"+
					"\nProteus Technologies Pvt. Ltd.";
					
			mailToClient = 	"<ROOT><MAIL>"+
							"<EMAIL_TYPE>page</EMAIL_TYPE>" +
							"<ENTITY_CODE>BASE</ENTITY_CODE>" +
							"<ENTITY_TYPE>"+"E"+"</ENTITY_TYPE>" +
							"<SUBJECT>"+mailSubject+"</SUBJECT>" +
							"<BODY_TEXT>" + mailBody + "</BODY_TEXT>" +
							"<TO_ADD>"+clientEmailId.trim()+"</TO_ADD>"+
							"<CC_ADD></CC_ADD>" +
							"<ATTACHMENT><BODY></BODY><LOCATION></LOCATION></ATTACHMENT>"+
							"</MAIL></ROOT>";
			
			BaseLogger.log("3", getUserInfo(), null,  "Service Ticket Closed mail to client....::"+mailToClient);
			email.sendMail(mailToClient, "ITM", userInfo);
			BaseLogger.log("3", getUserInfo(), null,  "Service Ticket Closed mail to client...send completed successfully...::");
		}
		catch(Exception e )
		{
			BaseLogger.log("3", getUserInfo(), null,  "Exception in ServiceResolvePostSave::::Mail not send...!");
			e.getMessage();
			e.printStackTrace();				
			throw new ITMException(e);
		}//success messages for ticket has been closed	
		return errString;
	}
	
	//Created by Ajit on 04-APR-25 to send the mail using request Id [Start]
	private String sendMailOnReqClose(String requestId, String userId, Connection conn) throws ITMException
	{
		BaseLogger.log("3", getUserInfo(), null,  "sendMailOnCloseReqId method called");
		String clientEmailId="", custName="", mailSubject="",mailBody="",mailToClient="";
		PreparedStatement pstmt = null;
		ResultSet rs = null;		
		String sql="",custCode="",errString="", reqDetail="",changeUser = "";
		java.sql.Timestamp reqDate=null;    
		
		try
		{
			DBAccessEJB dbAccess = new DBAccessEJB();	
		    ibase.utility.UserInfoBean userInfo = dbAccess.createUserInfo(userId);	
		      
			sql = "select cust_code, DTL_DESCR, COMPLAIN_DATE,chg_user from ser_request where req_id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, requestId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				custCode = checkNull(rs.getString("cust_code"));
				reqDetail = checkNull(rs.getString("DTL_DESCR"));
				reqDate = rs.getTimestamp("COMPLAIN_DATE");
				changeUser = checkNull(rs.getString("chg_user"));
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;
			BaseLogger.log("3", getUserInfo(), null,  "shName::custName:: "+custName);
			BaseLogger.log("3", getUserInfo(), null,  "shName::clientEmailId:: "+clientEmailId);
			
			sql = "select name,email_id from users where code = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, changeUser.trim());
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				custName = checkNull(rs.getString("name"));
				clientEmailId = checkNull(rs.getString("email_id"));
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;													
			
			BaseLogger.log("3", getUserInfo(), null,  "shName::custName:: "+custName);
			BaseLogger.log("3", getUserInfo(), null,  "shName::clientEmailId:: "+clientEmailId);

			if(clientEmailId == null || clientEmailId.trim().length() == 0)
			{	
				ITMDBAccessEJB itmDBAccess = new ITMDBAccessEJB();
				errString = itmDBAccess.getErrorString("","VTCLENTID","");
				return errString;
			}
			GenericUtility genericUtility = GenericUtility.getInstance();
			String applDateFormat = genericUtility.getApplDateFormat();
	        SimpleDateFormat sdf = new SimpleDateFormat(applDateFormat);
			String reqDateStr = sdf.format(reqDate);
			
			EMail email = new EMail();
			mailSubject = "Your Ticket "+requestId+" has been resolved with request ID.";
			
			mailBody = "Dear "+ custName + ","+
					"\n\nWe hope this email finds you well. We are writing to inform you that your ticket with the below issue details has been successfully resolved and closed."+
					"\n\nTicket No :"+requestId+
					"\nDate Logged: "+reqDateStr+
					"\nIssue details: "+reqDetail+
					"\n\nWe appreciate your patience throughout the process." + 
					"\n\nShould you experience any further difficulties or have any additional questions, please don't hesitate to reach out to our customer support team."+
					"\n\nOnce again, we would like to express our gratitude for choosing our services and for giving us the opportunity to assist you. We value your business and look forward to serving you in the future."+
					"\n\nThank you for your cooperation."+
					"\n\nRegards,"+
					"\nCustomer Support";
					
			mailToClient = 	"<ROOT><MAIL>"+
							"<EMAIL_TYPE>page</EMAIL_TYPE>" +
							"<ENTITY_CODE>BASE</ENTITY_CODE>" +
							"<ENTITY_TYPE>"+"E"+"</ENTITY_TYPE>" +
							"<SUBJECT>"+mailSubject+"</SUBJECT>" +
							"<BODY_TEXT>" + mailBody + "</BODY_TEXT>" +
							"<TO_ADD>"+clientEmailId.trim()+"</TO_ADD>"+
							"<CC_ADD></CC_ADD>" +
							"<ATTACHMENT><BODY></BODY><LOCATION></LOCATION></ATTACHMENT>"+
							"</MAIL></ROOT>";
			
			BaseLogger.log("3", getUserInfo(), null,  "Service Ticket Closed mail to client....::"+mailToClient);
			email.sendMail(mailToClient, "ITM", userInfo);
			BaseLogger.log("3", getUserInfo(), null,  "Service Ticket Closed mail to client...send completed successfully...::");
		}
		catch(Exception e )
		{
			BaseLogger.log("3", getUserInfo(), null,  "Exception in sendMailOnCloseWithReqId::::Mail not send...!");
			e.getMessage();
			e.printStackTrace();				
			throw new ITMException(e);
		}//success messages for ticket has been closed	
		return errString;
	}
	//Created by Ajit on 04-APR-25 to send the mail using request Id [Start]

	
	private String sendMailOnAwaiting(String ticketNo, String userId, Connection conn) throws ITMException
	{
		String clientEmailId="", custName="", mailSubject="",mailBody="",mailToClient="";
		PreparedStatement pstmt = null;
		ResultSet rs = null;		
		String sql="",custCode="",errString="",ticketDetail="" , changeUser="";
		java.sql.Timestamp ticketDate=null;    
		try
		{
			DBAccessEJB dbAccess = new DBAccessEJB();	
		    ibase.utility.UserInfoBean userInfo = dbAccess.createUserInfo(userId);	
		      
			sql = "select cust_code, ticket_detail, ticket_date,submitted_by from service_complaint where ticket_no= ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, ticketNo);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				custCode = checkNull(rs.getString("cust_code"));
				ticketDetail = checkNull(rs.getString("ticket_detail"));
				ticketDate = rs.getTimestamp("ticket_date");
				changeUser = checkNull(rs.getString("submitted_by"));
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;
			
			sql = "select email_id, contact_pers_name from entity_contact where entity_type = 'C' and entity_code = ? and role_code='SUPP' and user_id__portal = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, custCode);
			pstmt.setString(2, changeUser);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				clientEmailId = checkNull(rs.getString("email_id"));
				custName = checkNull(rs.getString("contact_pers_name"));
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;													
			
			BaseLogger.log("3", getUserInfo(), null,  "shName::custName:: "+custName);
			  
			if(clientEmailId == null || clientEmailId.trim().length() == 0)
			{	
				ITMDBAccessEJB itmDBAccess = new ITMDBAccessEJB();
				errString = itmDBAccess.getErrorString("","VTCLENTID","");
				return errString;
			}
			GenericUtility genericUtility = GenericUtility.getInstance();
			String applDateFormat = genericUtility.getApplDateFormat();
	        SimpleDateFormat sdf = new SimpleDateFormat(applDateFormat);
			String ticketDateStr = sdf.format(ticketDate);
			
			EMail email = new EMail();
			mailSubject = "Confirmation Required - Resolution for Your Ticket "+ticketNo+"" ;
					
			mailBody = "Dear "+ custName + ","
					+"\n\n\t We hope this email finds you well. We are writing to follow up on the ticket you recently raised with our support team. We are pleased to inform you that we have implemented a resolution to resolve the issue. Details of the ticket are mentioned below -" + 
					"\n\nTicket No :"+ticketNo+
					"\nDate Logged: "+ticketDateStr+
					"\nIssue details: "+ticketDetail+
					"\n\nWe kindly request you to verify the resolution provided and confirm if it meets your requirements. It is essential for us to ensure that the implemented solution aligns with your expectations and resolves the issue at hand effectively.\n" + 
					"\nIf you have any questions, concerns, or require further assistance, please don't hesitate to reach out to our support team. \n" + 
					"\nThank you for your cooperation.\n" + 
					"\nRegards," +
					"\nCustomer Support\n" + 
					"Proteus Technologies Pvt. Ltd.";					
			
			mailToClient = 	"<ROOT><MAIL>"+
									"<EMAIL_TYPE>page</EMAIL_TYPE>" +
									"<ENTITY_CODE>BASE</ENTITY_CODE>" +
									"<ENTITY_TYPE>"+"E"+"</ENTITY_TYPE>" +
									"<SUBJECT>"+mailSubject+"</SUBJECT>" +
									"<BODY_TEXT>"+mailBody+"</BODY_TEXT>" +
									"<TO_ADD>"+clientEmailId.trim()+"</TO_ADD>"+
									"<CC_ADD></CC_ADD>" +
									"<ATTACHMENT><BODY></BODY><LOCATION></LOCATION></ATTACHMENT>"+
									"</MAIL></ROOT>";
			
			BaseLogger.log("3", getUserInfo(), null,  "Service Ticket Awaiting client confirmation mail to client....::"+mailToClient);
			email.sendMail(mailToClient, "ITM", userInfo);
			BaseLogger.log("3", getUserInfo(), null,  "Service Ticket Awaiting client confirmation mail to client...send completed successfully...::");
		}
		catch(Exception e )
		{
			BaseLogger.log("3", getUserInfo(), null,  "Exception in ServiceResolvePostSave::::Mail not send...!");
			e.getMessage();
			e.printStackTrace();				
			throw new ITMException(e);
		}//success messages for ticket has been closed	
		return errString;
	}
	
	private Node getCurrentDetailFromDom(Document dom,String domId)
	{
		NodeList detailList = null;
		Node currDetail = null,reqDetail = null;
		String currDomId = "";
		int	detailListLength = 0;

		detailList = dom.getElementsByTagName("Detail2");
		detailListLength = detailList.getLength();
		for (int ctr = 0;ctr < detailListLength;ctr++)
		{
			currDetail = detailList.item(ctr);
			currDomId = currDetail.getAttributes().getNamedItem("domID").getNodeValue();
			if ( currDomId.equals( domId ) )
			{
				reqDetail = currDetail;
				break;
			}			
		}
		return reqDetail;
	}
	public String checkNull(String inputStr) throws ITMException {
		try {
			if (inputStr != null && inputStr.trim().length() > 0) {
				return inputStr.trim();
			} else {
				return "";
			}
		} catch (Exception e) {
			BaseLogger.log("3", getUserInfo(), null, "Exception in checknull--[" + e.getMessage() + "]");
			e.printStackTrace();
			throw new ITMException(e);
		}
	}
	private String getCurrentUpdateFlag(Node currDetail)
	{
		NodeList currDetailList = null;
		String updateStatus = "",nodeName = "";
		int currDetailListLength = 0;

		currDetailList = currDetail.getChildNodes();
		currDetailListLength = currDetailList.getLength();
		for (int i=0;i< currDetailListLength;i++)
		{
			nodeName = currDetailList.item(i).getNodeName();
			if (nodeName.equalsIgnoreCase("Attribute"))
			{
				updateStatus = currDetailList.item(i).getAttributes().getNamedItem("updateFlag").getNodeValue();
				break;
			}
		}
		return updateStatus;		
	}	

	private DistStkUpdLocal getComponent(String componentName)throws Exception // for ejb3
    {
		DistStkUpdLocal distStkUpdLocal = null;
        try
        {
			System.out.println("Looking For Component.... :: " + componentName);
			AppConnectParm appConnect = new AppConnectParm();
			java.util.Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);
			distStkUpdLocal = (DistStkUpdLocal)ctx.lookup("ibase/DistStkUpd/local");  //for ejb3 
			System.out.println(componentName+" Found.....");			
        }
        catch(Exception e)
        {
			throw e;
        }
		return distStkUpdLocal;
	}
	
}
