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.HashMap;
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.DAO.DayWiseCollectionDAO;
import com.reallinkbilling.db.GetDBConnection;

public class CollectionReportJsp extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -8703987118265094121L;
	private String fromDate;
	private String toDate;
	private HttpSession session;
	private List<DayWiseCollectionDAO> collectionDAOList = new ArrayList<DayWiseCollectionDAO>();
	private SessionMap<String,Object> sessionMap;  
	private String defaultValue;
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	
	@Override
	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{
	        	
	        	customerSearchOptionList.put("BYNAME", "BY NAME");
	        	customerSearchOptionList.put("BYMOBILE", "BY MOBILE");
	        	customerSearchOptionList.put("BYADDRESS","BY ADDRESS");
				setCustomerSearchOption("BYNAME");
				setDefaultValue("BYNAME");
				
	        	
	        	Date d = new Date();
	        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
	        	this.setFromDate(dateFormat.format(d));
	        	this.setToDate(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");
		    		
	    			DayWiseCollectionDAO collectionDAO = new DayWiseCollectionDAO();
	    			
					connection = GetDBConnection.getDBConnection(db);
	    			
	    			
	    			// cash collection 
					sql = "SELECT "
	    					+ "bill_date,"
	    					+ "bill_total_amount,"
	    					+ "bill_amount_received,"
	    					+ "bill_amount_retrurn "
	    					+ "FROM "
	    					+ "shop_bill_info_master "
	    					+ "WHERE "
	    					+ "shop_id = ? "
	    					+ "AND "
	    					+ "shop_code = ? "
	    					+ "AND "
	    					+ "bill_date = STR_TO_DATE(?, '%d-%m-%Y')";
	    			
	    			preparedStatement =connection.prepareStatement(sql);
	    			preparedStatement.setString(1, shopId);
	    			preparedStatement.setString(2, shopCode);
	    			preparedStatement.setString(3, this.getFromDate());
	    			resultSet = preparedStatement.executeQuery();
	    		
	    			float totalBillAmount = 0.0F;
	    			float totalCreditGiven = 0.0F;
	    			float totalAmountCollected = 0.0F;
	    			float totalCreditCollection =0.0F;
	    			while(resultSet.next())	    				
	    			{
	    				
    				if(resultSet.getString(2) != null && resultSet.getString(3) != null && resultSet.getString(4) != null)
    				{
	    				totalBillAmount = totalBillAmount + (Float.parseFloat(resultSet.getString(2)));
	    				
	    				float amtReceived = Float.parseFloat(resultSet.getString(3));
	    				float amountReturn  = Float.parseFloat(resultSet.getString(4));
	    				
	    				if(amountReturn > 0 )
	    				{
	    					totalAmountCollected = totalAmountCollected + Float.parseFloat(resultSet.getString(2));
	    				}
	    				else
	    				{
	    					totalAmountCollected = totalAmountCollected + amtReceived;
	    					totalCreditGiven = totalCreditGiven 
	    							+ (Float.parseFloat(resultSet.getString(2)) - amtReceived);
	    				}
	    				
	    			}
	    			}
	    			
	    			
	    			

	    			sql = "SELECT SUM(payment_amount) "
	    					+ "FROM "
	    					+ "shop_customer_payment_master "
	    					+ "WHERE "
	    					+ "shop_id = ? "
	    					+ "AND "
	    					+ "shop_code = ? "
	    					+ "AND "
	    					+ "entry_date = STR_TO_DATE(?, '%d-%m-%Y')";
	    			
	    			PreparedStatement ps = connection.prepareStatement(sql);
	    			

	    			ps.setString(1, shopId);
	    			ps.setString(2, shopCode);
	    			ps.setString(3, this.getFromDate());
	    			
	    			ResultSet rs =  ps.executeQuery();
	    		
	    			
	    			if(rs.next())
	    			{
	    				if(rs.getString(1) != null)
	    				{
	    				
	    					totalCreditCollection = Float.parseFloat(rs.getString(1));
	    				}
	    				else
	    				{
	    					totalCreditCollection = 0.0F;
	    				}
	    			}
	    			
	    			collectionDAO.setCollectionDate(getFromDate());
	    			collectionDAO.setTotalBilling(""+totalBillAmount);
	    			collectionDAO.setTotalCashCollection(""+totalAmountCollected);
	    			collectionDAO.setTotalCreditCollection(""+totalCreditCollection);
	    			collectionDAO.setTotalCreeditGiven(""+totalCreditGiven);
	    			collectionDAO.setTotalCollection(""+(totalCreditCollection+totalAmountCollected));
	    			collectionDAOList.add(collectionDAO);
	    		
	    			result ="success";
	    			
	    			if(rs != null)
	    			{
	    				rs.close();
	    			}
	    			
	    			if(ps != null)
	    			{
	    				ps.close();
	    			}
	    		}
	    		 catch (SQLException e) {
		    			
		    			result = "error";
		    			
		    			addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Something Went Wrong!");
		    		} catch (IOException e) {
		    			result = "error";
		    			
		    			addActionError(e.getMessage()+" || "+e.getCause()+" || Something Went Wrong!");
		    		}finally {
		    			if(resultSet != null)
	    				{
	    					try {
	    						resultSet.close(); resultSet = null;
	    					} catch (SQLException e) {
	    						
	    					}
	    				}
		    			if(preparedStatement != null)
		    			{
		    				try {preparedStatement.close(); preparedStatement = null;} catch (SQLException e) {}
		    			}
		    			if(connection != null)
		    			{
		    				
		    				try {connection.close(); connection = null;}catch (SQLException e) {}
		    			}
		    			
		    		}
	        	
	        	
	        	
	        	
	        }
	        
	        return result;
	}
	public String getFromDate() {
		return fromDate;
	}
	public void setFromDate(String fromDate) {
		this.fromDate = fromDate;
	}
	public String getToDate() {
		return toDate;
	}
	public void setToDate(String toDate) {
		this.toDate = toDate;
	}
	public HttpSession getSession() {
		return session;
	}
	public void setSession(HttpSession session) {
		this.session = session;
	}
	public List<DayWiseCollectionDAO> getCollectionDAOList() {
		return collectionDAOList;
	}
	public void setCollectionDAOList(List<DayWiseCollectionDAO> collectionDAOList) {
		this.collectionDAOList = collectionDAOList;
	}
	
	   
		public String getDefaultValue() {
		return defaultValue;
	}
	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}
	public Map<String, String> getCustomerSearchOptionList() {
		return customerSearchOptionList;
	}
	public void setCustomerSearchOptionList(Map<String, String> customerSearchOptionList) {
		this.customerSearchOptionList = customerSearchOptionList;
	}
	public String getCustomerSearchOption() {
		return customerSearchOption;
	}
	public void setCustomerSearchOption(String customerSearchOption) {
		this.customerSearchOption = customerSearchOption;
	}
	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;  
	}
	

}
