package com.reallinkbilling.add;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
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.reallinkbilling.resource.GetNewIdForNewEntry;
import com.opensymphony.xwork2.ActionSupport;
import com.stonecrusher.infrawhatsappmsg.CheckBalance;
import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.stonecrusher.infrawhatsappmsg.SendWhatsAppMessage;
import com.reallinkbilling.utils.GetAccountListForDrCr;
import com.reallinkbilling.utils.GetCustomerCreditAmountById;
import com.reallinkbilling.utils.GetTypeOfPaymentList;
import com.reallinkbilling.utils.InsertBankAccDrCrEntry;
import com.reallinkbilling.utils.MaintainCloseingBalUtil;
import com.reallinkbilling.utils.WhatsAppSettingsUtil;
import com.realllinkbilling.message.AddTextLocalResponseToDB;
import com.realllinkbilling.message.SendTextLocalMessage;

public class AddCustomerPaymentDetails extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -9028271818197958108L;
	
	
	private HttpSession session;
	private String key;
	private String paymentDate;
	private String custName;
	private String amount;
	private String paymentDetails;
	private String outstandingAmount;
	private boolean sendSMS;
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private String defaultValue;
	private SessionMap<String,Object> sessionMap;  
	
	private List<String> paymentTypeList = new ArrayList<String>();
	private String typeOfPayment;
	private String accountId;
	private Map<String,String> accountList = new LinkedHashMap<String,String>();
	private boolean paymentSaved;
	private String paymentId;
	
	
	public String execute() throws IOException{
		 
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        else{
	        	
	        	this.getCustomerSearchOptionList().put("BYNAME", "BY NAME");
	        	this.getCustomerSearchOptionList().put("BYMOBILE", "BY MOBILE");
	        	this.getCustomerSearchOptionList().put("BYADDRESS","BY ADDRESS");
				this.setCustomerSearchOption("BYNAME");
				this.setDefaultValue("BYNAME");
	        	
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
				
				String sql = "";
				String db = (String) session.getAttribute("db");
				
				String customerMobileNumber="";
					try
					{
						
						
						String shopId = (String) this.getSessionMap().get("shopId");
			    		String shopCode = (String) this.getSessionMap().get("shopCode");

		        		String fullUserName = (String) this.getSessionMap().get("userFullName");
			        	
			        	String splitUserName [] = new String[5];
			        	
						String custId = EncryptionDecryption.decrypt(getKey());
						
						String billedBy = "";
			        	try
			        	{
			        		splitUserName = fullUserName.split(" ");
			        		billedBy = splitUserName[0];
			        		
			        	}catch(Exception e)
			        	{
			        		billedBy =fullUserName;
			        	}
			        	
			        	java.util.Date date = new java.util.Date();
		        	      long t = date.getTime();	        	     
		        	      java.sql.Time time = new java.sql.Time(t);
			        	
						connection = GetDBConnection.getDBConnection(db);
						connection.setAutoCommit(false);
						
						float openingBal = 0.0F;
	       				
	       				PreparedStatement getOpeningBalPSMT = null;
	       				ResultSet getOpeningBalRS = null;
	       				String sqlOpeningBal = "SELECT "
	       						+ "opening_balance "
	       						+ "FROM "
	       						+ "shop_cust_close_open_bal_master  "
	       						+ "WHERE "
	       						+ "customer_id = ? "
	       						+ "AND "
	       						+ "shop_id = ? "
	       						+ "AND "
	       						+ "shop_id = ? ";
	       				
	       				getOpeningBalPSMT = connection.prepareStatement(sqlOpeningBal);
	       				
	       				getOpeningBalPSMT.setString(1, custId);
	       				getOpeningBalPSMT.setString(2, shopId);
	       				getOpeningBalPSMT.setString(3, shopCode);
	       				
	       				getOpeningBalRS = getOpeningBalPSMT.executeQuery();
	       				
	       				if(getOpeningBalRS.next())
	       				{
	       					openingBal = getOpeningBalRS.getFloat(1);
	       				}
	       			
	       				if(getOpeningBalRS != null)
	       				{
	       					getOpeningBalRS.close();
	       					getOpeningBalRS = null;
	       				}
	       				
	       				if(getOpeningBalPSMT != null)
	       				{
	       					getOpeningBalPSMT.close();
	       					getOpeningBalPSMT = null;
	       				}
	       				
	       				
						
						sql = "SELECT "
								+ "mobile_number "
								+ "FROM "
								+ "shop_customer_master "
								+ "WHERE "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? "
								+ "AND "
								+ "customer_id = ?";
						
						preparedStatement = connection.prepareStatement(sql);
						
						preparedStatement.setString(1, shopId);
						preparedStatement.setString(2, shopCode);
						preparedStatement.setString(3, custId);
						
						resultSet = preparedStatement.executeQuery();
						
						if(resultSet.next())
						{
							customerMobileNumber = resultSet.getString(1);
						}
						
						int newEntryId = GetNewIdForNewEntry.getNewIdForNewEntry
								("shop_customer_payment_master", "entry_id", this.getSessionMap(), connection);
					
				
						
						sql = "INSERT INTO "
								+ "shop_customer_payment_master "
								+ "("
								+ "entry_id,"
								+ "shop_id,"
								+ "shop_code,"
								+ "entry_date,"
								+ "entry_time,"
								+ "customer_id,"
								+ "customer_name,"
								+ "payment_amount,"
								+ "payment_details,"
								+ "payment_received_by) "
								+ "VALUES "
								+ "(?,?,?,STR_TO_DATE(?, '%d-%m-%Y'),?,?,?,?,?,?)";
						
						
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
						
						preparedStatement = connection.prepareStatement(sql);
						
						preparedStatement.setInt(1, newEntryId);
						preparedStatement.setString(2, shopId);
						preparedStatement.setString(3, shopCode);
						preparedStatement.setString(4, this.getPaymentDate());
						preparedStatement.setTime(5, time);
						preparedStatement.setString(6, custId);
						preparedStatement.setString(7, this.getCustName());
						preparedStatement.setString(8, this.getAmount());
						preparedStatement.setString(9, this.getPaymentDetails());
						preparedStatement.setString(10, billedBy);
						
						int rowsInserted = preparedStatement.executeUpdate();
						
						
					
						
						
						
						if(rowsInserted>0 )
						{
							if(preparedStatement != null)
							{
								preparedStatement.close();
								preparedStatement = null;
							}
							
							if(resultSet != null)
							{
								resultSet.close();
								resultSet = null;
							}
							
							int rowCreditDebitIdInsetred = 0;
			        		
							if(!this.getTypeOfPayment().equals("CHEQUE") )
		        			{
			        		if(this.getAccountId() != null && !this.getAccountId().equals("") && this.getTypeOfPayment() != null && !this.getTypeOfPayment().equals(""))
				    		{
							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 entryId = 1;
					
						if(resultSet.next())
						{
							if(!(resultSet.getString(1) == null))
							{
								entryId = Integer.parseInt(resultSet.getString(1));
								entryId = entryId + 1;
								
							}
							
						}
						else
						{	entryId =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, accountId);
			    		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, entryId);
							preparedStatement.setString(2, shopId);
							preparedStatement.setString(3, shopCode);
							preparedStatement.setString(4, accountId);
							preparedStatement.setString(5, accountNumber);
							preparedStatement.setString(6, this.getPaymentDate());
							preparedStatement.setTime(7, time);
							preparedStatement.setString(8, "CREDIT");
							preparedStatement.setString(9, this.getAmount());
							preparedStatement.setString(10, typeOfPayment);
							preparedStatement.setString(11, billedBy);
							preparedStatement.setString(12, "PAID BY "+this.getCustName()+" Against Outstanding amount: "+this.getOutstandingAmount());
							
							
							int rowInsetred = preparedStatement.executeUpdate();
							boolean isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(this.getAccountId(),"CREDIT", this.getPaymentDate(),  Float.parseFloat(this.getAmount()), billedBy, connection, this.getSessionMap());
							
							if(isCloseingBalMaintained && rowInsetred > 0)
							{
								   
								sql = "UPDATE "
        	        					+ "shop_customer_payment_master "
        	        					+ "SET "
        	        					+ "account_credit_debit_id = ? "
        	        					+ "WHERE "
    									+ "entry_id = ? "
    									+ "AND "
    									+ "shop_id = ? "
    									+ "AND "
    									+ "shop_code = ? ";
        	        			
        	        			
	    						preparedStatement = connection.prepareStatement(sql);
	    						
	    						preparedStatement.setInt(1, entryId);
	    						preparedStatement.setInt(2, newEntryId);
	    						preparedStatement.setString(3, shopId);
	    		        		preparedStatement.setString(4, shopCode);
	    		        		
	    						 rowCreditDebitIdInsetred = preparedStatement.executeUpdate();
	    						 
							}
	    						
							
						}
					}
							connection.commit();
							
						
							
	    	        		String messageServiceProvider = (String) this.getSessionMap().get("serviceprovider");
	    	        
							if(this.isSendSMS())
							{
								
	    	        			
	    	        			HashMap<String,String> templateList = (HashMap<String,String>)this.getSessionMap().get("template_map_list");
	    	        			boolean allOkSMSSettings = true;
	    	        			boolean sendWhatsAppMessage = WhatsAppSettingsUtil.isWhatsAppSendingEnabled(this.getSessionMap());
	    	        		
	    	        			
	    	        			String ownerMessage = "";
	        			
	    	        			String mobileNumber = WhatsAppSettingsUtil.resolveTargetMobile(this.getSessionMap(), customerMobileNumber);
	    	        			float creditAmt = GetCustomerCreditAmountById.getCustomerCreditAmountById(custId, this.getSessionMap());
			    	        	
    	        			try{
	        					ownerMessage = templateList.get("CUSTOMER_CREDIT_AMOUNT_RECEIVED");
	        				
	        					ownerMessage = ownerMessage.split("#")[1];
	        					
	        					
	        					ownerMessage = ownerMessage.replace("{1var1}", this.getAmount());
	        					ownerMessage = ownerMessage.replace("{2var2}", ""+creditAmt);
	        					ownerMessage = ownerMessage.replace("{3var3}", (String)this.getSessionMap().get("shopcustcarenumber"));
	        					
    	        			}catch (Exception e) {
    	        				
    	        				e.printStackTrace();
	        					allOkSMSSettings = false;
    	        			}
	    	        			

	    	        			
	    	        				
	    	        		 
	    	        			 
	    	        			
	    	    	        		
	    	        		if(!sendWhatsAppMessage)
							{
								addActionMessage("WhatsApp message sending is disabled in settings.");
							}
							else if(!WhatsAppSettingsUtil.isValidMobileNumber(mobileNumber))
							{
								addActionMessage("Invalid Mobile Number ! Cannot send message !");
							}
							else if("INFRAINFOTECH".equals(messageServiceProvider) && allOkSMSSettings)
							{
	    	        			

	    	        			


	    						
								String[] tokenData = WhatsAppSettingsUtil.getDefaultTokenDetails(this.getSessionMap());
								if(tokenData != null && tokenData.length >= 3 && !mobileNumber.contains("99999999"))
								{
									try
									{
									String userName = tokenData[0];
									String tokenNumber = tokenData[1];
									String balanceCheckTokenNumber = tokenData[2];
									
									String resp  = SendWhatsAppMessage.sendMessageOnly(userName, mobileNumber, ownerMessage, tokenNumber);
		    	        			
		    	        		
		    	        			if(WhatsAppSettingsUtil.isFailedResponse(resp))
		    	        			{
		    	        				addActionError("Counldn't send message" + resp);
		    	        			}
		    	        			else
		    	        			{
		    	        				int bal = CheckBalance.checkBal(userName, balanceCheckTokenNumber);
		    	        				if(resp.toLowerCase().contains("success"))
		    	        				{
		    	        					addActionMessage("WhatsApp Message Sent Successfully! Remaining Message Balance : "+bal);
		    	        				}
		    	        				else
		    	        				{
		    	        					addActionMessage("WhatsApp message response : "+resp);
		    	        				}
		    	        				
		    	        			}
	    									
									}catch (Exception e) {
										addActionError("Couldn't send message to milk supplier!"+e.getMessage()+"|"+e.getCause());
									}
								}
								else
								{
									addActionError("WhatsApp token mapping not found for defaultWhatsAppNumber.");
								}
	    					
	    					
							
							}
							
	    	        			
	    	        		
							}
							else if(this.sendSMS && !WhatsAppSettingsUtil.isValidMobileNumber(WhatsAppSettingsUtil.resolveTargetMobile(this.getSessionMap(), customerMobileNumber)))
							{
								addActionMessage("Invalid Mobile Number ! Cannot send message !");
								
							}
							
							this.setPaymentSaved(true);
							this.setPaymentId(""+newEntryId);
							
							
							result = "success";
							addActionMessage("Payment Details added successfully !");
						}
						else
						{
							connection.rollback();
							result = "error";
							addActionError("ERROR ! Payment details not added! Please try again !");
						}
						
					}catch (SQLException e) {
						try {connection.rollback();} catch (SQLException e1) {}
						result = "error";
						//e.printStackTrace();
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Customer details not added !");
					} catch (IOException e) {
						//e.printStackTrace();
						result = "error";						
						addActionError(e.getMessage()+" || "+e.getCause()+" || Customer details not added !");
					}finally {
						if(resultSet != null)
		   				{
		   					try {resultSet.close();resultSet=null;}catch(SQLException sqe){}   					
		   				}
						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 amount !");
		}
		this.setAccountList(GetAccountListForDrCr.getAccountList(this.getSessionMap())); 
		
		if(!hasActionErrors())
		{
			if(!getAmount().equals(""))
			{
				float floatAmt = 0.0F;
				float floatOutstandingAmt  = Float.parseFloat(getOutstandingAmount());
				try
				
				{
					floatAmt = Float.parseFloat(getAmount());
					
					if(floatAmt < 0)
					{
						addActionError("Amount cannot be less than '0' !");
					}
					
				}
				catch(NumberFormatException nfe)
				{
					addActionError("Please provide correct amount to add details !");
				}
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getTypeOfPayment() == null || this.getTypeOfPayment().equals(""))
			{
				addActionError("Please select type of payment!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getAccountId() == null || this.getAccountId().equals(""))
			{
				addActionError("Please select account for debit entry!");
			}
		}
		this.setAccountList(GetAccountListForDrCr.getAccountList(this.getSessionMap())); 
		this.setPaymentTypeList(GetTypeOfPaymentList.getTypeOfPaymentList());
	}
	public HttpSession getSession() {
		return session;
	}
	public void setSession(HttpSession session) {
		this.session = session;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public String getPaymentDate() {
		return paymentDate;
	}
	public void setPaymentDate(String paymentDate) {
		this.paymentDate = paymentDate;
	}
	public String getCustName() {
		return custName;
	}
	public void setCustName(String custName) {
		this.custName = custName;
	}
	public String getAmount() {
		return amount;
	}
	public void setAmount(String amount) {
		this.amount = amount;
	}
	public String getPaymentDetails() {
		return paymentDetails;
	}
	public void setPaymentDetails(String paymentDetails) {
		this.paymentDetails = paymentDetails;
	}

	public String getOutstandingAmount() {
		return outstandingAmount;
	}

	public void setOutstandingAmount(String outstandingAmount) {
		this.outstandingAmount = outstandingAmount;
	}

	public boolean isSendSMS() {
		return sendSMS;
	}

	public void setSendSMS(boolean sendSMS) {
		this.sendSMS = sendSMS;
	}

	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;  
	}

	public Map<String, String> getAccountList() {
		return accountList;
	}

	public void setAccountList(Map<String, String> accountList) {
		this.accountList = accountList;
	}

	public List<String> getPaymentTypeList() {
		return paymentTypeList;
	}

	public void setPaymentTypeList(List<String> paymentTypeList) {
		this.paymentTypeList = paymentTypeList;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public String getTypeOfPayment() {
		return typeOfPayment;
	}

	public void setTypeOfPayment(String typeOfPayment) {
		this.typeOfPayment = typeOfPayment;
	}

	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;
	}
	
	
	

}
