package com.reallinkbilling.report;

import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.reallinkbilling.DAO.CustomerCreditColectionReportDAO;
import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.opensymphony.xwork2.ActionSupport;

public class CreditCollectionReport  extends ActionSupport implements SessionAware, ServletResponseAware, ServletRequestAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6069028619270662664L;
	private String fromDate;
	private String toDate;

	private SessionMap<String,Object> sessionMap;  
	private HttpSession session;
	private List<CustomerCreditColectionReportDAO> creditCollectionList = new ArrayList<CustomerCreditColectionReportDAO>();
	private HttpServletRequest request = null;
	private HttpServletResponse response = null;
	private List<String> downloadTypeList = new ArrayList<String>();
	private String downloadType;
	private String totalAmount = "0.00";
	
	private String customerNameCode;
	
	public String execute(){
		
		
		
		 downloadTypeList.add("pdf");
		    downloadTypeList.add("xl");
		 
		String result = "login";
		this.setSession(ServletActionContext.getRequest().getSession(false)); 
		
	        if(this.getSession()==null || this.getSession().getAttribute("login")==null){ 
	        	addActionMessage(this.getText("message.error.plzloginfirst"));
	        	result = "login";
	        }  
	        else{
	        	 Map<String, String> map = new HashMap<String, String>();

		        Enumeration <String> headerNames = this.getRequest().getHeaderNames();
		        
		        while (headerNames.hasMoreElements()) {
		            String key = (String) headerNames.nextElement();
		            String value = this.getRequest().getHeader(key);
		            map.put(key, value);
		        }
		        //Android
		      
		    
		      
		      
		    	
	        	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);
					
					if(this.getCustomerNameCode() == null || this.getCustomerNameCode().trim().equals(""))
					{
					
						sql = "SELECT "
								+ "customer_id,"
								+ "customer_name,"
								+ "DATE_FORMAT(entry_date,'%d-%m-%Y'),"
								+ "entry_time,"
								+ "payment_amount,"
								+ "payment_details, "
								+ "payment_received_by,"
								+ "entry_id "
								+ "FROM "
								+ "shop_customer_payment_master "
								+ "WHERE "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? "
								+ "AND "
								+ "(entry_date "
								+ "BETWEEN "
								+ "STR_TO_DATE(?,'%d-%m-%Y') "
								+ "AND "
								+ "STR_TO_DATE(?,'%d-%m-%Y'))";
						
						
						
						preparedStatement = connection.prepareStatement(sql);
						preparedStatement.setString(1, shopId);
						preparedStatement.setString(2, shopCode);
						preparedStatement.setString(3, this.getFromDate());
						preparedStatement.setString(4, this.getToDate());
					}
					else
					{
					    String customerSearch = resolveCustomerSearchTerm(this.getCustomerNameCode());

					    sql = "SELECT "
					            + "customer_id,"
					            + "customer_name,"
					            + "DATE_FORMAT(entry_date,'%d-%m-%Y'),"
					            + "entry_time,"
					            + "payment_amount,"
					            + "payment_details, "
					            + "payment_received_by,"
					            + "entry_id "
					            + "FROM "
					            + "shop_customer_payment_master "
					            + "WHERE "
					            + "shop_id = ? "
					            + "AND "
					            + "shop_code = ? "
					            + "AND "
					            + "customer_id = ? "
					            + "AND "
					            + "entry_date BETWEEN "
					            + "STR_TO_DATE(?,'%d-%m-%Y') "
					            + "AND "
					            + "STR_TO_DATE(?,'%d-%m-%Y')";

					    preparedStatement = connection.prepareStatement(sql);

					    preparedStatement.setString(1, shopId);
					    preparedStatement.setString(2, shopCode);
					    preparedStatement.setString(3, customerSearch);
				    preparedStatement.setString(4, this.getFromDate());					   
				    preparedStatement.setString(5, this.getToDate());


					}
					
					
					
					resultSet = preparedStatement.executeQuery();
					int rowCount = 0;
					resultSet.last();
					rowCount = resultSet.getRow();
					resultSet.beforeFirst();
					
					double totalAmountValue = 0.0;
					
					if(rowCount > 0)
					{
						while(resultSet.next())
						{
							CustomerCreditColectionReportDAO reportDAO = new CustomerCreditColectionReportDAO();
							
							reportDAO.setCustomerId(resultSet.getString(1));
							reportDAO.setCustomerName(resultSet.getString(2));
							reportDAO.setEntryDate(resultSet.getString(3));
							reportDAO.setEntryTime(resultSet.getString(4));
							reportDAO.setAmount(resultSet.getString(5));
							
							reportDAO.setAmount(resultSet.getString(5));

							if (resultSet.getString(5) != null && !resultSet.getString(5).trim().equals("")) {
							    totalAmountValue += Double.parseDouble(resultSet.getString(5));
							}
							
							reportDAO.setComments(resultSet.getString(6));
							reportDAO.setEntryBy(resultSet.getString(7));
							reportDAO.setPaymentId(resultSet.getString(8));
							reportDAO.setKey(
									URLEncoder.encode(EncryptionDecryption.encrypt(
											
													resultSet.getString(1)+"#"
													+resultSet.getString(2)+"#"
													+resultSet.getString(3)+"#"
													+resultSet.getString(4)+"#"
													+resultSet.getString(5)+"#"
													+resultSet.getString(7)),"UTF-8"));
							
							//customerId#Customername#entryDate#time#Amount#EntryBy
							
							this.getCreditCollectionList().add(reportDAO);
							
						}
						
						this.setTotalAmount(String.format("%.2f", totalAmountValue));
						
						
							result = "success";
						
					}
					else
					{
						
							result = "error";
						
						addActionError(this.getText("message.error.datanotfoundforspecifiedinfo"));
					}
					
				}catch (SQLException e) {
					//e.printStackTrace();
					
						result = "error";
					
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || "+this.getText("message.error.detailscouldnotfound"));

				} catch (Exception e) {
					
						result = "error";
					
				addActionError(e.getMessage() +" || "+this.getText("message.error.detailscouldnotfound"));

			}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 SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	

	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	@Override  
	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}


	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<CustomerCreditColectionReportDAO> getCreditCollectionList() {
		return creditCollectionList;
	}

	public void setCreditCollectionList(List<CustomerCreditColectionReportDAO> creditCollectionList) {
		this.creditCollectionList = creditCollectionList;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	private String resolveCustomerSearchTerm(String customerNameCode) {
	    if (customerNameCode == null) {
	        return "";
	    }

	    String cleanedValue = customerNameCode.trim();

	    if (cleanedValue.isEmpty() || "Customer_Not_Found".equals(cleanedValue)) {
	        return "";
	    }

	    if (cleanedValue.contains("-")) {
	        return cleanedValue.split("-")[0].trim();
	    }

	    return cleanedValue;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub
		this.request = arg0;
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		this.response = arg0;
	}

	public List<String> getDownloadTypeList() {
		return downloadTypeList;
	}

	public void setDownloadTypeList(List<String> downloadTypeList) {
		this.downloadTypeList = downloadTypeList;
	}

	public String getDownloadType() {
		return downloadType;
	}

	public void setDownloadType(String downloadType) {
		this.downloadType = downloadType;
	}

	public String getCustomerNameCode() {
		return customerNameCode;
	}

	public void setCustomerNameCode(String customerNameCode) {
		this.customerNameCode = customerNameCode;
	}

	public String getTotalAmount() {
		return totalAmount;
	}

	public void setTotalAmount(String totalAmount) {
		this.totalAmount = totalAmount;
	}
	
	
}
