package com.reallinkbilling.add;


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.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.GetNewIdForNewEntry;
import com.reallinkbilling.utils.GetAccountListForDrCr;
import com.reallinkbilling.utils.MaintainCloseingBalUtil;
import com.opensymphony.xwork2.ActionSupport;

public class AddEmployeePaymentDetails extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6208411094853732491L;
	private SessionMap<String,Object> sessionMap;
	private String employeePaymentDate;
	private String employeeMobile;
	private String employeeName;
	private Float amount;
	private String typeOfPayment;
	private String details;
	private String key;
	private List<String> paymentTypeList = new ArrayList<String>();
	private String addSideBarJs;
	private Map<String,String> accountList = new LinkedHashMap<String,String>();
	private String accountId;
	private boolean paymentSaved;
	private String paymentId;

	
	public String execute() {
		 
		String result = "login";
	
		
	        if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){ 
	        	addActionMessage("Please Logout and Login again !");
	        	result = "login";
	        }  
	        else{
	        		
	        	
				String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    	
				Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
			
					
				String sql = "";
				String db = (String)  this.getSessionMap().get("db");
				
				try
				{
					connection = GetDBConnection.getDBConnection(db);
					connection.setAutoCommit(false);
					
					String employeeId = EncryptionDecryption.decrypt(this.getKey());
					
					 
					int newPaymentId = GetNewIdForNewEntry.getNewIdForNewEntry
							("shop_employee_payment_details", "entry_id", this.getSessionMap(), connection);
				
					
					SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
		        	
				 	java.util.Date date = new java.util.Date();
		    	    long t = date.getTime();	        	     
		    	    java.sql.Time time = new java.sql.Time(t);
		    	    
		    		String user = (String) this.getSessionMap().get("userFullName");
					String shortName = "";
					
					try
					{
						shortName = user.split(" ")[0];
					}catch(Exception e)
					{
						shortName = user;
					}
					
					sql = "INSERT INTO "
							+ "shop_employee_payment_details "
							+ "("
							+ "entry_id,"
							+ "entry_date,"
							+ "entry_time,"
							+ "shop_id,"
							+ "shop_code,"
							+ "payment_date,"
							+ "employee_id,"
							+ "employee_name,"
							+ "payment_amount,"
							+ "payment_type,"
							+ "payment_details,"
							+ "entry_by,"
							+ "amount_debit_account_id) "
							+ "VALUES "
							+ "(?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?)";
					
					preparedStatement = connection.prepareStatement(sql);
					
					preparedStatement.setInt(1, newPaymentId);
					preparedStatement.setString(2, dateFormat.format(date));
					preparedStatement.setTime(3, time);
					preparedStatement.setString(4, shopId);
					preparedStatement.setString(5, shopCode);
					preparedStatement.setString(6, this.getEmployeePaymentDate());
					preparedStatement.setString(7, employeeId);
					preparedStatement.setString(8, this.getEmployeeName());
					preparedStatement.setFloat(9, this.getAmount());
					preparedStatement.setString(10, this.getTypeOfPayment());
					preparedStatement.setString(11, this.getDetails().trim().toUpperCase());
					preparedStatement.setString(12, shortName);
					preparedStatement.setString(13, this.getAccountId());
					
					int k = preparedStatement.executeUpdate();
					
					if(k>0)
					{
						
    	        		if(preparedStatement!= null)
    	        		{
    	        			preparedStatement.close();
    	        			preparedStatement = null;
    	        		}
						sql = "SELECT "
								+ "entry_id "
								+ "FROM "
								+ "bank_account_credit_debit_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 entryAccountId = 1;
				
					if(resultSet.next())
					{
						if(!(resultSet.getString(1) == null))
						{
							entryAccountId = Integer.parseInt(resultSet.getString(1));
							entryAccountId = entryAccountId + 1;
							
						}
						
					}
					else
					{	entryAccountId =1;
						
					}
					
	        		
        				
        				if(resultSet != null)
    	        		{
    	        			resultSet.close();
    	        			resultSet = null;
    	        		}
    	        		if(preparedStatement!= null)
    	        		{
    	        			preparedStatement.close();
    	        			preparedStatement = null;
    	        		}
        				
    	        		String accountNumber = "";
    	        		sql = "SELECT "
    	        				+ "account_number	 "
    	        				+ "FROM "
    	        				+ "bank_account "
    	        				+ "WHERE "
    	        				+ "account_id  = ?"
    	        				+ "AND "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? ";
    	        			
    	        		preparedStatement = connection.prepareStatement(sql);
    	        		
    	        		preparedStatement.setString(1, this.getAccountId());
    	        		preparedStatement.setString(2, shopId);
    					preparedStatement.setString(3, shopCode);
    					
    	        		resultSet = preparedStatement.executeQuery();
    	        		if(resultSet.next())
    	        		{
    	        			accountNumber = resultSet.getString(1);
    	        		}
    	        		

    	        		if(resultSet != null)
    	        		{
    	        			resultSet.close();
    	        			resultSet = null;
    	        		}
    	        		if(preparedStatement!= null)
    	        		{
    	        			preparedStatement.close();
    	        			preparedStatement = null;
    	        		}
    						
    						sql = "INSERT "
    								+ "INTO "
    								+ "bank_account_credit_debit_master "
    								+ "("
    								+ "entry_id,"
    								+ "shop_id,"
    		        				+ "shop_code,"
    		        				+ "account_id,"
    								+ "account_number,"
    								+ "entry_date,"
    								+ "entry_time,"
    								+ "entry_type,"
    								+ "amount,"
    								+ "payment_type,"
    								+ "entry_by,"
    								+ "entry_details) "
    								+ "VALUES "
    								+ "(?,?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?)";
    						
    						preparedStatement = connection.prepareStatement(sql);
    						
    						preparedStatement.setInt(1, entryAccountId);
    						preparedStatement.setString(2, shopId);
    		        		preparedStatement.setString(3, shopCode);
    		        		preparedStatement.setString(4, this.getAccountId());
    						preparedStatement.setString(5, accountNumber);
    						preparedStatement.setString(6, this.getEmployeePaymentDate());
    						preparedStatement.setTime(7, time);
    						preparedStatement.setString(8, "DEBIT");
    						preparedStatement.setFloat(9, this.getAmount());
    						preparedStatement.setString(10, this.getTypeOfPayment());
    						preparedStatement.setString(11, shortName);
    						preparedStatement.setString(12, "EMPLOYEE PAYMENT TO "+this.getEmployeeName().trim().toUpperCase());
    						
    						int rowInsetred = preparedStatement.executeUpdate();
        				
    						
    						boolean isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(this.getAccountId(),"DEBIT", this.getEmployeePaymentDate(), this.getAmount(), shortName, connection, this.getSessionMap());
							
    						if(rowInsetred > 0 && isCloseingBalMaintained)
    						{
    							
    							sql = "UPDATE "
        	        					+ "shop_employee_payment_details "
        	        					+ "SET "
        	        					+ "credit_debit_id = ? "
        	        					+ "WHERE "
    									+ "entry_id = ? "
    									+ "AND "
    									+ "shop_id = ? "
    									+ "AND "
    									+ "shop_code = ? ";
        	        			
        	        			
	    						preparedStatement = connection.prepareStatement(sql);
	    						
	    						preparedStatement.setInt(1, entryAccountId);
	    						preparedStatement.setInt(2, newPaymentId);
	    						preparedStatement.setString(3, shopId);
	    		        		preparedStatement.setString(4, shopCode);
	    		        		
	    						int rowCreditDebitIdInsetred = preparedStatement.executeUpdate();
	        				
	    						
	    						
	    						if(rowCreditDebitIdInsetred > 0 )
	    						{
	    							this.setPaymentSaved(true);
	    							this.setPaymentId(""+newPaymentId);
	    							
	    							
	    							
	    							
	    							connection.commit();
	    	        				result = SUCCESS;
	    							addActionMessage("Employee payment details added successfully!");
	    						}
	    						
	    						
    	        				
    						}
    						else
    						{
    							connection.rollback();
    							result = ERROR;
    							addActionError("Employee Payment Could Not Be Added Please Try Again !");
    						}
        			
        			
						
					}
					else
					{
						connection.rollback();
						result = ERROR;
						addActionError("Payment details not added! Please try again!");
					}
					
					
					
				}
				catch (SQLException e) {
					result = "error";
					
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Something Went Wrong !");
				}
				catch (Exception e) {
						result = "error";
					
					addActionError(e.getMessage() +" || 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;
	}
	
	@Override
	public void validate() {
		
		if(this.getAmount() == null || this.getAmount().equals(""))
		{
			addActionError("Please provide correct amount!");
		}
		
		paymentTypeList.add("CASH");
    	paymentTypeList.add("UPI");
    	paymentTypeList.add("RTGS");
    	paymentTypeList.add("NEFT");
    	paymentTypeList.add("CHEQUE");
    	
    	this.setAccountList(GetAccountListForDrCr.getAccountList(this.getSessionMap()));     
    	
    	if(!hasActionErrors())
    	{
    		if(this.getTypeOfPayment() == null || this.getTypeOfPayment().equals(""))
    		{
    			addActionError("Please Provide Type Of Payment !");
    		}
    	}
    	
    		
    	if(!hasActionErrors()){
    		if(this.getAccountId() == null || this.getAccountId().equals(""))
    		{
    			addActionError("Please Select Account For Debit Entry !");
    		}
    	}
    	
    	
		this.setAddSideBarJs("FALSE");
	}
	
	
	public String getEmployeePaymentDate() {
		return employeePaymentDate;
	}


	public void setEmployeePaymentDate(String employeePaymentDate) {
		this.employeePaymentDate = employeePaymentDate;
	}


	public String getEmployeeMobile() {
		return employeeMobile;
	}


	public void setEmployeeMobile(String employeeMobile) {
		this.employeeMobile = employeeMobile;
	}


	public String getEmployeeName() {
		return employeeName;
	}


	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}



	public Float getAmount() {
		return amount;
	}


	public void setAmount(Float amount) {
		this.amount = amount;
	}


	public String getTypeOfPayment() {
		return typeOfPayment;
	}


	public void setTypeOfPayment(String typeOfPayment) {
		this.typeOfPayment = typeOfPayment;
	}


	public String getDetails() {
		return details;
	}


	public void setDetails(String details) {
		this.details = details;
	}


	public String getKey() {
		return key;
	}


	public void setKey(String key) {
		this.key = key;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


	public List<String> getPaymentTypeList() {
		return paymentTypeList;
	}

	public void setPaymentTypeList(List<String> paymentTypeList) {
		this.paymentTypeList = paymentTypeList;
	}

	public String getAddSideBarJs() {
		return addSideBarJs;
	}

	public void setAddSideBarJs(String addSideBarJs) {
		this.addSideBarJs = addSideBarJs;
	}

	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;  
	}

	public Map<String, String> getAccountList() {
		return accountList;
	}

	public void setAccountList(Map<String, String> accountList) {
		this.accountList = accountList;
	}

	public String getAccountId() {
		return accountId;
	}

	public void setAccountId(String accountId) {
		this.accountId = accountId;
	}

	public boolean isPaymentSaved() {
		return paymentSaved;
	}

	public void setPaymentSaved(boolean paymentSaved) {
		this.paymentSaved = paymentSaved;
	}

	public String getPaymentId() {
		return paymentId;
	}

	public void setPaymentId(String paymentId) {
		this.paymentId = paymentId;
	}
	

}



