package com.reallinkbilling.jspRedirect;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.utils.GetAccountListForDrCr;
import com.reallinkbilling.utils.GetTypeOfPaymentList;

public class AddCustPaymentDetailsJsp extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -3799538907460674543L;
	
	private HttpSession session;
	private String key;
	private String paymentDate;
	private String custName;
	private String custMobile;
	private String outstandingAmount;
	private SessionMap<String,Object> sessionMap;
	
	private Map<String,String> accountList = new LinkedHashMap<String,String>();
	private List<String> paymentTypeList = new ArrayList<String>();
	
	
	public String execute(){
		
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		 
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        else{
	        	
	        	this.setAccountList(GetAccountListForDrCr.getAccountList(this.getSessionMap())); 
	        	this.setPaymentTypeList(GetTypeOfPaymentList.getTypeOfPaymentList());
	        	
	        	Date d = new Date();
	        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
	        	
	        	setPaymentDate(dateFormat.format(d));
	        	
	        	Connection connection = null;
	       		PreparedStatement preparedStatement= null;
	       		ResultSet resultSet = null;
	       		
	       		
	       		String sql = "";
	       		String db = (String) this.getSessionMap().get("db");
	       		
	       		try {
	       			
	       			String shopId = (String) this.getSessionMap().get("shopId");
		    		String shopCode = (String) this.getSessionMap().get("shopCode");
	       			
					connection = GetDBConnection.getDBConnection(db);
	       			
	       			
	       			String custId = EncryptionDecryption.decrypt(key);
	       			
	       			setKey(EncryptionDecryption.encrypt(custId));
	       			
	       			
	       			float openingBal = 0.0F;
       				
       				PreparedStatement getOpeningBalPSMT = null;
       				ResultSet getOpeningBalRS = null;
       				String sqlOpeningBal = "SELECT "
       						+ "opening_balance "
       						+ "FROM "
       						+ "shop_cust_close_open_bal_master  "
       						+ "WHERE "
       						+ "customer_id = ? "
       						+ "AND "
       						+ "shop_id = ? "
       						+ "AND "
       						+ "shop_code = ? ";
       				
       				getOpeningBalPSMT = connection.prepareStatement(sqlOpeningBal);
       				
       				getOpeningBalPSMT.setString(1, custId);
       				getOpeningBalPSMT.setString(2, shopId);
       				getOpeningBalPSMT.setString(3, shopCode);
       				
       				getOpeningBalRS = getOpeningBalPSMT.executeQuery();
       				
       				if(getOpeningBalRS.next())
       				{
       					openingBal = getOpeningBalRS.getFloat(1);
       				}
       			
       				if(getOpeningBalRS != null)
       				{
       					getOpeningBalRS.close();
       					getOpeningBalRS = null;
       				}
       				
       				if(getOpeningBalPSMT != null)
       				{
       					getOpeningBalPSMT.close();
       					getOpeningBalPSMT = null;
       				}
       				
	       				       			
	       			sql = "select "
	       					+ "customer_name,"
	       					+ "mobile_number "
	       					+ "FROM "
	       					+ "shop_customer_master "
	       					+ "WHERE "
	       					+ "shop_id = ? "
	       					+ "AND "
	       					+ "shop_code = ? "
	       					+ "AND "
	       					+ "customer_id = ?";
	       			
	       			
	       			preparedStatement = connection.prepareStatement(sql);
	       			preparedStatement.setString(1, shopId);
	       			preparedStatement.setString(2, shopCode);
	       			preparedStatement.setString(3, custId);
	       			
	       			resultSet = preparedStatement.executeQuery();
	       			
	       			resultSet.last();
	       			int rowCount = resultSet.getRow();
	       			resultSet.beforeFirst();
	       			
	       			
	       			if(rowCount>0)
	       			{
	       				result = "success";
		       			if(resultSet.next())
		       			{
		       				
		       				this.setCustName(resultSet.getString(1));
		       				this.setCustMobile(resultSet.getString(2));		       				
		       				
		       				
		       			}
		       			if(resultSet != null)
		       			{
		       				resultSet.close();
		       				resultSet = null;
		       			}
		       		
		       			if(preparedStatement != null)
	       				{
	       					preparedStatement.close();
	       					preparedStatement = null;
	       				}
		       			
	       				float floatTotalAmt = 0.0F;
	       				float floatAmtReceived = 0.0F;
	       				float floatBalanceAmt = 0.0F;
	       				float totalBalanceAmt = 0.0F;
	       				float totalPaymentDone = 0.0F;
	       				
	       				sql = "SELECT "	           					
	           					+ "bill_total_amount,"
	           					+ "bill_amount_received,"
	           					+ "bill_amount_retrurn "
	           					+ "FROM "
	           					+ "shop_bill_info_master "
	           					+ "WHERE "
	           					+ "shop_id = ? "
	           					+ "AND "
	           					+ "shop_code = ? "
	           					+ "AND "		           					
	           					+ "customer_id = ?";
	           				
	       				
	       				
	       				preparedStatement = connection.prepareStatement(sql);
	       				preparedStatement.setString(1, shopId);
	       				preparedStatement.setString(2, shopCode);
	       				preparedStatement.setString(3, custId);
	       				
	       				ResultSet resultSetBillInfo = preparedStatement.executeQuery();
	       				
	       				while(resultSetBillInfo.next())
	       				{
	       					try
	       					{
		       					floatTotalAmt = Float.parseFloat(resultSetBillInfo.getString(1));
		           				floatAmtReceived = Float.parseFloat(resultSetBillInfo.getString(2));
		           				floatBalanceAmt = floatTotalAmt - floatAmtReceived;
		           				
		           				if(floatBalanceAmt > 0)
		           				{
		           					totalBalanceAmt = totalBalanceAmt+floatBalanceAmt; 	           					
		           				}
		           				
	       					}catch(NumberFormatException nfe)
	       					{
	       						result = "error";
	       						addActionError("Error While Formatting while calculating balance amount!"+nfe.getMessage());
	       					}
	       				}
	       				if(resultSetBillInfo != null)
	       				{
	       					resultSetBillInfo.close();
	       				}
	       				if(preparedStatement != null)
	       				{
	       					preparedStatement.close();
	       				}
	       				
	       				sql = "SELECT "
	       						+ "SUM(payment_amount) "
	       						+ "FROM "
	       						+ "shop_customer_payment_master "
	       						+ "WHERE "
	       						+ "shop_id = ? "
	       						+ "AND "
	       						+ "shop_code = ? "
	       						+ "AND "
	       						+ "customer_id = ?";
	       			
	       				preparedStatement = connection.prepareStatement(sql);
	       				preparedStatement.setString(1, shopId);
	       				preparedStatement.setString(2, shopCode);
	       				preparedStatement.setString(3, custId);
	       				
	       				ResultSet resultSetTotalPayment = preparedStatement.executeQuery();
	       				
	       				resultSetTotalPayment.last();
	       				int rowCount2 = resultSetTotalPayment.getRow();
	       				resultSetTotalPayment.beforeFirst();
	       				
	       				if(rowCount2>0)
	       				{
	       				
		       				while(resultSetTotalPayment.next())
		       				{
		       					try
		       					{
		       						if(resultSetTotalPayment.getString(1) != null)
		       						{		       						
		       							totalPaymentDone = Float.parseFloat(resultSetTotalPayment.getString(1));
		       						}
		       					}
		       					catch(NumberFormatException nfe)
		       					{
		       						result = "error";
		       						addActionError("Error While Formatting while calculating total payment amount!"+nfe.getMessage());
		       					}
		       				}
		       						
		       				
		       				totalBalanceAmt = (totalBalanceAmt - totalPaymentDone) + openingBal;
	       				}
	       				setOutstandingAmount(""+totalBalanceAmt);
	       				
	       				if(resultSetTotalPayment != null)
	       				{
	       					resultSetTotalPayment.close();
	       					resultSetTotalPayment = null;
	       				}
	       				
	       			}else
	       			{
	       				result = "error";
	       				addActionError("Somthing Went Wrong ! Please try Again");
	       			}
	   				
	       		} catch (SQLException e) {
	    			//e.printStackTrace();
	    			addActionError(e.getErrorCode()+" || "+e.getMessage() +" || DETAILS NOT FOUND !");
	    		} catch (IOException e) {
	    			
	    			//e.printStackTrace();
	    			addActionError(e.getMessage()+" || "+e.getCause()+" || DETAILS NOT FOUND !");
	    		}finally {
	    			if(resultSet != null)
    				{
    					try {
    						resultSet.close();
    					} catch (SQLException e) {
    						
    					}
    				}
	    			if(preparedStatement != null)
	    			{
	    				try {preparedStatement.close();} catch (SQLException e) {}
	    			}
	    			if(connection != null)
	    			{
	    				
	    				try {connection.close();}catch (SQLException e) {}
	    			}
	    			
	    		}
	        	
	        }
	        
	        return result;
}


public HttpSession getSession() {
	return session;
}


public void setSession(HttpSession session) {
	this.session = session;
}


public String getKey() {
	return key;
}


public void setKey(String key) {
	this.key = key;
}


public String getPaymentDate() {
	return paymentDate;
}


public void setPaymentDate(String paymentDate) {
	this.paymentDate = paymentDate;
}


public String getCustName() {
	return custName;
}


public void setCustName(String custName) {
	this.custName = custName;
}


public String getCustMobile() {
	return custMobile;
}


public void setCustMobile(String custMobile) {
	this.custMobile = custMobile;
}


public String getOutstandingAmount() {
	return outstandingAmount;
}


public void setOutstandingAmount(String outstandingAmount) {
	this.outstandingAmount = outstandingAmount;
}



public Map<String, String> getAccountList() {
	return accountList;
}


public void setAccountList(Map<String, String> accountList) {
	this.accountList = accountList;
}


public List<String> getPaymentTypeList() {
	return paymentTypeList;
}


public void setPaymentTypeList(List<String> paymentTypeList) {
	this.paymentTypeList = paymentTypeList;
}


public static long getSerialversionuid() {
	return serialVersionUID;
}


public SessionMap<String, Object> getSessionMap() {
return sessionMap;
}

public void setSessionMap(SessionMap<String, Object> sessionMap) {
this.sessionMap = sessionMap;
}

public void setSession(Map<String, Object> map) {  
sessionMap=(SessionMap<String, Object>)map;  
}

}
