package com.reallinkbilling.report;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
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 DaywiseCollectionReport extends ActionSupport implements SessionAware{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -5638605039448515442L;
	
	private String fromDate;
	private String toDate;
	private HttpSession session;
	private List<DayWiseCollectionDAO> collectionDAOList = new ArrayList<DayWiseCollectionDAO>();
	private String defaultValue;
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	
	private String totalBilling;
	private String totalCashCollected;
	private String totalCreditCollected;
	private String totalCreditGiven;
	private String totalCollection;
	private SessionMap<String,Object> sessionMap;  
	
	@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");
	        	
	        	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);
	    			
	    			 Date fromD=new SimpleDateFormat("dd-MM-yyyy").parse(this.getFromDate());  
	    			 Date toD=new SimpleDateFormat("dd-MM-yyyy").parse(this.getToDate());  
	    			 DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
	    			 
	    			 long diff = toD.getTime() -fromD.getTime() ;
	    			
	    			 long fromDateMillies = fromD.getTime();
	    			 
	    			 
	    			 List<String> listOfDays = new ArrayList<String>();
	    			 
	    			
	    			 	listOfDays.add(this.getFromDate());
	    			 	
	    				long diffDays = diff / (24 * 60 * 60 * 1000);
	    				
	    				int intDays = Integer.parseInt(""+diffDays);
	    				
	    				for(int i = intDays;i>0;i--)
	    				{
	    					fromDateMillies = fromDateMillies+(24 * 60 * 60 * 1000);
	    					Date d = new Date(fromDateMillies);	    					
	    					listOfDays.add(dateFormat.format(d));    					
	    				}
	    				
	    				 float floatTotalBilling=0.0F;
	    				 float floatTotalCashCollected=0.0F;
	    				 float floatTotalCreditCollected=0.0F;
	    				 float floatTotalCreditGiven=0.0F;
	    				 float floatTotalCollection=0.0F;
	    				 
	    				
	    				
	    				for(int i = 0;i<listOfDays.size();i++)
	    				{
	    					
	    					
	    					DayWiseCollectionDAO collectionDAO = new DayWiseCollectionDAO();
	    					
	    					
	    					// 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, listOfDays.get(i));
	    	    			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, listOfDays.get(i));
	    	    			ResultSet rs = ps.executeQuery();
	    	    			
	    	    			
	    	    			if(rs.next())
	    	    			{
	    	    				try
	    	    				{
		    	    				if(rs.getString(1) != null)
		    	    				{
		    	    				
		    	    					totalCreditCollection = Float.parseFloat(rs.getString(1));
		    	    				}
		    	    				else
		    	    				{
		    	    					totalCreditCollection = 0.0F;
		    	    				}
	    	    				}catch(NumberFormatException nfe)
	    	    				{}
	    	    			}
	    	    			
	    	    			collectionDAO.setCollectionDate(listOfDays.get(i));
	    	    			collectionDAO.setTotalBilling(""+totalBillAmount);
	    	    			collectionDAO.setTotalCashCollection(""+totalAmountCollected);
	    	    			collectionDAO.setTotalCreditCollection(""+totalCreditCollection);
	    	    			collectionDAO.setTotalCreeditGiven(""+totalCreditGiven);
	    	    			collectionDAO.setTotalCollection(""+(totalCreditCollection+totalAmountCollected));
	    	    			
	    	    			floatTotalBilling = floatTotalBilling+ totalBillAmount;
	    	    			floatTotalCashCollected = floatTotalCashCollected + totalAmountCollected;
	    	    			floatTotalCreditCollected = floatTotalCreditCollected + totalCreditCollection;
	    	    			floatTotalCreditGiven = floatTotalCreditGiven + totalCreditGiven;
	    	    			floatTotalCollection = floatTotalCollection + (totalCreditCollection+totalAmountCollected);
	    	    			
	    	    			
	    	    			this.getCollectionDAOList().add(collectionDAO);	
	    	    			
	    	    			if(rs != null)
	    	    			{
	    	    				rs.close();
	    	    			}
	    	    			if(ps != null)
	    	    			{
	    	    				ps.close();
	    	    			}
	    				}
	    				
	    				
	    				this.setTotalBilling(""+floatTotalBilling);
	    				this.setTotalCashCollected(""+floatTotalCashCollected);
	    				this.setTotalCreditCollected(""+floatTotalCreditCollected);
	    				this.setTotalCreditGiven(""+floatTotalCreditGiven);
	    				this.setTotalCollection(""+floatTotalCollection);
	    				
	    				result = "success";

	    		}
	    		 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!");
		    		} catch (ParseException e) {
		    			result = "error";
		    			addActionError(e.getMessage()+" || "+e.getCause()+" || Error while parsing date! Something Went Wrong!");
					}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;
	}

	@Override
	public void validate() {
		
		try
		{
		 Date fromD=new SimpleDateFormat("dd-MM-yyyy").parse(this.getFromDate());  
		 Date toD=new SimpleDateFormat("dd-MM-yyyy").parse(this.getToDate());
		 long diff = toD.getTime() -fromD.getTime() ;
		 

			
			long diffDays = diff / (24 * 60 * 60 * 1000);
			
			if(diffDays > 31)
			{
				addActionError("Count of days more than 31 is not allowed !");
			}
		}catch(Exception e)
		{
			
		}
	}
	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 String getTotalBilling() {
		return totalBilling;
	}

	public void setTotalBilling(String totalBilling) {
		this.totalBilling = totalBilling;
	}

	public String getTotalCashCollected() {
		return totalCashCollected;
	}

	public void setTotalCashCollected(String totalCashCollected) {
		this.totalCashCollected = totalCashCollected;
	}

	public String getTotalCreditCollected() {
		return totalCreditCollected;
	}

	public void setTotalCreditCollected(String totalCreditCollected) {
		this.totalCreditCollected = totalCreditCollected;
	}

	public String getTotalCreditGiven() {
		return totalCreditGiven;
	}

	public void setTotalCreditGiven(String totalCreditGiven) {
		this.totalCreditGiven = totalCreditGiven;
	}

	public String getTotalCollection() {
		return totalCollection;
	}

	public void setTotalCollection(String totalCollection) {
		this.totalCollection = totalCollection;
	}
	   
	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;  
	}
	

}
