package com.reallinkbilling.delete;

import java.net.URLDecoder;
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.Date;
import java.util.HashMap;
import java.util.Map;

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.MaintainCloseingBalUtil;


public class DeleteCustPaymentEntry  extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 2334557252632403550L;
	
	
	private String paymentId;
	
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private String defaultValue;
	private SessionMap<String,Object> sessionMap;
	
	public String execute() throws Exception {
		String result = "login";
		
		     if(this.getSessionMap()==null || this.getSessionMap().get("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");
	    		
	    		
	    		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 userName = "";
					
					try
					{
						userName = user.split(" ")[0];
					}catch(Exception e)
					{
						userName = user;
					}
						
					
	    		try
	    		{
	    			
	    			String shopId = (String) this.getSessionMap().get("shopId");
		    		String shopCode = (String) this.getSessionMap().get("shopCode");
		    		
					connection = GetDBConnection.getDBConnection(db);
	    			
	    			if(this.getPaymentId() ==null || this.getPaymentId().equals(""))
	    			{
	    				addActionError("URL Tampered! Please try again!");
	    				result = "error";
	    			}
	    			//custid + entryid + date + amount
	    			
	    			
	    			String keyData [] = EncryptionDecryption.decrypt(URLDecoder.decode(this.getPaymentId(),"UTF-8")).split("#");
	    			
	    			if(!hasActionErrors())
	    			{
	    				
	    				sql = "SELECT "
								+ "account_credit_debit_id "
								+ "FROM "
								+ "shop_customer_payment_master "
								+ "WHERE "
	    						+ "entry_id = ? "
	    						+ "AND "
	    						+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? ";
						
						preparedStatement = connection.prepareStatement(sql);
						
						preparedStatement.setString(1, keyData[1]);
	    				preparedStatement.setString(2, shopId);
	    				preparedStatement.setString(3, shopCode);
	    				
						resultSet = preparedStatement.executeQuery();
						
						
						if(resultSet.next()){
							String accCrditDebitId = resultSet.getString(1);
							if(resultSet != null)
							{
								resultSet.close();
								resultSet = null;
							}
							if(preparedStatement != null)
							{
								preparedStatement.close();
								preparedStatement = null;
							}
							boolean isCloseingBalMaintained = false;
						    
							if(accCrditDebitId != null && !accCrditDebitId.equals("") )
							{
								
							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, accCrditDebitId);
							preparedStatement.setString(2, shopId);
							preparedStatement.setString(3, shopCode);
							
							resultSet = preparedStatement.executeQuery();
							
							int m = 0;
							String paymentType = null;
							String entryDate1 = null;
							String accountId = null;
							Float amount = null;
							
							if(resultSet.next())
							{
								accountId = resultSet.getString(2);
							    paymentType = resultSet.getString(6);
								 entryDate1 = resultSet.getString(4);
								 amount = resultSet.getFloat(7);
								 
								PreparedStatement  insertIntoDeletedPSMT = null;
								
								String inertDeletedSQL = "INSERT "
										+ "INTO "
										+ "bank_account_credit_debit_deleted_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, accCrditDebitId);
								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, time);
								insertIntoDeletedPSMT.setString(8, resultSet.getString(6));
								insertIntoDeletedPSMT.setFloat(9, resultSet.getFloat(7));
								insertIntoDeletedPSMT.setString(10, resultSet.getString(8));
								insertIntoDeletedPSMT.setString(11, userName);
								insertIntoDeletedPSMT.setString(12, resultSet.getString(10));
								
								  m = insertIntoDeletedPSMT.executeUpdate();
								
								if(insertIntoDeletedPSMT != null)
								{
									insertIntoDeletedPSMT.close();
									insertIntoDeletedPSMT = null;
								}
								
							}
							
							
							if(resultSet != null)
							{
								resultSet.close();
								resultSet = null;
							}
							if(preparedStatement != null)
							{
								preparedStatement.close();
								preparedStatement = null;
							}
							
							if(m>0)
							{
								

							
							sql = "DELETE "
									+ "FROM "
									+ "bank_account_credit_debit_master "
									+ "WHERE "
									+ "entry_id = ? "
									+ "AND "
									+ "shop_id = ? "
									+ "AND "
									+ "shop_code = ? ";
							
							preparedStatement = connection.prepareStatement(sql);
							preparedStatement.setString(1, accCrditDebitId);
							preparedStatement.setString(2, shopId);
							preparedStatement.setString(3, shopCode);
							
							int k = preparedStatement.executeUpdate();
							
							if(k>0  )
							{
								SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
								Date parsedDate = null;

								try {
								    parsedDate = inputDateFormat.parse(entryDate1); 
								} catch (ParseException e) {
								    e.printStackTrace();  
								}

								if (parsedDate != null) {
								     SimpleDateFormat outputDateFormat = new SimpleDateFormat("dd-MM-yyyy");
								    String formattedDate = outputDateFormat.format(parsedDate); 
								   
								    if (paymentType.equals("CREDIT")) {
								    	isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(accountId, "DEBIT", formattedDate, amount, userName, connection, this.getSessionMap());
								    } else {
								    	isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(accountId, "CREDIT", formattedDate, amount, userName, connection, this.getSessionMap());
								    }
								}

							}
							}
							}
							
							
						}
	    				
						
						
	    				sql ="DELETE "
	    						+ "FROM "
	    						+ "shop_customer_payment_master "
	    						+ "WHERE "
	    						+ "customer_id = ? "
	    						+ "AND "
	    						+ "entry_id = ? "
	    						+ "AND "
	    						+ "entry_date = STR_TO_DATE(?,'%d-%m-%Y') "	    						
	    						+ "AND "
	    						+ "shop_id = ? "
	    						+ "AND "
	    						+ "shop_code = ? ";
	    				
	    				preparedStatement = connection.prepareStatement(sql);
	    				preparedStatement.setString(1, keyData[0]);
	    				preparedStatement.setString(2, keyData[1]);
	    				preparedStatement.setString(3, keyData[2]);
	    				preparedStatement.setString(4, shopId);
	    				preparedStatement.setString(5, shopCode);
	    				
	    				
	    				
	    				int k = preparedStatement.executeUpdate();
	    				
	    				if(k>0)
	    				{
	    					addActionMessage("Customer payment entry deleted successfully!");
	    					result = "success";
	    				}
	    				else
	    				{
	    					addActionError("Customer payment entry not deleted! 1");
	    					result = "error";
	    				}
	    			}
	    			
	    			
	    			
	    		}
	    		catch (SQLException e) {
	    			e.printStackTrace();
	    			result = "error";
	    			
	    			addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Customer payment entry not deleted!");
	    		}
	    		catch (Exception e) {
	    			e.printStackTrace();
	    			result = "error";
	    			addActionError(e.getMessage() +" || Customer payment entry not deleted!");
				}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 String getPaymentId() {
		return paymentId;
	}

	public void setPaymentId(String paymentId) {
		this.paymentId = paymentId;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	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 getDefaultValue() {
		return defaultValue;
	}

	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}


	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;  
	}

	
}
