package com.reallinkbilling.update;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
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.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.utils.GetAccountListForDrCr;
import com.reallinkbilling.utils.MaintainCloseingBalUtil;

public class UpdateEmployeePaymentDetails extends ActionSupport implements SessionAware{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3152784180681908197L;

	
	private SessionMap<String,Object> sessionMap;  
	private String key;
	private String laborPaymentDate;
	private String laborName;
	private String laborMobile;
	private Float laborOutstandingAmount;
	private Float amount;
	private String typeOfPayment;
	private String accountId;
	
	private List<String> paymentTypeList = new ArrayList<String>();
	private Map<String,String> accountList = new LinkedHashMap<String,String>();
	private String details;
	private HttpSession session;
	private String addSideBarJs;
	
	private String fromDate;
	private String toDate;
	private String entryId;
	
	public String execute() {
		 
		String result = "login";
	
		
	        if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){ 
	        	addActionMessage(this.getText("message.error.plzloginfirst"));
	        	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 entryId = EncryptionDecryption.decrypt(this.getEntryId());
	    			
					
	    			String user = (String) session.getAttribute("userFullName");
					String shortName = "";
					
					try
					{
						shortName = user.split(" ")[0];
					}catch(Exception e)
					{
						shortName = user;
					}
					
					java.util.Date date = new java.util.Date();
		      	      long t = date.getTime();	        	     
		      	      java.sql.Time time = new java.sql.Time(t);
					
						
		      	      
		      	      

		    				sql = "SELECT "
	  							+ "credit_debit_id "
	  							+ "FROM "
	  							+ "shop_employee_payment_details "
	  							+ "WHERE "
	    						+ "entry_id = ? "
	    						+ "AND "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? ";
  					
  					preparedStatement = connection.prepareStatement(sql);
  					
  					    preparedStatement.setString(1, entryId);
	    				preparedStatement.setString(2, shopId);
	    				preparedStatement.setString(3, shopCode);
	    				
  					resultSet = preparedStatement.executeQuery();
  					
  					
  					if(resultSet.next()){
  						String crditDebitId = resultSet.getString(1);
  						
  						
  						
  						if(resultSet != null)
						{
							resultSet.close();
							resultSet = null;
						}
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
						
						
						sql = "SELECT "
								+ "entry_id,"
								+ "account_id,"
								+ "account_number,"
								+ "entry_date,"
								+ "entry_time,"
								+ "entry_type,"
								+ "amount,"
								+ "payment_type,"
								+ "entry_by,"
								+ "entry_details "
								+ "FROM "
								+ "bank_account_credit_debit_master "
								+ "WHERE "
								+ "entry_id = ? "
								+ "AND "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? ";
						
						preparedStatement = connection.prepareStatement(sql);
						preparedStatement.setString(1, crditDebitId);
						preparedStatement.setString(2, shopId);
						preparedStatement.setString(3, shopCode);

						
						resultSet = preparedStatement.executeQuery();
						
						int m = 0;
						if(resultSet.next())
						{
							
							PreparedStatement  insertIntoDeletedPSMT = null;
							
							String inertDeletedSQL = "INSERT "
									+ "INTO "
									+ "bank_account_credit_debit_updated_entry_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 "
									+ "(?,?,?,?,?,?,?,?,?,?,?,?)";
							
							insertIntoDeletedPSMT = connection.prepareStatement(inertDeletedSQL);
							
							insertIntoDeletedPSMT.setString(1, crditDebitId);
							insertIntoDeletedPSMT.setString(2, shopId);
							insertIntoDeletedPSMT.setString(3, shopCode);
							insertIntoDeletedPSMT.setString(4, resultSet.getString(2));
							insertIntoDeletedPSMT.setString(5, resultSet.getString(3));
							insertIntoDeletedPSMT.setString(6, resultSet.getString(4));
							insertIntoDeletedPSMT.setTime(7, resultSet.getTime(5));
							insertIntoDeletedPSMT.setString(8, resultSet.getString(6));
							insertIntoDeletedPSMT.setFloat(9, this.getAmount());
							insertIntoDeletedPSMT.setString(10, resultSet.getString(8));
							insertIntoDeletedPSMT.setString(11, shortName);
							insertIntoDeletedPSMT.setString(12, resultSet.getString(10));
							
							   
							  m = insertIntoDeletedPSMT.executeUpdate();
							  
							  String paymentType = resultSet.getString(6);
							  
							  
							  SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
								Date parsedDate = null;

								try {
								    parsedDate = inputDateFormat.parse(resultSet.getString(4)); 
								} catch (ParseException e) {
								    e.printStackTrace();  
								}

								if (parsedDate != null) {
								     SimpleDateFormat outputDateFormat = new SimpleDateFormat("dd-MM-yyyy");
								    String formattedDate = outputDateFormat.format(parsedDate); 
					
								    
							 
							    
							    
							  boolean isCloseingBalMaintained = false;
							  
							  if (paymentType.equals("CREDIT")) {
							   isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(resultSet.getString(2),"DEBIT", formattedDate, resultSet.getFloat(7), shortName, connection, this.getSessionMap());
							  }else {
								   isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(resultSet.getString(2),"CREDIT", formattedDate, resultSet.getFloat(7), shortName, connection, this.getSessionMap());
								  
							  }
								}
							  
							if(insertIntoDeletedPSMT != null)
							{
								insertIntoDeletedPSMT.close();
								insertIntoDeletedPSMT = null;
							}
							
						}
						if(resultSet != null)
						{
							resultSet.close();
							resultSet = null;
						}
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
				
					
							sql = "UPDATE "
									+ "shop_employee_payment_details "
									+ "SET "
									+ "payment_date = STR_TO_DATE(?,'%d-%m-%Y'),"
									+ "entry_time = ?,"
									+ "employee_id = ?,"
									+ "employee_name = ?,"
									+ "payment_amount = ?,"
									+ "payment_type = ?,"
									+ "amount_debit_account_id = ?,"
									+ "payment_details = ?,"
									+ "entry_by = ? "
									+ "WHERE "
									+ "entry_id = ?"
									+ "AND "
									+ "shop_id = ? "
									+ "AND "
									+ "shop_code = ? ";
						
							
							
							
							preparedStatement = connection.prepareStatement(sql);
							
						
							preparedStatement.setString(1, this.getLaborPaymentDate());
							preparedStatement.setTime(2, time);
							preparedStatement.setString(3, EncryptionDecryption.decrypt(this.getKey()));
							preparedStatement.setString(4, this.getLaborName());
							preparedStatement.setFloat(5, this.getAmount());
							preparedStatement.setString(6, this.getTypeOfPayment());
							preparedStatement.setString(7, this.getAccountId());
							preparedStatement.setString(8, this.getDetails());							
							preparedStatement.setString(9, shortName);
							preparedStatement.setString(10, entryId);
							preparedStatement.setString(11, shopId);
							preparedStatement.setString(12, shopCode);
							
							int	rowCount = preparedStatement.executeUpdate();
							
					
					
					
					
		        	
					if(rowCount>0)	
	        		{
						
    	        		
    	        		
						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);
    	        		}
    	        		

						
						sql = "UPDATE "
								+ "bank_account_credit_debit_master "
								+ "SET "
								+ "entry_date = STR_TO_DATE(?,'%d-%m-%Y'),"
								+ "entry_time = ?,"
								+ "account_id = ?,"
								+ "account_number = ?,"
								+ "entry_type = ?,"
								+ "amount = ?,"
								+ "payment_type = ?,"
								+ "entry_by = ?,"
								+ "entry_details = ? "
								+ "WHERE "
								+ "entry_id = ? "
								+ "AND "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? ";
					
						
						
						
						preparedStatement = connection.prepareStatement(sql);
						
					
						preparedStatement.setString(1, this.getLaborPaymentDate());
						preparedStatement.setTime(2, time);
						preparedStatement.setString(3, this.getAccountId());
						preparedStatement.setString(4, accountNumber);
						preparedStatement.setString(5, "DEBIT");
						preparedStatement.setFloat(6, this.getAmount());
						preparedStatement.setString(7, this.getTypeOfPayment());							
						preparedStatement.setString(8, shortName);
						preparedStatement.setString(9, "UPDATED EMPLOYEE PAYMENT TO "+this.getLaborName().trim().toUpperCase());
						preparedStatement.setString(10, crditDebitId);
						preparedStatement.setString(11, shopId);
						preparedStatement.setString(12, shopCode);
						
						int	count = preparedStatement.executeUpdate();
						
						boolean isCloseingBalMaintained1 = MaintainCloseingBalUtil.maintainCloseingBal(this.getAccountId(),"DEBIT", this.getLaborPaymentDate(), this.getAmount(), shortName, connection, this.getSessionMap());
							
						if(count > 0 && isCloseingBalMaintained1)
						{
							connection.commit();
							result = SUCCESS;
							 addActionMessage("Employee Payment Details Updated Successfully !"); 
						}
	        	
				
	        			
						
						
	        		}
					else
					{
						connection.rollback();
						result = "error";
        				addActionError("Employee Payment Details Could Not Updated (cheque) Please Try Again !");
					}
					
					  
  						
  					}
				}catch (SQLException e) {
					e.printStackTrace();
					try {
						connection.rollback();
					} catch (SQLException e1) {}
					result = ERROR;
					addActionError("Details Not Updated Please Try Again !");
				} catch (Exception e) {
					
					result = ERROR;
					addActionError("Details Not Updated Please Try Again !");
				}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 void validate() {
      this.setAddSideBarJs("FALSE");
		
		session=ServletActionContext.getRequest().getSession(false);
    	paymentTypeList.add("CASH");
    	paymentTypeList.add("UPI");
    	paymentTypeList.add("RTGS");
    	paymentTypeList.add("NEFT");
    	
    	this.setAccountList(GetAccountListForDrCr.getAccountList(this.getSessionMap()));     
    	
    	
    	if(this.getAmount() == null || this.getAmount().equals("") || this.getAmount()<0)
    	{
    		addActionError("Please Provide Correct Amount !");
    	}
    	
    	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 !");
    		}
    	}
    	
    	
	}
	
	public String getKey() {
		return key;
	}



	public void setKey(String key) {
		this.key = key;
	}



	

	public static long getSerialversionuid() {
		return serialVersionUID;
	}



	

	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 List<String> getPaymentTypeList() {
		return paymentTypeList;
	}



	public void setPaymentTypeList(List<String> paymentTypeList) {
		this.paymentTypeList = paymentTypeList;
	}



	public HttpSession getSession() {
		return session;
	}



	public void setSession(HttpSession session) {
		this.session = session;
	}



	public String getAddSideBarJs() {
		return addSideBarJs;
	}



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



	public String getAccountId() {
		return accountId;
	}



	public void setAccountId(String accountId) {
		this.accountId = accountId;
	}



	

	public Map<String, String> getAccountList() {
		return accountList;
	}



	public void setAccountList(Map<String, String> accountList) {
		this.accountList = accountList;
	}



	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 getLaborPaymentDate() {
		return laborPaymentDate;
	}



	public void setLaborPaymentDate(String laborPaymentDate) {
		this.laborPaymentDate = laborPaymentDate;
	}



	


	public String getLaborName() {
		return laborName;
	}



	public void setLaborName(String laborName) {
		this.laborName = laborName;
	}



	public String getLaborMobile() {
		return laborMobile;
	}



	public void setLaborMobile(String laborMobile) {
		this.laborMobile = laborMobile;
	}



	public Float getLaborOutstandingAmount() {
		return laborOutstandingAmount;
	}



	public void setLaborOutstandingAmount(Float laborOutstandingAmount) {
		this.laborOutstandingAmount = laborOutstandingAmount;
	}



	public String getDetails() {
		return details;
	}



	public void setDetails(String details) {
		this.details = details;
	}



	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 String getEntryId() {
		return entryId;
	}



	public void setEntryId(String entryId) {
		this.entryId = entryId;
	}



	
 
}



