package com.reallinkbilling.add;



import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.db.GetDBConnection;


public class AddCustomerPaymentReminder extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6208411094853732491L;
	private SessionMap<String,Object> sessionMap;  
	
	private String paymentReminderAddDate;
	private String customerName;
	private Float outstandingAmount;
	private String paymentPromiseDate;
	private String comments;
	private String addSideBarJs;

	public String execute() {
		 
		String result = "login";
	
		
	        if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){ 
	        	addActionMessage(this.getText("message.error.plzloginfirst"));
	        	result = "error";
	        }  
	        else{
	        	
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;

				
	    		
	    		
	    		String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
				String sql = "";
				String db = (String)  this.getSessionMap().get("db");
				
				try
				{
					
					String custData [] = this.getCustomerName().split("-");
					connection = GetDBConnection.getDBConnection(db);
					
					
					sql = "SELECT "
							+ "entry_id "
							+ "FROM "
							+ "shop_customer_payment_reminder_master "
							+ "WHERE "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ? "
							+ "ORDER BY "
							+ "entry_id "
							+ "DESC LIMIT 1";
					
				
				preparedStatement = connection.prepareStatement(sql);
				preparedStatement.setString(1, shopId);
				preparedStatement.setString(2, shopCode);
				
				resultSet = preparedStatement.executeQuery();
				
				int nextEntryId = 0;
				
				if(resultSet.next())
				{
					if(!(resultSet.getString(1) == null))
					{
						nextEntryId = resultSet.getInt(1);
						
						
						nextEntryId = nextEntryId+1;
					}
					else
					{
						nextEntryId =1;
					}
				}
					
				if(resultSet != null)
				{
					resultSet.close();
					resultSet = null;
				}
				if(preparedStatement != null)
				{
					preparedStatement.close();
					preparedStatement = null;
				}
					
					sql = "INSERT INTO "
							+ "shop_customer_payment_reminder_master "
							+ "("
							+ "entry_id,"
							+ "shop_id,"
							+ "shop_code,"
							+ "reminder_add_date,"
							+ "customer_id,"
							+ "customer_name,"
							+ "customer_mobile_number,"
							+ "outsatnding_amount,"
							+ "payment_promise_date,"
							+ "comments,"
							+ "status) "
							+ "VALUES "
							+ "(?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?)";
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setInt(1, nextEntryId);
					preparedStatement.setString(2, shopId);
					preparedStatement.setString(3, shopCode);
					preparedStatement.setString(4, this.getPaymentReminderAddDate());
					preparedStatement.setString(5, custData[0]);
					preparedStatement.setString(6, custData[1]);
					preparedStatement.setString(7, custData[2]);
					preparedStatement.setFloat(8,this.getOutstandingAmount());
					preparedStatement.setString(9, this.getPaymentPromiseDate());
					preparedStatement.setString(10, this.getComments());
					preparedStatement.setString(11, "NOTIFY");
					int k = preparedStatement.executeUpdate();
					
					if(k>0)
					{
						result = SUCCESS;
						addActionMessage(this.getText("message.success.reminerDetailsAddedSuccessfullyFor")+custData[1]+"!");
						
						this.setCustomerName("");
						this.setOutstandingAmount(0.0F);
						this.setPaymentPromiseDate("");
						this.setComments("");
					}
					else
					{
						result = ERROR;
						addActionError(this.getText("message.error.reminderDetailsNotAdded"));
					}
					
					
				}
				catch (SQLException e) {
					e.printStackTrace();
					result = ERROR;					
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" ||"+this.getText("message.error.reminderDetailsNotAdded"));
				}
				catch (Exception e) {
					e.printStackTrace();
					result = ERROR;					
					addActionError(e.getMessage() +" || "+this.getText("message.error.reminderDetailsNotAdded"));
				}
				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;
	}
	
	@Override
	public void validate() {
	
	
		
		
		
	if(this.getPaymentReminderAddDate() == null || this.getPaymentReminderAddDate().equals(""))
	{
		addActionError(this.getText("message.error.olzProvideAddDate"));
	}

	if(!hasActionErrors())
	{
		//System.out.println("Customer Name Received: " + this.getCustomerName());

		if(this.getCustomerName() == null || this.getCustomerName().trim().equals(""))
		{
		    addActionError(this.getText("message.error.plzProvideCustomerNameCorrectly"));
		}
		else
		{
		    String s[] = this.getCustomerName().split("-", -1);

		   // System.out.println("Customer Name Parts: " + s.length);

		    if(s.length != 4)
		    {
		        addActionError(this.getText("message.error.plzProvideCustomerNameCorrectly"));
		    }
		}
	}
	
	if(!hasActionErrors())
	{
		if(this.getOutstandingAmount() == null || this.getOutstandingAmount().equals(""))
		{
			addActionError(this.getText("message.errorplzProvideCorrectOutstandingAmount"));
		}
	}
	
	if(!hasActionErrors())
	{
		if(this.getPaymentPromiseDate() == null || this.getPaymentPromiseDate().equals(""))
		{
			addActionError(this.getText("message.error.plzProvideNextPromiseDate"));
		}
	}
	
	}
	
	public String getPaymentReminderAddDate() {
		return paymentReminderAddDate;
	}


	public void setPaymentReminderAddDate(String paymentReminderAddDate) {
		this.paymentReminderAddDate = paymentReminderAddDate;
	}


	public String getCustomerName() {
		return customerName;
	}


	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}

	public Float getOutstandingAmount() {
		return outstandingAmount;
	}


	public void setOutstandingAmount(Float outstandingAmount) {
		this.outstandingAmount = outstandingAmount;
	}


	public String getPaymentPromiseDate() {
		return paymentPromiseDate;
	}


	public void setPaymentPromiseDate(String paymentPromiseDate) {
		this.paymentPromiseDate = paymentPromiseDate;
	}


	public String getComments() {
		return comments;
	}


	public void setComments(String comments) {
		this.comments = comments;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	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 getAddSideBarJs() {
		return addSideBarJs;
	}

	public void setAddSideBarJs(String addSideBarJs) {
		this.addSideBarJs = addSideBarJs;
	}
	

}