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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.fasterxml.jackson.databind.ObjectMapper;
import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.bulksmsgateway.AddBulkSMSGatewayResponseToDB;
import com.reallinkbilling.bulksmsgateway.SendBulkSMSGatewayMessage;
import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.utils.GetAccountListForDrCr;
import com.reallinkbilling.utils.GetTypeOfPaymentList;
import com.reallinkbilling.utils.InsertBankAccDrCrEntry;
import com.reallinkbilling.utils.MaintainCloseingBalUtil;
import com.realllinkbilling.message.AddTextLocalResponseToDB;
import com.realllinkbilling.message.MessageReplyPojo;
import com.realllinkbilling.message.SendTextLocalMessage;

public class AddSupplierPaymentDetails extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6802538530805180042L;
	private HttpSession session;
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private String defaultValue;
	private String paymentDate;
	private String key;
	private Float debtAmount;
	private Float amountPaid;
	private String supplierName;
	private String paymentDetails;
	private boolean sendSMS;
	private SessionMap<String,Object> sessionMap;  

	private String accountId;
	private String typeOfPayment;
	private Map<String,String> accountList = new LinkedHashMap<String,String>();
	private List<String> paymentTypeList = new ArrayList<String>();
	
	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{
	        	
	        	String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
	        	customerSearchOptionList.put("BYNAME", "BY NAME");
	        	customerSearchOptionList.put("BYMOBILE", "BY MOBILE");
	        	customerSearchOptionList.put("BYADDRESS","BY ADDRESS");
				setCustomerSearchOption("BYNAME");
				setDefaultValue("BYNAME");
	        	result ="success";
	        	
	        	
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
				
				String sql = "";
				String db = (String) this.getSessionMap().get("db");
				
				String supplierMobileNumber = "";
				
				

        		String fullUserName = (String) this.getSessionMap().get("userFullName");
	        	
	        	String splitUserName [] = new String[5];
	        	
	        	String entryBy = "";
	        	try
	        	{
	        		splitUserName = fullUserName.split(" ");
	        		entryBy = splitUserName[0];
	        		
	        	}catch(Exception e)
	        	{
	        		entryBy =fullUserName;
	        	}
				
				try
				{
					String supplierId = EncryptionDecryption.decrypt(getKey());
					String supplierName = "";
					
					connection = GetDBConnection.getDBConnection(db);
					connection.setAutoCommit(false);
					
					sql = "SELECT "
							+ "supplier_id,"
							+ "suplier_name,"
							+ "contact_number "
							+ "FROM "
							+ "shop_supplier_master "
							+ "WHERE "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ? "
							+ "AND "
							+ "supplier_id = ? ";
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					preparedStatement.setString(3, supplierId);
					
					resultSet = preparedStatement.executeQuery();
					
					if(resultSet.next())
					{
						supplierName = resultSet.getString(2);
						supplierMobileNumber = resultSet.getString(3);
					}
					else
					{
						addActionError("Supplier Not found! URL Tampered!");						
					}
					
					
					if(!hasActionErrors())
					{
						
						if(resultSet != null)
						{
							resultSet.close();
							resultSet = null;
						}
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
						
						sql = "SELECT "
								+ "entry_id "
								+ "FROM "
								+ "shop_supplier_payment_details "
								+ "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 newEntryId = 0;
						if(resultSet.next())
						{
							if(!(resultSet.getString(1) == null))
							{
								newEntryId = Integer.parseInt(resultSet.getString(1))+1;
								
							}
							else
							{
								newEntryId =1;
								
							}
						}
						
						  java.util.Date date = new java.util.Date();
		        	      long t = date.getTime();	        	     
		        	      java.sql.Time time = new java.sql.Time(t);
		        	      
						sql = "INSERT INTO "
								+ "shop_supplier_payment_details "
								+ "(entry_id,"
								+ "supplier_id,"
								+ "shop_id,"
								+ "shop_code,"
								+ "payment_date,"
								+ "payment_time,"
								+ "payment_amount,"
								+ "payment_type,"
								+ "payement_details,"
								+ "entry_by) "
								+ "VALUES "
								+ "(?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?)";
						
						
						preparedStatement = connection.prepareStatement(sql);
						preparedStatement.setString(1, ""+newEntryId);
						preparedStatement.setString(2, supplierId);
						preparedStatement.setString(3, shopId);
						preparedStatement.setString(4, shopCode);
						preparedStatement.setString(5, this.getPaymentDate());
						preparedStatement.setTime(6, time);
						preparedStatement.setFloat(7, this.getAmountPaid());
						preparedStatement.setString(8, "NA");
						preparedStatement.setString(9, this.getPaymentDetails());
						preparedStatement.setString(10, entryBy);
						
						int rowCount = preparedStatement.executeUpdate();
						
						boolean debitEntryAdded = InsertBankAccDrCrEntry.addBankAccDebitEntry(this.getPaymentDate(), this.getAccountId(), this.getAmountPaid(), this.getTypeOfPayment(), this.getSessionMap(), "Payment given to "+supplierName+" | "+this.getPaymentDetails());
						
						boolean isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(this.getAccountId(),"DEBIT", this.getPaymentDate(), this.getAmountPaid(), entryBy, connection, this.getSessionMap());
					
						if(rowCount > 0 && debitEntryAdded && isCloseingBalMaintained)
						{

							if(this.isSendSMS() && supplierMobileNumber.length()==10)
							{	
								String messageServiceProvider = "BULKSMSGATEWAY";

	    	        			//System.out.println("in Send Message");
	    	        			String mobileNumber = supplierMobileNumber;
	    	        			String msg= "प्रिय पुरवठादार, आपणास एकूण  "+this.getAmountPaid()+" रुपये दिले ! धन्यवाद ! सागर अॅग्रो सेल्स";
	    	        			
	    	        			if(messageServiceProvider.equals("TEXTLOCAL"))
	    						{
								
	    							
	    	    	        			String resp = new SendTextLocalMessage().sendSms(mobileNumber, msg);
	    	    	        			
	    		    	        			if(resp.contains("Invalid"))
	    		    	        			{
	    										
	    										addActionMessage("Message Not Sent. Invalid Number !!!");
	    										
	    									}
	    									else
	    									{
	    											AddTextLocalResponseToDB responseToDB = new AddTextLocalResponseToDB();
	    											Map<String,String> responseDetails = responseToDB.addTextLocalResponseToDB(resp, mobileNumber, messageServiceProvider,"BIILING");
	    											if(responseDetails != null)
	    			    	        				{
	    			    	        					String dbAdded = responseDetails.get("DBADDED");
	    			    	        					
	    			    	        					if(dbAdded.equals("TRUE"))
	    			    	        					{
	    			    	        						addActionMessage("Message details added!" + responseDetails.get("MESSAGE"));
	    			    	        					}
	    			    	        					else
	    			    	        					{
	    			    	        						addActionError("Message details not added! "+responseDetails.get("MESSAGE"));
	    			    	        					}
	    			    	        				}
	    									}
	    							
	    					}
							else if(messageServiceProvider.equals("BULKSMSGATEWAY"))
							{
								String messageApiKey = "kirveravindra#Kirveravi@123";
								String messageSendrId = "RHTSMS";
									try
									{
									String [] keyDetails =  messageApiKey.split("#");
									String userName2 = keyDetails[0];
									String password = keyDetails[1];
									
									
		    	        			SendBulkSMSGatewayMessage gatewayMessage = new SendBulkSMSGatewayMessage();
		    	        			String resp  = gatewayMessage.sendSms(userName2, password, mobileNumber, msg, messageSendrId,"");
		    	        			if(resp.contains("failed"))
		    	        			{
		    	        				addActionError("Counldn't send message" + resp);
		    	        			}
		    	        			else
		    	        			{
		    	        				AddBulkSMSGatewayResponseToDB gatewayResponseToDB = new AddBulkSMSGatewayResponseToDB();
		    	        				Map<String,String> responseDetails = gatewayResponseToDB.addBulkSMSGatewayResponseToDB(this.getSessionMap(), resp, mobileNumber, messageServiceProvider, messageSendrId, msg, "BIILING");
		    	        				
		    	        				if(responseDetails != null)
		    	        				{
		    	        					String dbAdded = responseDetails.get("DBADDED");
		    	        					
		    	        					if(dbAdded.equals("TRUE"))
		    	        					{
		    	        						addActionMessage("Message details added!" + responseDetails.get("MESSAGE"));
		    	        					}
		    	        					else
		    	        					{
		    	        						addActionError("Message details not added! "+responseDetails.get("MESSAGE"));
		    	        					}
		    	        				}
		    	        				
		    	        			}
	    									
									}catch (Exception e) {
										addActionError("Couldn't send message to milk supplier!"+e.getMessage()+"|"+e.getCause());
									}
							}
							
	    	        			
	    	        		
							}
							else if(this.sendSMS && (supplierMobileNumber.length()<10 || supplierMobileNumber.length()>10))
							{
								addActionMessage("Invalid Mobile Number ! Cannot send message !");
								
							}
							
							connection.commit();
							result = "success";
							addActionMessage("Supplier Payment Details added successfully!");
						}
						else
						{
							connection.rollback();
							result = "error";
							addActionError("Supplier payment details not added! Please try again!");
						}
						
						
						
					}
					else
					{
						connection.rollback();
						result = "error";
					}
				}
				catch (SQLException e) {
					result = "error";
					try {connection.rollback();} catch (SQLException e1) {}
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Supplier payment details not added !");
				} catch (IOException e) {
					
					result = "error";						
					addActionError(e.getMessage()+" || "+e.getCause()+" || Supplier payment 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.getDebtAmount()== null || this.getDebtAmount().equals(""))
		{
			addActionError("Somthing went wrong! Debt amount not displayed!");
		}
		
		if(!hasActionErrors())
		{
			if(this.getAmountPaid() ==null || this.getAmountPaid().equals(""))
			{
				addActionError("Please provide correct amount paid!");
			}
			else if(this.getAmountPaid() <= 0 )
			{
				addActionError("Amount paid cannot be less than equal to '0'!");
			}
			
			/*else if(this.getAmountPaid() > this.getDebtAmount())
			{
				addActionError("Amount paid cannot be greater than debt amount!");
			}*/
		}
		
		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 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 String getPaymentDate() {
		return paymentDate;
	}

	public void setPaymentDate(String paymentDate) {
		this.paymentDate = paymentDate;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public Float getDebtAmount() {
		return debtAmount;
	}

	public void setDebtAmount(Float debtAmount) {
		this.debtAmount = debtAmount;
	}

	public Float getAmountPaid() {
		return amountPaid;
	}

	public void setAmountPaid(Float amountPaid) {
		this.amountPaid = amountPaid;
	}

	public String getPaymentDetails() {
		return paymentDetails;
	}

	public void setPaymentDetails(String paymentDetails) {
		this.paymentDetails = paymentDetails;
	}

	public String getSupplierName() {
		return supplierName;
	}

	public void setSupplierName(String supplierName) {
		this.supplierName = supplierName;
	}

	public boolean isSendSMS() {
		return sendSMS;
	}

	public void setSendSMS(boolean sendSMS) {
		this.sendSMS = sendSMS;
	}
	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 String getAccountId() {
		return accountId;
	}

	public void setAccountId(String accountId) {
		this.accountId = accountId;
	}

	public String getTypeOfPayment() {
		return typeOfPayment;
	}

	public void setTypeOfPayment(String typeOfPayment) {
		this.typeOfPayment = typeOfPayment;
	}
	
	

}
