/*
 * Created on April 04, 2007
 *
 */
package ibase.webitm.ejb.fin;

/**
 * @author - Alka
 *
 */

import java.rmi.RemoteException;
import java.text.*;
import java.util.ArrayList;
import java.util.Date;
import java.sql.*;

import org.w3c.dom.*;


import javax.ejb.*;

import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.DistCommon;
import javax.ejb.Stateless; // added for ejb3
@Stateless // added for ejb3

public class PaymentReq extends ValidatorEJB implements PaymentReqLocal,PaymentReqRemote // SessionBean
{
	GenericUtility genericUtility = GenericUtility.getInstance(); 

	/*public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("PaymentReqEJB is in Process..........");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}

	public String itemChanged() throws RemoteException,ITMException
	{
		return "";
	}
	public String wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String  errString = null;
		System.out.println("Validation Start..........");
		try
		{
			System.out.println("xmlString:::"+ xmlString);
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1); 
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : PaymentReqEJB : wfValData(String xmlString) : ==>\n"+e.getMessage());
		}
		return (errString);
	}
	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = "", errCode = "";
		ConnDriver connDriver = new ConnDriver();	
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		String loginCode = null; 
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = null; 
		int ctr,currentFormNo=0, cnt = 0;
		int childNodeListLength;
		String  empCodeCust = "", empCodeDivHd = "", workflowStatus = "";
		String tranIdPorcp = "",  confirmed = "", varValue = "", vouchCreated = "", itemSer = "";
		double amountToPay = 0, porcpAmount = 0, amountPaid = 0;
		ArrayList arItemSer =  new ArrayList();
		DistCommon distCommon = new DistCommon();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			loginCode = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			GenericUtility genericUtility = GenericUtility.getInstance(); 
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch(currentFormNo)
			{
				case 1:
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					for(ctr = 0; ctr < childNodeListLength; ctr++)
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						
						if (childNodeName.equals("tran_id"))
						{
							tranIdPorcp = genericUtility.getColumnValue("tran_id", dom);
							System.out.println("tranIdPorcp ::: " + tranIdPorcp);
							
//							TO CHECK IF PORCP TRANSACTION IS CONFIRMED AND IF ITEM_SER MATCHES DISPARM
							sql = "SELECT CONFIRMED, ITEM_SER, VOUCH_CREATED, WORKFLOW_STATUS FROM PORCP WHERE TRAN_ID = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, tranIdPorcp);
							rs = pstmt.executeQuery();
							
							if (rs.next())
							{
								confirmed = rs.getString(1)== null ? "N":rs.getString(1);
								itemSer = rs.getString(2).trim();
								vouchCreated = rs.getString(3)== null ? "N":rs.getString(3);
								workflowStatus = rs.getString(4) == null ? "0":rs.getString(4);
							}
							rs.close();
							pstmt.close();
							if (workflowStatus.equalsIgnoreCase("1"))
							{
								errCode = "VTPORWF";
								errString = getErrorString("tran_id",errCode,loginCode);
								break;
							}
							
							if (confirmed.equalsIgnoreCase("N"))
							{
								errCode = "VTPORCN";
								errString = getErrorString("tran_id",errCode,loginCode);
								break;
							}
							if (vouchCreated.equalsIgnoreCase("Y"))
							{
								errCode = "VTPORVCH";
								errString = getErrorString("tran_id",errCode,loginCode);
								break;
							}
							System.out.println("itemSer ::: [" + itemSer + "]");

							varValue = distCommon.getDisparams("999999", "PAY_REQ_SER", conn);
							if (varValue.indexOf(",") > 0)
							{
								arItemSer = genericUtility.getTokenList(varValue, ",");
							}
							for (int i=0; i<arItemSer.size(); i++)
							{
								if (arItemSer.contains((Object)itemSer))
								{
									continue;
								}
								else
								{
									errCode = "VTPORSER";
									errString = getErrorString("tran_id",errCode,loginCode);
									break;
								}
							}
						}
						else if (childNodeName.equals("emp_code__cust"))
						{
							empCodeCust = genericUtility.getColumnValue("emp_code__cust", dom);
							
							sql = " SELECT COUNT(*) FROM EMPLOYEE WHERE EMP_CODE = '" + empCodeCust + "'";
							pstmt = conn.prepareStatement(sql);
//							pstmt.setString(1, empCodeCust);
							rs = pstmt.executeQuery();
							
							if (rs.next())
							{
								cnt = rs.getInt(1);
							}
							rs.close();
							pstmt.close();
							if (cnt != 1)
							{
								errCode = "VTCUSTO";
								errString = getErrorString("emp_code__cust",errCode,loginCode);
								break;
							}
						}
						else if (childNodeName.equals("emp_code__divhd"))
						{
							empCodeDivHd = genericUtility.getColumnValue("emp_code__divhd", dom);
							
							sql = " SELECT COUNT(*) FROM EMPLOYEE WHERE EMP_CODE = '" + empCodeDivHd + "'";
							pstmt = conn.prepareStatement(sql);
//							pstmt.setString(1, empCodeDivHd);
							rs = pstmt.executeQuery();
							
							if (rs.next())
							{
								cnt = rs.getInt(1);
							}
							rs.close();
							pstmt.close();
							if (cnt != 1)
							{
								errCode = "VTDIVHD";
								errString = getErrorString("emp_code__divhd",errCode,loginCode);
								break;
							}
						}
						else if (childNodeName.equals("amount_topay"))
						{
							amountToPay = Double.parseDouble(genericUtility.getColumnValue("amount_topay", dom));
							porcpAmount = Double.parseDouble(genericUtility.getColumnValue("porcp_amount", dom));
							amountPaid = Double.parseDouble(genericUtility.getColumnValue("amount_paid", dom));
							
							if (amountToPay > porcpAmount)
							{
								errCode = "VTAPPAMT";
								errString = getErrorString("amount_topay",errCode,loginCode);
								break;
							}
						}
					}//END FOR
					break;
				case 2:
					System.out.println("Validation for Detail..........");

			}//END SWITCH
		}//END TRY
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
		}
		finally
		{
			try	{
				pstmt = null; rs = null;
				conn.close();conn = null;
			}catch(Exception d){}
		}

		System.out.println("ErrString ::"+ errString);
		return errString;
	}//END OF VALIDATION 

	public String itemChanged(String xmlString, String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String valueXmlString = null;
		try
		{
			dom = parseString(xmlString); 
			System.out.println("xmlString" + xmlString);
			dom1 = parseString(xmlString1); 
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [PaymentReqEJB][itemChanged(String,String)] :==>\n"+e.getMessage());
		}
        return valueXmlString; 
	}
	
	public String itemChanged(Document dom, Document dom1,Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		int currentFormNo = 0;
		StringBuffer valueXmlString = new StringBuffer();
		String columnValue = null;
		String tranIdPorcp="", tranDatePorcp = "", suppCode = "", suppName = "", recDate = "";
		String purcOrder = "", transMode = "", tranName = "", lrNo = "", lrDate = "", dcNo = "", dcDate = "";
		String frtAmount = "", invoiceNo = "", invoiceDate = "", exciseRef = "", ordDate = "";
		String projCode = "", crTerm = "", empCodeCust = "", empCodeDivHd = "";
		String empFname = "", empMname = "", empLname = "", cctrCodeDr = "";
		double amtPaid = 0, porcpAmount = 0;
		
		NodeList parentNodeList = null;
		Node parentNode = null; 
		Node childNode = null;
		NodeList childNodeList = null;
		String childNodeName = null;
		int ctr = 0;
		
		GenericUtility genericUtility = GenericUtility.getInstance();
				
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			System.out.println("[PaymentReqEJB] [itemChanged] :currentFormNo ....." +currentFormNo);
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			valueXmlString.append("<Detail>");	
			switch (currentFormNo)
			{
				case 1:
					
//				SEARCHING THE DOM FOR THE INCOMING COLUMN VALUE START
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					ctr = 0;
					int childNodeListLength = childNodeList.getLength();
					do
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if(childNodeName.equals(currentColumn))
						{
							if (childNode.getFirstChild() != null)
							{
								columnValue=childNode.getFirstChild().getNodeValue().trim();
							}
						}
						ctr++;
					}while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));
					System.out.println(currentColumn + " ==> '" + columnValue + "'");
					if (currentColumn.trim().equals("tran_id"))
					{
						tranIdPorcp = genericUtility.getColumnValue("tran_id", dom);
						System.out.println("tranIdPorcp ::: " + tranIdPorcp);
						
						sql = " SELECT A.TRAN_DATE, A.PURC_ORDER, A.SUPP_CODE, B.SUPP_NAME, A.DC_NO, A.DC_DATE, "
							+ " C.TRAN_NAME, A.REC_DATE, A.EXCISE_REF, A.LR_NO, A.LR_DATE, A.TRANS_MODE, "
							+ " A.FRT_AMT, A.INVOICE_NO, A.INVOICE_DATE, D.ORD_DATE, D.PROJ_CODE, D.CR_TERM, A.AMOUNT "
							+ " FROM PORCP A LEFT OUTER JOIN TRANSPORTER C ON A.TRAN_CODE = C.TRAN_CODE, "
							+ " SUPPLIER B, PORDER D  WHERE  A.SUPP_CODE = B.SUPP_CODE  AND "
							+ " A.PURC_ORDER = D.PURC_ORDER AND A.TRAN_ID = ? "; //'"+ tranIdPorcp +"'

						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, tranIdPorcp);
						rs = pstmt.executeQuery();
						System.out.println("sql ::: " + sql);
						if (rs.next())
						{
							tranDatePorcp = genericUtility.getValidDateString(rs.getTimestamp(1).toString(), genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat()); 
							purcOrder = rs.getString(2); 
							suppCode = rs.getString(3); 
							suppName = rs.getString(4); 
							dcNo = rs.getString(5) == null ? "":rs.getString(5); 
							dcDate = rs.getString(6) == null?"":genericUtility.getValidDateString(rs.getTimestamp(6).toString(), genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat()); 
							tranName = rs.getString(7) == null ? "":rs.getString(7); 
							recDate = rs.getString(8) == null?"":genericUtility.getValidDateString(rs.getTimestamp(8).toString(), genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat()); ;
							exciseRef = rs.getString(9) == null ? "":rs.getString(9); 
							lrNo = rs.getString(10) == null ? "":rs.getString(10); 
							lrDate = rs.getString(11) == null?"":genericUtility.getValidDateString(rs.getTimestamp(11).toString(), genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat()); ; 
							transMode = rs.getString(12) == null ? "":rs.getString(12); 
							frtAmount = rs.getString(13) == null ? "":rs.getString(13);
							invoiceNo = rs.getString(14) == null ? "":rs.getString(14); 
							invoiceDate = rs.getString(15) == null?"":genericUtility.getValidDateString(rs.getTimestamp(15).toString(), genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat()); 
							ordDate = rs.getTimestamp(16) == null?"":genericUtility.getValidDateString(rs.getTimestamp(16).toString(), genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat()); 
							projCode = rs.getString(17) == null ? "":rs.getString(17); 
							crTerm = rs.getString(18) == null ? "":rs.getString(18);
							porcpAmount = rs.getDouble(19);
						}
						rs.close();
						pstmt.close();
						
						sql = " SELECT SUM(NET_AMT) FROM MISC_PAYDET WHERE VOUCH_NO IN " 
							+ " (SELECT TRAN_ID FROM VOUCHER WHERE PURC_ORDER = ? )";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, purcOrder);
						rs = pstmt.executeQuery();
						System.out.println("sql ::: " + sql);
						if (rs.next())
						{
							amtPaid = rs.getDouble(1);
						}
						
						sql = "SELECT CCTR_CODE__DR FROM PORCPDET WHERE TRAN_ID = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, tranIdPorcp);
						rs = pstmt.executeQuery();
						
						while (rs.next())
						{
							if (cctrCodeDr == "")
							{
								cctrCodeDr = rs.getString(1);
								System.out.println("cctrCodeDr :::: " + cctrCodeDr);
							}
							else
							{
								break;
							}
						}
						valueXmlString.append("<tran_date>").append("<![CDATA[" + tranDatePorcp + "]]>").append("</tran_date>");
						valueXmlString.append("<purc_order>").append("<![CDATA[" + purcOrder + "]]>").append("</purc_order>");
						valueXmlString.append("<supp_code>").append("<![CDATA[" + suppCode + "]]>").append("</supp_code>");
						valueXmlString.append("<supp_name>").append("<![CDATA[" + suppName + "]]>").append("</supp_name>");
						valueXmlString.append("<dc_no>").append("<![CDATA[" + dcNo + "]]>").append("</dc_no>");
						valueXmlString.append("<dc_date>").append("<![CDATA[" + dcDate + "]]>").append("</dc_date>");
						valueXmlString.append("<tran_name>").append("<![CDATA[" + tranName + "]]>").append("</tran_name>");
						valueXmlString.append("<rec_date>").append("<![CDATA[" + recDate + "]]>").append("</rec_date>");
						valueXmlString.append("<excise_ref>").append("<![CDATA[" + exciseRef + "]]>").append("</excise_ref>");
						valueXmlString.append("<lr_no>").append("<![CDATA[" + lrNo + "]]>").append("</lr_no>");
						valueXmlString.append("<lr_date>").append("<![CDATA[" + lrDate + "]]>").append("</lr_date>");
						valueXmlString.append("<trans_mode>").append("<![CDATA[" + transMode + "]]>").append("</trans_mode>");
						valueXmlString.append("<frt_amt>").append("<![CDATA[" + frtAmount + "]]>").append("</frt_amt>");
						valueXmlString.append("<invoice_no>").append("<![CDATA[" + invoiceNo + "]]>").append("</invoice_no>");
						valueXmlString.append("<invoice_date>").append("<![CDATA[" + invoiceDate + "]]>").append("</invoice_date>");
						valueXmlString.append("<ord_date>").append("<![CDATA[" + ordDate + "]]>").append("</ord_date>");
						valueXmlString.append("<proj_code>").append("<![CDATA[" + projCode + "]]>").append("</proj_code>");
						valueXmlString.append("<cr_term>").append("<![CDATA[" + crTerm + "]]>").append("</cr_term>");
						valueXmlString.append("<porcp_amount>").append("<![CDATA[" + porcpAmount + "]]>").append("</porcp_amount>");
						valueXmlString.append("<amount_paid>").append("<![CDATA[" + amtPaid + "]]>").append("</amount_paid>");
						valueXmlString.append("<cctr_code><![CDATA[").append(cctrCodeDr).append("]]></cctr_code>");
					}
					else if (currentColumn.trim().equals("emp_code__cust"))
					{
						empCodeCust = genericUtility.getColumnValue("emp_code__cust", dom);
						
						sql = " SELECT EMP_FNAME, EMP_MNAME, EMP_LNAME FROM EMPLOYEE WHERE EMP_CODE = '" + empCodeCust + "' ";
						pstmt = conn.prepareStatement(sql);
//						pstmt.setString(1, empCodeCust);
						rs = pstmt.executeQuery();
						
						if (rs.next())
						{
							empFname = rs.getString(1);
							empMname = rs.getString(2);
							empLname = rs.getString(3);
						}
						rs.close();
						pstmt.close();

						valueXmlString.append("<cust_fname>").append("<![CDATA[" + empFname + "]]>").append("</cust_fname>");
						valueXmlString.append("<cust_mname>").append("<![CDATA[" + empMname + "]]>").append("</cust_mname>");
						valueXmlString.append("<cust_lname>").append("<![CDATA[" + empLname + "]]>").append("</cust_lname>");
					}
					else if (currentColumn.trim().equals("emp_code__divhd"))
					{
						empCodeDivHd = genericUtility.getColumnValue("emp_code__divhd", dom);
						
						sql = " SELECT EMP_FNAME, EMP_MNAME, EMP_LNAME FROM EMPLOYEE WHERE EMP_CODE = '" + empCodeDivHd + "' ";
						pstmt = conn.prepareStatement(sql);
//						pstmt.setString(1, empCodeDivHd	);
						rs = pstmt.executeQuery();
						
						if (rs.next())
						{
							empFname = rs.getString(1);
							empMname = rs.getString(2);
							empLname = rs.getString(3);
						}
						rs.close();
						pstmt.close();

						valueXmlString.append("<divhd_fname>").append("<![CDATA[" + empFname + "]]>").append("</divhd_fname>");
						valueXmlString.append("<divhd_mname>").append("<![CDATA[" + empMname + "]]>").append("</divhd_mname>");
						valueXmlString.append("<divhd_lname>").append("<![CDATA[" + empLname + "]]>").append("</divhd_lname>");
					}
					valueXmlString.append("</Detail>");
					break;
				
				case 2:
				}//END OF SWITCH
				valueXmlString.append("</Root>");				
			}//END OF TRY
		
		catch(Exception e)
		{
			System.out.println("Exception ::"+ e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close(); rs = null;
					pstmt.close(); pstmt = null;
					conn.close();conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception ::"+e);
				e.printStackTrace();
			}			
		}
		return valueXmlString.toString();
	}//END OF ITEMCHANGE
	
	public void confirmPaymentReq(String tranId, String roleCode, String authority) throws RemoteException
	{
		System.out.println("Updating Status in Transaction .... for roleCode ["+ roleCode +"] for tranId ["+tranId+"] by [" + authority + "]");
		ConnDriver connDriver = new ConnDriver();
//		String retString = "";
		String sql = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try
		{
			conn = connDriver.getConnectDB("Driver");
			connDriver = null;
//			loginEmpCode = getEmpCode(roleCode, conn);
			System.out.println("roleCode in confirmPaymentReq ::::::::"+ roleCode);
		
			if (authority.equalsIgnoreCase("C"))
			{
				sql = "UPDATE PAYMENT_REQ SET CONFIRMED__CUST ='Y', CONF_DATE__CUST = ? WHERE TRAN_ID = ? " ;
			}
			else if (authority.equalsIgnoreCase("D"))
			{
				sql = "UPDATE PAYMENT_REQ SET CONFIRMED__DIVHD ='Y', CONF_DATE__DIVHD = ? WHERE TRAN_ID = ? " ;
			}
			else if (authority.equalsIgnoreCase("PUR"))
			{
				sql = "UPDATE PORCP SET VOUCH_CREATED ='Y' WHERE TRAN_ID IN (SELECT TRAN_ID__PORCP FROM PAYMENT_REQ "
					+ " WHERE TRAN_ID = ?) " ;
			}
			
			System.out.println("Executing Query:::" + sql);				
			System.out.println("Setting Parameters :::["+ tranId + "]");
			pstmt=conn.prepareStatement(sql);
			if (authority.equalsIgnoreCase("PUR"))
			{
				pstmt.setString(1,tranId);
			}
			else
			{
				pstmt.setTimestamp(1,new Timestamp(System.currentTimeMillis()));
				pstmt.setString(2,tranId);
			}
			int update = pstmt.executeUpdate();
			System.out.println("No Of Record Update for authority -- " + authority + " :::::" + update);
		}
		catch (SQLException se)
		{
			System.out.println("Exception ::"+se);
			se.printStackTrace();
		}
		catch (Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
		}
		finally{
		    try{
		    	if (pstmt != null)
		    	{
		    		pstmt.close(); pstmt = null;
		    	}
		    	if (conn != null)
		    	{
		    		conn.close(); conn = null;
		    	}
		    }catch(Exception e){}
		}
	}

/*	private String getEmpCode(String rCode, Connection con)
	{
		String sql=null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String eCode=null;
		
		try
		{
			sql="SELECT EMP_CODE FROM USERS A, WF_ROLE B WHERE A.CODE = B.USER_ID AND B.ROLE_CODE = '" + rCode + "'";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next())
			{
				eCode = rs.getString(1);
			}
			rs.close(); rs=null;
			pstmt.close(); pstmt=null;
		}
		catch(Exception e)
		{
			System.out.println("Exception in getEmpCode :::: " + e.getMessage());
			e.printStackTrace();
		}
		return eCode;
	}*/
}
