package com.reallinkbilling.delete;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.DAO.ChallanProductInfoDAO;
import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.update.UpdateProductStockDetails;

public class DeleteChallanFromCustAccountDetails extends ActionSupport implements SessionAware{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3673797192697533006L;
	private SessionMap<String,Object> sessionMap; 
	private String challanNumber;
	private String typeOfBill;
	private String fromDate;
	private String toDate;
	private String key;
	private String custName;
	private String custMobile;
	private String dateAsStringType2;
	
	public String execute() {
		 
		String result = "login";
	
		
	        if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){ 
	        	addActionMessage("Please Logout and Login again !");
	        	result = "login";
	        }  
	        else{
	        	
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
			
				String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	        	
			
	    		String custId = EncryptionDecryption.decrypt(getKey());	        	
	        	setKey(EncryptionDecryption.encrypt(custId));
	        	
				String sql = "";
				String db = (String)  this.getSessionMap().get("db");
				
				try
				{
					connection = GetDBConnection.getDBConnection(db);
					connection.setAutoCommit(false);
					
					
					
					sql = "SELECT "
	       					+ "customer_name,"
	       					+ "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();
	       			
	       			resultSet.last();
	       			int rowCount = resultSet.getRow();
	       			resultSet.beforeFirst();
	       			
	       			
	       			if(rowCount>0)
	       			{
	       				result = "success";
		       			while(resultSet.next())
		       			{
		       				
		       				this.setCustName(resultSet.getString(1));
		       				this.setCustMobile(resultSet.getString(2));					
		       				
		       				
		       			}
	       			}
	       			else
	       			{
	       				result = "error";
	       				addActionError("Details Not Found !");
	       			}
	       			
	       			if(resultSet != null)
	       			{
	       				resultSet.close();
	       				resultSet = null;
	       			}
	       			
	       			if(preparedStatement != null)
	       			{
	       				preparedStatement.close();
	       				preparedStatement = null;
	       			}
					
					sql = "SELECT "
							+ "product_id,"
							+ "product_name,"
							+ "sales_unit,"
							+ "sales_rate,"
							+ "product_quantity "
							+ "FROM "
							+ "shop_challan_product_info_master "
							+ "WHERE "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ? "
							+ "AND "
							+ "challan_number = ? "
							+ "AND "
							+ "challan_date = STR_TO_DATE(?,'%d-%m-%Y') ";
					
					preparedStatement = connection.prepareStatement(sql);
					
					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					preparedStatement.setString(3, this.getChallanNumber());
					preparedStatement.setString(4, this.getDateAsStringType2());
					
					
					//System.out.println(preparedStatement.toString());
					resultSet = preparedStatement.executeQuery();
					resultSet.last();
					int noOfRows = resultSet.getRow();
					resultSet.beforeFirst();
					
					ArrayList<ChallanProductInfoDAO> productList = new ArrayList<ChallanProductInfoDAO>();
					
					if(noOfRows>0)
					{
						
						while (resultSet.next()) 
						{
							
							ChallanProductInfoDAO infoDAO = new ChallanProductInfoDAO();
							infoDAO.setProductId(resultSet.getString(1));
							infoDAO.setProductName(resultSet.getString(2));
							infoDAO.setSalesUnit(resultSet.getString(3));
							infoDAO.setSalesRate(resultSet.getFloat(4));
							infoDAO.setQuantity(resultSet.getFloat(5));
							
							productList.add(infoDAO);
						}
						
						int productCount = productList.size();
						boolean stockAdded = true;
						int productQuantityUpdatedCount = 0;
						
						for(ChallanProductInfoDAO infoDAO : productList)
						{
							stockAdded = UpdateProductStockDetails.addStockToCurrentStock(connection, this.getSessionMap(), infoDAO.getProductId(), infoDAO.getProductName(), infoDAO.getQuantity());
							 
							if(stockAdded)
							{
								productQuantityUpdatedCount = productQuantityUpdatedCount + 1;
							}
						}
						
						
						if(stockAdded && (productQuantityUpdatedCount==productCount))
						{
							
							if(preparedStatement != null)
							{
								preparedStatement.close();
								preparedStatement = null;
							}
							
							sql = "DELETE "
									+ "FROM "
									+ "shop_challan_product_info_master "
									+ "WHERE "
									+ "shop_id = ? "
									+ "AND "
									+ "shop_code = ? "
									+ "AND "
									+ "challan_number = ? "
									+ "AND "
									+ "challan_date = STR_TO_DATE(?,'%d-%m-%Y') ";
							
							preparedStatement = connection.prepareStatement(sql);
							
							preparedStatement.setString(1, shopId);
							preparedStatement.setString(2, shopCode);
							preparedStatement.setString(3, this.getChallanNumber());
							preparedStatement.setString(4, this.getDateAsStringType2());
							
								
							int rowCountDeleted = preparedStatement.executeUpdate();
							
							
							if(rowCountDeleted > 0)
							{
								if(preparedStatement != null)
								{
									preparedStatement.close();
									preparedStatement = null;
								}
								
								
								sql = "DELETE FROM "
										+ "shop_challan_info_master "
										+ "WHERE "
										+ "shop_id = ? "
										+ "AND "
										+ "shop_code = ? "
										+ "AND "
										+ "challan_number = ? "
										+ "AND "
										+ "challan_date = STR_TO_DATE(?,'%d-%m-%Y') ";
								
								preparedStatement = connection.prepareStatement(sql);
								
								preparedStatement.setString(1, shopId);
								preparedStatement.setString(2, shopCode);
								preparedStatement.setString(3, this.getChallanNumber());
								preparedStatement.setString(4, this.getDateAsStringType2());
								
								
							
								int billDeletedCount = preparedStatement.executeUpdate();
								
								if(billDeletedCount > 0)
								{
									connection.commit();
									result = SUCCESS;
									
									addActionMessage("Challan Deleted Successfully!");
								}
								else
								{
									connection.rollback();
									result = ERROR;
									addActionError("Something went Wrong! Please try again! Error while challan delete!");
									
								}
								
								
							}
							else
							{
								connection.rollback();
								result = ERROR;
								addActionError("Something went Wrong! Please try again! Error while challan product delete!");
							}
							
							
						}
						else
						{
							connection.rollback();
							result = ERROR;
							addActionError("Something went Wrong! Please try again! Error while challan product qty update!");
						}
					}
					else
					{
						result = ERROR;
						addActionError("Details Not Found! Please try Again!");
					}
					
					
				}
				catch (SQLException e) {
					
					e.printStackTrace();
					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;
	}
	
	
	






	public String getTypeOfBill() {
		return typeOfBill;
	}




	public void setTypeOfBill(String typeOfBill) {
		this.typeOfBill = typeOfBill;
	}




	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 getKey() {
		return key;
	}




	public void setKey(String key) {
		this.key = key;
	}




	public static long getSerialversionuid() {
		return serialVersionUID;
	}




	public String getCustName() {
		return custName;
	}




	public void setCustName(String custName) {
		this.custName = custName;
	}




	public String getCustMobile() {
		return custMobile;
	}




	public void setCustMobile(String custMobile) {
		this.custMobile = custMobile;
	}




	public String getDateAsStringType2() {
		return dateAsStringType2;
	}




	public void setDateAsStringType2(String dateAsStringType2) {
		this.dateAsStringType2 = dateAsStringType2;
	}




	public String getChallanNumber() {
		return challanNumber;
	}






	public void setChallanNumber(String challanNumber) {
		this.challanNumber = challanNumber;
	}






	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;  
	}
	

}





