package com.reallinkbilling.add;

import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
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.utils.GetAccountListForDrCr;
import com.reallinkbilling.utils.GetLastBillNumber;
import  com.reallinkbilling.utils.GetProductStockByName;
import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.DAO.BillInformationDAO;
import com.reallinkbilling.DAO.BillProductInfoDAO;
import com.reallinkbilling.resource.CheckAlreadyAvailable;
import com.reallinkbilling.resource.GetListResource;

public class AddProductToBill extends ActionSupport implements SessionAware,Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5416864158386161538L;
	private HttpSession session;
	private String billDateTime;
	private String operator;
	private String paymentType;
	
	private String customerName;
	private String customerId;
	private String customerMobileNumber;
	private String customerType;
	private ArrayList<String> customerTypeList = new ArrayList<String>();
	private String customerIdNameAll;
	
	private String productName;
	private String productMarathiName;
	private String alias;
	private String salesUnit;
	private String taxId;
	private Float salesRate;
	private Float quantity;
	private Float quantity2;
	private Float discountPercentage;
	private Float discountRupees;
	private Float amount;
	private String billType;
	private Float amountAfterDiscount;
	private Float transportCharge;
	private String comments;
	private boolean sendSMS;
	private String alternateMobileNumber;
	private Float amountPaid;
	private SessionMap<String,Object> sessionMap;  
	private Float returnAmount;
	private boolean billSaved;
	private String billNumber;
	private Map<String,String> taxList = new LinkedHashMap<String,String>();
	private Map<String,String> unitList = new LinkedHashMap<String,String>();
	private Map<String,String> paymentTypeList = new  LinkedHashMap<String,String>();
	private Map<String,String> billTypeList = new  LinkedHashMap<String,String>();
	private List<BillProductInfoDAO> productInfoList ;
	private String defaultValue;
	private boolean addQuantity2;
	private Float totalAmount;
	private Float totalDiscount;
	private Float totalAmouAfterDisount;
	private String accountId;
	private String removeVaules="false";
	private String discountType;
	private Float directDiscountAmount;
	private BillInformationDAO billInfoDAO = null;
	private boolean productReturn;
	
	
	private String viewBill;
	
	private Map<String,String> rateTypeList = new LinkedHashMap<String,String>();
	private String rateType;
	private Float makingLabourAmount;
	
	private Map<String,String> labourChargeTypeList = new LinkedHashMap<String,String>();
	private String labourChargeType;
	private String addLabourCharges;
	private Float cashAmount;
	private Float bankRtgsUpiAmount;
	
	private Map<String,String> discountTypeList = new LinkedHashMap<String,String>();
	
	private Map<String,String> accountList = new LinkedHashMap<String,String>();
	private List<String> paymentTypeList2 = new ArrayList<String>();
	
	private String batchId;
	private String expiryDate;
	private String lastBillNumber;
	
	private String buyerOrderNumber;
	private String dispatchDocNumber;
	private String vehicleNumber;
	
	
	@SuppressWarnings("unchecked")
	 public String execute() throws IOException{
		 
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Logout and Login again !");
	        	result = "error";
	        }  
	        else{
	        	
	        	

	        	HashMap<String, String> settings = (HashMap<String, String>) this.getSessionMap().get("shop_settings");
	        	this.setLastBillNumber(GetLastBillNumber.getLastBillNumber(settings.get("default_bill_type"), this.getSessionMap()));
	    		
	        	String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
	    		if(settings.get("add_quntity2").equals("TRUE"))
	        	{
	        		this.setAddQuantity2(true);
	        	}
	        	else
	        	{
	        		this.setAddQuantity2(false);
	        	}
	    		
	    		this.setDiscountType((String) settings.get("discount_type"));
	        	
	    		
	    		this.setProductInfoList((List<BillProductInfoDAO>) this.getSessionMap().get("productList"));
	        	
	        	this.setBillInfoDAO((BillInformationDAO) this.getSessionMap().get("billInformation"));
				
	        	if(this.getProductInfoList() == null)
	        	{
	        		this.setProductInfoList( new ArrayList<BillProductInfoDAO>());
	        	}
	        	
	        	if(this.getBillInfoDAO()==null)
	        	{
	        		this.setBillInfoDAO(new BillInformationDAO());
	        	}
	        
	        	int listSize = this.getProductInfoList().size();
	        	

	        	float floatSalesRate = this.getSalesRate();
	        	float floatQuantity =this.getQuantity();
	        	float floatDiscount =this.getDiscountRupees();
	        	float floatAmout = 0.0F;
	        	
	        	DecimalFormat dfRound = new DecimalFormat("##.##");
	        	
	        	if(settings.get("discount_type").equals("PERQUANTITY"))
	        	{
	        	
		        	floatAmout = floatSalesRate * floatQuantity - (floatDiscount*floatQuantity);
		        	this.setAmountAfterDiscount(Float.valueOf(dfRound.format(floatAmout)));
	        	}
	        	if(settings.get("discount_type").equals("PERCENTAGE"))
	        	{
	        		float totalAmount = floatSalesRate * floatQuantity;
	        		float totalDiscount =  totalAmount * (floatDiscount / 100.0F);
		        	floatAmout = totalAmount - totalDiscount;
		        	
		        	this.setAmountAfterDiscount(Float.valueOf(dfRound.format(floatAmout)));
	        	}
	        	
	        	if(this.getBatchId() == null || this.getBatchId().equals(""))
	        	{
	        		this.setBatchId("NA");
	        	}
	        	if(this.getExpiryDate() == null || this.getExpiryDate().equals(""))
	        	{
	        		this.setExpiryDate("NA");
	        	}
	        			
				
	        	BillProductInfoDAO billProductInfoDAO = new BillProductInfoDAO();
	        	
		        	billProductInfoDAO.setId(null);	        	
		        	billProductInfoDAO.setSerialNumber(""+(listSize+1));
		        	billProductInfoDAO.setProductId(this.getProductName().split("-")[0]);
		        	if(this.isProductReturn())
		        	{
		        		billProductInfoDAO.setProductName(this.getProductName().split("-")[1]+"-RTN");
		        		billProductInfoDAO.setProductNameMarathi(this.getProductMarathiName()+"-RTN");
		        	}else
		        	{
		        		billProductInfoDAO.setProductName(this.getProductName().split("-")[1]);
		        		billProductInfoDAO.setProductNameMarathi(this.getProductMarathiName());
		        	}
		        		
		        	billProductInfoDAO.setProductCode(this.getProductName().split("-")[2]);
		        
		        	billProductInfoDAO.setSalesUnit(this.getSalesUnit());
		        	billProductInfoDAO.setTaxId(this.getTaxId());
		        	billProductInfoDAO.setSalesRate(this.getSalesRate());
	        	
	        	if(isAddQuantity2())
	        	{
	        		billProductInfoDAO.setQuantity2(this.getQuantity2());
	        	}
	        	else
	        	{
	        		billProductInfoDAO.setQuantity2(0.0F);
	        		
	        	}
	        	billProductInfoDAO.setQuantity(this.getQuantity());
	        	billProductInfoDAO.setDiscountPecentage(this.getDiscountPercentage());
	        	
	        	if(this.getDiscountType().equals("PERQUANTITY"))
	        	{
	        	
	        		billProductInfoDAO.setDiscountRupees(this.getDiscountRupees());
	        	}
	        	
	        	if(this.getDiscountType().equals("PERCENTAGE"))
	        	{
	        		billProductInfoDAO.setDiscountPecentage(this.getDiscountRupees());
	        		billProductInfoDAO.setDiscountRupees(this.getAmount() - this.getAmountAfterDiscount());
	        	}
	        	
	        	if(this.isProductReturn())
	        	{
	        		billProductInfoDAO.setAmount(-this.getAmount());
		        	billProductInfoDAO.setAmountAfterDiscount(-this.getAmountAfterDiscount());
		        	billProductInfoDAO.setProductReturn(true);
		        	
	        	}
	        	else
	        	{
		        	billProductInfoDAO.setAmount(this.getAmount());
		        	billProductInfoDAO.setAmountAfterDiscount(this.getAmountAfterDiscount());
		        	billProductInfoDAO.setProductReturn(false);
	        	}
	        
	        	
	        	billProductInfoDAO.setAlias(this.getAlias());
	        	billProductInfoDAO.setAddedToDB(false);
	        	billProductInfoDAO.setShopId(shopId);
	        	billProductInfoDAO.setShopCode(shopCode);
	        	
	        	if(settings.get("add_making_charge_column").equals("TRUE"))
	        	{
	        		billProductInfoDAO.setMakingLaborCharge(this.getMakingLabourAmount());
	        	}
	        	else
	        	{
	        		billProductInfoDAO.setMakingLaborCharge(0.0F);
	        		this.setMakingLabourAmount(0.0F);
	        	}
	        	
	        	float floatAmountAftDiscount = this.getAmountAfterDiscount();
	        	float totalProductDiscount = this.getAmount() - getAmountAfterDiscount();
	        	
	        	
	        	float sgst = 0.0F;
	        	float cgst = 0.0F;
	        	float igst = 0.0F;
	        	
				if(this.getBillType().equals("TAX-INVOICE"))
				{
				
					Map<String,String> taxInfo = GetListResource.GetTaxNamePercentage(this.getTaxId(),this.getSessionMap());
		        	
					String taxName = taxInfo.get("TAX-NAME");
					String taxPercentage = taxInfo.get("TAX-PERCENTAGE");
					
					billProductInfoDAO.setTaxName(taxName);
					billProductInfoDAO.setTaxPercentage(Float.parseFloat(taxPercentage));
					
					if(this.getRateType().equals("INCLUDEGST"))
					{
						
						float floatTaxRate = Float.parseFloat(taxPercentage);	
						
						float basicTax = floatTaxRate+100.0F;
			        	
			        	float grossAmount = (floatAmountAftDiscount / basicTax) * 100.0F;
			        	
			        	float totalTax = floatAmountAftDiscount - grossAmount;
						
						if(taxName.toUpperCase().contains("IGST"))
						{
							igst = totalTax;
						}
						else
						{
							sgst = totalTax/2.0F;
				        	cgst = totalTax/2.0F;
						}
		        	
		        	     
						 DecimalFormat df = new DecimalFormat("0.00");
					        
				        	
			        	 billProductInfoDAO.setProductTotalDiscount(totalProductDiscount);
			        	 billProductInfoDAO.setGrossAmount(Float.valueOf(df.format(grossAmount)));
			        	 billProductInfoDAO.setSgst(Float.valueOf(df.format(sgst)));
			        	 billProductInfoDAO.setCgst(Float.valueOf(df.format(cgst)));
			        	 billProductInfoDAO.setIgst(Float.valueOf(df.format(igst)));
			        		if(this.isProductReturn())
					         {
					        	 billProductInfoDAO.setAmountAfterDiscount(-(floatAmountAftDiscount + this.getMakingLabourAmount()));
					        	 billProductInfoDAO.setAmount(-(billProductInfoDAO.getAmount() + this.getMakingLabourAmount()));
					         }
			        		else
			        		{
			        			 billProductInfoDAO.setAmountAfterDiscount((floatAmountAftDiscount + this.getMakingLabourAmount()));
					        	 billProductInfoDAO.setAmount(billProductInfoDAO.getAmount() + this.getMakingLabourAmount());

			        		}
			        	 
					}
					
					if(this.getRateType().equals("EXCLUDEGST"))
					{
						float floatTaxRate = Float.parseFloat(taxPercentage);	
						float totalTax = floatAmountAftDiscount * (floatTaxRate/100.0F);
						
						if(taxName.toUpperCase().contains("IGST"))
						{
							igst = totalTax;
						}
						else
						{
							sgst = totalTax/2.0F;
				        	cgst = totalTax/2.0F;
						}
						
						
						 DecimalFormat df = new DecimalFormat("0.00");
					        
				        	
			        	 billProductInfoDAO.setProductTotalDiscount(totalProductDiscount);
			        	 billProductInfoDAO.setGrossAmount(Float.valueOf(df.format(floatAmountAftDiscount)));
			        	 billProductInfoDAO.setSgst(Float.valueOf(df.format(sgst)));
			        	 billProductInfoDAO.setCgst(Float.valueOf(df.format(cgst)));
			        	 billProductInfoDAO.setIgst(Float.valueOf(df.format(igst)));
			        	 
			        	 if(this.isProductReturn())
			        	 {
			        		 billProductInfoDAO.setAmountAfterDiscount(-(floatAmountAftDiscount + totalTax + this.getMakingLabourAmount()));
			        		 billProductInfoDAO.setAmount(-(this.getAmount() + totalTax  + this.getMakingLabourAmount()));
			        	 }
			        	 else
			        	 {
			        		 billProductInfoDAO.setAmountAfterDiscount(floatAmountAftDiscount + totalTax + this.getMakingLabourAmount());
				        	 billProductInfoDAO.setAmount(this.getAmount() + totalTax  + this.getMakingLabourAmount());
				        	 
			        	 }
					}
				}
				else
				{
					 billProductInfoDAO.setProductTotalDiscount(totalProductDiscount);
		        	 billProductInfoDAO.setGrossAmount(floatAmountAftDiscount);
		        	 billProductInfoDAO.setSgst(0.0F);
		        	 billProductInfoDAO.setCgst(0.0F);
		        	 billProductInfoDAO.setIgst(0.0F);
		        	 if(this.isProductReturn())
		        	 {
		        		 billProductInfoDAO.setAmountAfterDiscount(-(floatAmountAftDiscount + this.getMakingLabourAmount()));
		        		 billProductInfoDAO.setAmount(-(this.getAmount() + this.getMakingLabourAmount()));
		        	 }
		        	 else
		        	 {
		        		 billProductInfoDAO.setAmountAfterDiscount(floatAmountAftDiscount + this.getMakingLabourAmount());
			        	 billProductInfoDAO.setAmount(this.getAmount() + this.getMakingLabourAmount());
			        	
		        	 }
				}
				
				
				billProductInfoDAO.setBatchId(this.getBatchId());
				billProductInfoDAO.setExpiryDate(this.getExpiryDate());
				
	        	 this.getProductInfoList().add(billProductInfoDAO);
	        	
	        	float floatTotalAmount = 0.0F;
	        	float floatTotalDiscount = 0.0F;
	        	float floatTotalAmtAfterDiscount = 0.0F;
	        	
	        	
	        	for(BillProductInfoDAO infoDAO : this.getProductInfoList())
	        	{
	        		floatTotalAmount  = floatTotalAmount+ infoDAO.getAmount();
	        		floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount + (infoDAO.getAmountAfterDiscount());
	        		floatTotalDiscount = floatTotalDiscount + (infoDAO.getProductTotalDiscount());
	        		
	        	}

	        	String custData [] = null;
	        	try
	        	{
	        		custData = this.getCustomerIdNameAll().split("-");
	        		
	        		if(custData.length > 2)
	        		{
		        		this.getBillInfoDAO().setCustId(custData[0]);
		        		this.getBillInfoDAO().setCustomerName(this.getCustomerName());
		        		this.getBillInfoDAO().setCustomerMobile(custData[2]);
		        		this.getBillInfoDAO().setCustomerType(this.getCustomerType());
		        		
		        		
	        		}
	        		else
	        		{
	        			this.getBillInfoDAO().setCustId("1");
		        		this.getBillInfoDAO().setCustomerName("1-"+custData[0]+"-"+custData[1]+"-REGULER");
		        		this.getBillInfoDAO().setCustomerMobile(custData[1]);
		        		this.getBillInfoDAO().setCustomerType(this.getCustomerType());
		        		
		        		this.setCustomerName("1-"+custData[0]+"-"+custData[1]+"-REGULER");
	        		}
	        		
	        	}catch(Exception e)
	        	{
	        		//e.printStackTrace();
	        		
	        		this.getBillInfoDAO().setCustId("1");
	        		this.getBillInfoDAO().setCustomerMobile("9999999999");
	        		this.getBillInfoDAO().setCustomerName("1-"+this.getCustomerName().trim().toUpperCase()+"-9999999999-REGULER");  
	        		this.getBillInfoDAO().setCustomerType("REGULETR");
	        	}
	    
	        	this.getBillInfoDAO().setBillNumber(getBillNumber());	     
	        	this.getBillInfoDAO().setBillDate(this.getBillDateTime());
	        	this.getBillInfoDAO().setPaymentType(getPaymentType());
	        	this.getBillInfoDAO().setBillType(getBillType());
	        		
	        	this.getBillInfoDAO().setBillSaved(false);
	        	this.getBillInfoDAO().setSendSMS(this.isSendSMS());
	        	this.getBillInfoDAO().setTransportCharge(this.getTransportCharge());
	        	String custMobNum  = "0";
	        	
	        	if(this.getBillInfoDAO().getCustomerMobile() == null || this.getBillInfoDAO().getCustomerMobile().equals(""))
	        	{
	        	
		        	String [] custData2 = new String[5];
		        	
		        	try
		        	{
		        		custData2 = this.getCustomerName().split("-");
		        		custMobNum = custData2[2];
		        		if(!(custMobNum.length() == 10) || custMobNum.contains("999999"))
		        		{
		        			this.getBillInfoDAO().setSendSMS(false);
		        		}
		        		
		        	}
		        	catch(Exception e)
		        	{
		        		if(getAlternateMobileNumber().length()==10)
		        		{
		        			custMobNum = getAlternateMobileNumber();
		        			this.getBillInfoDAO().setSendSMS(true);
		        		}
		        		else
		        		{
		        			this.getBillInfoDAO().setSendSMS(false);
		        		}
		        	}
		        	this.getBillInfoDAO().setCustomerMobile(custMobNum.trim());
	        	}
	        	//System.out.println("view : "+viewBill);
	        	
	        	this.setTotalAmount(floatTotalAmount);	        	
	        	this.setTotalDiscount(floatTotalDiscount);
	        	this.setTotalAmouAfterDisount(floatTotalAmtAfterDiscount);
	        	
	        	this.getBillInfoDAO().setTotalProductDiscount(floatTotalDiscount);
	        	this.getBillInfoDAO().setTotalAfterDiscountBillAmount(floatTotalAmtAfterDiscount);
	        	
	        	if(this.getBillInfoDAO().getPaymentType().equals("CASH"))
		    	{
		    		this.setCashAmount(floatTotalAmtAfterDiscount);
		    	}
		    	else if(this.getBillInfoDAO().getPaymentType().equals("CREDIT"))
		    	{
		    		this.setCashAmount(0.0F);
		    	}
		    	else
		    	{
		    		this.setCashAmount(0.0F);
		    	}
		    	this.setBankRtgsUpiAmount(0.0F);
		    	
	        	addActionMessage("Product added successfully to list !");
	        	this.setRemoveVaules("true");
	        	
	        	
	        	if(this.getPaymentType().equals("CASH"))
	        	{
	        		this.setAmountPaid(this.getTotalAmouAfterDisount());
	        		this.setReturnAmount(0.0F);
	        	}
	        	if(this.getPaymentType().equals("CREDIT")){
	        		this.setAmountPaid(0.0F);
	        		this.setReturnAmount(-this.getTotalAmouAfterDisount());
	        	}
	        	this.getSessionMap().put("billInformation", this.getBillInfoDAO());
	        	this.getSessionMap().put("productList", this.getProductInfoList());
	        	
	        	
	        	this.setProductName("");
	        	this.setQuantity(0.0F);
	        	this.setSalesRate(0.0F);
	        	this.setAmount(0.0F);
	        	this.setDiscountRupees(0.0F);
	        	this.setAmountAfterDiscount(0.0F);
	        	this.setMakingLabourAmount(0.0F);
	        	this.setQuantity2(0.0F);
	        	this.setProductReturn(false);
	        	this.setDirectDiscountAmount(0.0F);
	        	result = SUCCESS;
	        	
	        	this.setBillSaved(false);
	        	
	        }
	     
	        return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void validate() {
		String actualProductName = ""; 
		String productId = "";
		String productCode = "";
		try
		{
			productId = this.getProductName().split("-")[0];
			actualProductName = this.getProductName().split("-")[1];
			productCode =  this.getProductName().split("-")[2];
		}
		catch (Exception e) {
			actualProductName = this.getProductName();
			addActionError("Please provide correct product name (with -)! ");
		}
		
		
		 
    	
		
		session=ServletActionContext.getRequest().getSession(false); 
		List<BillProductInfoDAO> productInfoListTest = (List<BillProductInfoDAO>) this.getSessionMap().get("productList");
		
		//String checkCustName = (String) sessionMap.get("checkCustName");
    	
    	
		paymentTypeList.put("CASH","CASH");
    	paymentTypeList.put("CREDIT","CREDIT");
    	
    	if(productInfoListTest == null)
    	{    	
    		setDefaultValue("CASH");
    	}
    	else
    	{
    		setDefaultValue(getPaymentType());
    	}
    	
    	
    	
    	

    
		taxList = GetListResource.GetTaxList(this.getSessionMap());
	
    	
    	unitList = GetListResource.GetUnitList();
    	billTypeList = GetListResource.GetBillTypeList();
    	//setBillType(billTypeList.get("CASH-MEMO"));
    
		if(this.getCustomerName() == null || this.getProductName().equals("") 
				|| this.getSalesUnit().equals("") || this.getTaxId().equals("") 
				|| this.getBillType().equals(""))
		{
			addActionError("Fields marked with astrik(*) are mandetory 1!");
		}
		
		if(this.getSalesRate() == null 
				|| this.getQuantity() == null 
				|| this.getDiscountPercentage() == null 
				|| this.getDiscountRupees() == null
				|| this.getAmount() ==null)
		{
			addActionError("Fields marked with astrik(*) are mandetory 2!");
		}
		
		if(getCustomerName().equals("Customer_Not_Found"))
		{
			addActionError("Given customer name is not correct !");
		}
		
		if(!hasActionErrors())
		{
			if(this.getRateType() == null || this.getRateType().equals(""))
			{
				addActionError("Please select rate type!");
			}
		}
		
		if(!hasActionErrors())
		{

			String isCustomerAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_name_eng", "NA", actualProductName, this.getSessionMap());
			
			isCustomerAdded = result[0];
			
			if(!isCustomerAdded.equals("true"))
			{
				addActionError("Product name given not found ! Please provide correct product name !");
			}	
			
		}
		
		HashMap<String,String> shopSettingsMap = (HashMap<String, String>) this.getSessionMap().get("shop_settings");
		
	
    	if(shopSettingsMap.get("add_quntity2").equals("TRUE"))
    	{
    		this.setAddQuantity2(true);
    	}
    	else
    	{
    		this.setAddQuantity2(false);
    	}
		String addDuplicateProductToList = shopSettingsMap.get("add_duplicate_items_to_bill");
		this.setDiscountType((String) shopSettingsMap.get("discount_type"));
    	
    	
		if(!hasActionErrors())
		{
			if(isAddQuantity2())
			{
				if(this.getQuantity2() == null || this.getQuantity2().equals(""))
				{
					addActionError("Please provide 2nd quanity !");
				}
				else
				{
					if(!this.isProductReturn())
					{
					try
		    		{
		    		String dbStock2Quantity = GetProductStockByName.getProductStockByName2ndQty(productId,productCode,this.getSessionMap());
		    		
		    		if(!dbStock2Quantity.equals("NA"))
		    		{
		    			float dbStock2QuantityFloat = Float.parseFloat(dbStock2Quantity);
		    			
		    			if(dbStock2QuantityFloat == 0 || dbStock2QuantityFloat < 0)
		    			{
		    				addActionError("2 nd Quantity is less ("+dbStock2Quantity+") in stock of "+this.getProductName()+"! Cannot Sale!");
		    			}else
		    			{
		    				float saleProductQuantity2 =this.getQuantity2();
		    				
		    				float diffToUpdateQuantity2 = dbStock2QuantityFloat - saleProductQuantity2;
		    				
		    				if(diffToUpdateQuantity2 < 0)
		    				{
		    					addActionError("2 nd Quantity is less ("+dbStock2Quantity+") in stock of "+actualProductName+"! Cannot Sale!");
		    				}
		    			}
		    			
		    		}
		    		else
		    		{
		    			addActionError("Error while getting DB stock quantity of product!");
		    		}
		    		
		    		}catch(Exception e)
		    		{
		    			addActionError("Error while getting DB stock quantity of product!");
		    		}
					}
				}
			}
		}
	
		if(addDuplicateProductToList.equals("FALSE"))
		{
			if(productInfoListTest !=null)
			{
				if(!productInfoListTest.isEmpty())
				{
					for(BillProductInfoDAO infoDAO:productInfoListTest)
					{
					
						
							if(infoDAO.getProductName().equals(this.getProductName().split("-")[1]))
							{
								addActionError("Product is alredy added to list!");
								productInfoList = productInfoListTest;
							}
						
						
					}
				}
				else
				{
					this.setProductInfoList(productInfoListTest);
				}
			}
		}
		
		if(!hasActionErrors())
		{
			if("COMPOSITE-BILL".equals(this.getBillType()))
			{
				if(productInfoListTest != null && !productInfoListTest.isEmpty())
				{
					addActionError("Only one main product is allowed in Composite Bill.");
				}
			}
		}
		
		
		
		float floatTotalAmount = 0.0F;
    	float floatTotalDiscount = 0.0F;
    	float floatTotalAmtAfterDiscount = 0.0F;
    	
    	if(this.getProductInfoList() == null)
    	{
    		this.setProductInfoList((List<BillProductInfoDAO>) this.getSessionMap().get("productList"));
    	}
    	
    	
    	if(getCustomerName().equals("Customer_Not_Found"))
    	{
    		addActionError("Please Provide Correct Customer Name !");
    	}
    	
    	if(!hasActionErrors())
    	{
    		if(getPaymentType().equals("CREDIT") && !getCustomerName().equals("Customer_Not_Found"))
    		{
    			setDefaultValue(getPaymentType());
    			String isCustomerAdded = "false";
    			String [] custData = new String [5];
    			try
    			{
	    			custData = getCustomerIdNameAll().split("-");
	    			
	    			
	    			if(!custData[0].equals('1') ||  !custData[0].equals('0'))
	    			{
	    				
		    			
		    			String [] result = new String[2];
		    			String condition  = " or mobile_number = '"+custData[2]+"' ";
		    			
		    			
		    			
		    			result = new CheckAlreadyAvailable().checkAvaibility("shop_customer_master", "customer_name", condition, custData[1], this.getSessionMap());
		    			
		    			isCustomerAdded = result[0];
		    			
		    			if(isCustomerAdded.equals("false"))
		    			{
		    				addActionError("If Payment is 'CREDIT' then customer information must be added first! Please Check Customer Details First !");
		    			}
	    			}
	    			else
	    			{
	    				addActionError("If Payment is 'CREDIT' then customer information must be added first!");
	    			}
    			}
    			catch(Exception e)
    			{
    				addActionError("If Payment is 'CREDIT' then customer information must be added first!");
    			}
    			

    			
    					
    		}
    	}
    	
    	if(!hasActionErrors())
    	{
    		if(!this.isProductReturn())
			{
    			
			
    		try
    		{
    		String dbStockQuantity = GetProductStockByName.getProductStockByName(productId,productCode,this.getSessionMap());
    		
    		if(!dbStockQuantity.equals("NA"))
    		{
    			float dbStockQuantityFloat = Float.parseFloat(dbStockQuantity);
    			
    			if(dbStockQuantityFloat == 0 || dbStockQuantityFloat < 0)
    			{
    				addActionError("Quantity is less ("+dbStockQuantity+") in stock of "+this.getProductName()+"! Cannot Sale!");
    			}else
    			{
    				float saleProductQuantity =this.getQuantity();
    				
    				float diffToUpdateQuantity = dbStockQuantityFloat - saleProductQuantity;
    				
    				if(diffToUpdateQuantity < 0)
    				{
    					addActionError("Quantity is less ("+dbStockQuantity+") in stock of "+actualProductName+"! Cannot Sale!");
    				}
    			}
    			
    		}
    		else
    		{
    			addActionError("Error while getting DB stock quantity of product!");
    		}
    		
    		}catch(Exception e)
    		{
    			addActionError("Error while getting DB stock quantity of product!");
    		}
			}
    		
    	}
    	
    	
    	if(this.getProductInfoList() !=null)
    	{
	    	for(BillProductInfoDAO infoDAO : this.getProductInfoList())
	    	{
	    		floatTotalAmount  = floatTotalAmount+ infoDAO.getAmount();
	    		floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount + infoDAO.getAmountAfterDiscount();
	    		
	    		
	    	}
	    	floatTotalDiscount = floatTotalAmount - floatTotalAmtAfterDiscount;
	    	
	    	this.setTotalAmount(floatTotalAmount);
	    	this.setTotalDiscount(floatTotalDiscount);
	    	this.setTotalAmouAfterDisount(floatTotalAmtAfterDiscount);
	    	this.setBillInfoDAO((BillInformationDAO) this.getSessionMap().get("billInformation"));
	    	
	    	if(this.getBillInfoDAO().getPaymentType().equals("CASH"))
	    	{
	    		this.setCashAmount(floatTotalAmtAfterDiscount);
	    	}
	    	else if(this.getBillInfoDAO().getPaymentType().equals("CREDIT"))
	    	{
	    		this.setCashAmount(0.0F);
	    	}
	    	else
	    	{
	    		this.setCashAmount(0.0F);
	    	}
	    	this.setBankRtgsUpiAmount(0.0F);
    	}
    	
    	
    /*	if(!hasActionErrors())
    	{
    		float dealerPrice = GetProductDealerPrice.getDealarPrice(productId, actualProductName, productCode, this.getSessionMap());
    		
    		if(dealerPrice <= 0)
    		{
    			addActionError("Please add dealer price to this product!");
    			
    		}
    		else if(this.getSalesRate() < dealerPrice)
    		{
    			addActionError("Price of the product cannot be less than dealer price! Please check the product price!");
    		}
    		
    		
    		
    	}*/
    	

    	this.getRateTypeList().put("INCLUDEGST", "WITH GST");
    	this.getRateTypeList().put("EXCLUDEGST", "WITH-OUT GST");
    	
    	this.getLabourChargeTypeList().put("QUANTITYWISE", "BY QUANTITY");
    	this.getLabourChargeTypeList().put("PERCENTAGEWISE", "BY PERCENTAGE");

    
    	this.setAddLabourCharges((String) shopSettingsMap.get("add_making_charge_column"));
    	
    	if(this.getAddLabourCharges().equals("TRUE")){
    		if(this.getMakingLabourAmount() == null || this.getMakingLabourAmount().equals(""))
    		{
    			addActionError("Please provide making / labor charges!");
    		}
    	}
    	
    	this.getDiscountTypeList().put("PERCENTAGE", "PERCENTAGE");
    	this.getDiscountTypeList().put("PERQUANTITY", "PERQUANTITY");
    	
    	
    	
    	this.setAccountList(GetAccountListForDrCr.getAccountList((this.getSessionMap()))); 
		
    	paymentTypeList2.add("CASH");
    	paymentTypeList2.add("UPI");
    	paymentTypeList2.add("RTGS");
    	paymentTypeList2.add("NEFT");
    	paymentTypeList2.add("CHEQUE");
    	
    	HashMap<String, String> settings = (HashMap<String, String>) this.getSessionMap().get("shop_settings");
    	
       	this.setCustomerTypeList(GetListResource.getCustomerTypeList());
	      
    
    	this.setAccountId((String) settings.get("default_account_to_collect"));
    	
    	
    	if(this.getBillInfoDAO() != null)
    	{
    		
	    	if(this.getBillInfoDAO().getBuyerOrderNumber() != null)
	    	{
	    		if(this.getBillInfoDAO().getBuyerOrderNumber() != null || !this.getBillInfoDAO().getBuyerOrderNumber().equals(""))
	    		{
	    			this.setBuyerOrderNumber(this.getBillInfoDAO().getBuyerOrderNumber());
	    		}
	    		else
	    		{
	    			this.setBuyerOrderNumber("NA");
	    					
	    		}
	    	}
	    	
	    	
	    	if(this.getBillInfoDAO().getDispatchDocNumber() != null)
	    	{
	    		if(this.getBillInfoDAO().getDispatchDocNumber() != null || !this.getBillInfoDAO().getDispatchDocNumber().equals(""))
	    		{
	    			this.setDispatchDocNumber(this.getBillInfoDAO().getDispatchDocNumber());
	    		}
	    		else
	    		{
	    			this.setDispatchDocNumber("NA");
	    		}
	    	}
	    	
	    	if(this.getBillInfoDAO().getVehicleNumber() != null)
	    	{
	    		if(this.getBillInfoDAO().getVehicleNumber() != null || !this.getBillInfoDAO().getVehicleNumber().equals(""))
	    		{
	    			this.setVehicleNumber(this.getBillInfoDAO().getVehicleNumber());
	    		}
	    		else
	    		{
	    			this.setVehicleNumber("NA");
	    		}
	    	}
    	}
	}

	public HttpSession getSession() {
		return session;
	}


	public void setSession(HttpSession session) {
		this.session = session;
	}


	public String getBillDateTime() {
		return billDateTime;
	}


	public void setBillDateTime(String billDateTime) {
		this.billDateTime = billDateTime;
	}


	public String getOperator() {
		return operator;
	}


	public void setOperator(String operator) {
		this.operator = operator;
	}


	public String getPaymentType() {
		return paymentType;
	}


	public void setPaymentType(String paymentType) {
		this.paymentType = paymentType;
	}


	public String getCustomerName() {
		return customerName;
	}


	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}


	public String getAlias() {
		return alias;
	}


	public void setAlias(String alias) {
		this.alias = alias;
	}





	public String getSalesUnit() {
		return salesUnit;
	}

	public void setSalesUnit(String salesUnit) {
		this.salesUnit = salesUnit;
	}

	

	public String getTaxId() {
		return taxId;
	}

	public void setTaxId(String taxId) {
		this.taxId = taxId;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public String getBillType() {
		return billType;
	}

	public void setBillType(String billType) {
		this.billType = billType;
	}

	public String getBillNumber() {
		return billNumber;
	}

	public void setBillNumber(String billNumber) {
		this.billNumber = billNumber;
	}

	public Map<String, String> getTaxList() {
		return taxList;
	}

	public void setTaxList(Map<String, String> taxList) {
		this.taxList = taxList;
	}

	public Map<String, String> getUnitList() {
		return unitList;
	}

	public void setUnitList(Map<String, String> unitList) {
		this.unitList = unitList;
	}

	public Map<String, String> getPaymentTypeList() {
		return paymentTypeList;
	}

	public void setPaymentTypeList(Map<String, String> paymentTypeList) {
		this.paymentTypeList = paymentTypeList;
	}

	public Map<String, String> getBillTypeList() {
		return billTypeList;
	}

	public void setBillTypeList(Map<String, String> billTypeList) {
		this.billTypeList = billTypeList;
	}

	public String getDefaultValue() {
		return defaultValue;
	}

	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}

	public String getProductMarathiName() {
		return productMarathiName;
	}

	public void setProductMarathiName(String productMarathiName) {
		this.productMarathiName = productMarathiName;
	}


	public Float getAmountAfterDiscount() {
		return amountAfterDiscount;
	}

	public void setAmountAfterDiscount(Float amountAfterDiscount) {
		this.amountAfterDiscount = amountAfterDiscount;
	}

	public List<BillProductInfoDAO> getProductInfoList() {
		return productInfoList;
	}

	public void setProductInfoList(List<BillProductInfoDAO> productInfoList) {
		this.productInfoList = productInfoList;
	}

	
	public Float getTotalAmount() {
		return totalAmount;
	}

	public void setTotalAmount(Float totalAmount) {
		this.totalAmount = totalAmount;
	}

	public Float getTotalDiscount() {
		return totalDiscount;
	}

	public void setTotalDiscount(Float totalDiscount) {
		this.totalDiscount = totalDiscount;
	}

	public Float getTotalAmouAfterDisount() {
		return totalAmouAfterDisount;
	}

	public void setTotalAmouAfterDisount(Float totalAmouAfterDisount) {
		this.totalAmouAfterDisount = totalAmouAfterDisount;
	}

	public String getRemoveVaules() {
		return removeVaules;
	}

	public void setRemoveVaules(String removeVaules) {
		this.removeVaules = removeVaules;
	}

	public BillInformationDAO getBillInfoDAO() {
		return billInfoDAO;
	}

	public void setBillInfoDAO(BillInformationDAO billInfoDAO) {
		this.billInfoDAO = billInfoDAO;
	}

	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 Float getSalesRate() {
		return salesRate;
	}

	public void setSalesRate(Float salesRate) {
		this.salesRate = salesRate;
	}

	public Float getQuantity() {
		return quantity;
	}

	public void setQuantity(Float quantity) {
		this.quantity = quantity;
	}

	public Float getDiscountPercentage() {
		return discountPercentage;
	}

	public void setDiscountPercentage(Float discountPercentage) {
		this.discountPercentage = discountPercentage;
	}

	public Float getDiscountRupees() {
		return discountRupees;
	}

	public void setDiscountRupees(Float discountRupees) {
		this.discountRupees = discountRupees;
	}

	public Float getAmount() {
		return amount;
	}

	public void setAmount(Float amount) {
		this.amount = amount;
	}

	public Float getTransportCharge() {
		return transportCharge;
	}

	public void setTransportCharge(Float transportCharge) {
		this.transportCharge = transportCharge;
	}

	public Float getAmountPaid() {
		return amountPaid;
	}

	public void setAmountPaid(Float amountPaid) {
		this.amountPaid = amountPaid;
	}

	public Float getReturnAmount() {
		return returnAmount;
	}

	public void setReturnAmount(Float returnAmount) {
		this.returnAmount = returnAmount;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public String getComments() {
		return comments;
	}

	public void setComments(String comments) {
		this.comments = comments;
	}

	public String getViewBill() {
		return viewBill;
	}

	public void setViewBill(String viewBill) {
		this.viewBill = viewBill;
	}

	public boolean isSendSMS() {
		return sendSMS;
	}

	public void setSendSMS(boolean sendSMS) {
		this.sendSMS = sendSMS;
	}

	public String getAlternateMobileNumber() {
		return alternateMobileNumber;
	}

	public void setAlternateMobileNumber(String alternateMobileNumber) {
		this.alternateMobileNumber = alternateMobileNumber;
	}

	public boolean isBillSaved() {
		return billSaved;
	}

	public void setBillSaved(boolean billSaved) {
		this.billSaved = billSaved;
	}

	public Map<String, String> getRateTypeList() {
		return rateTypeList;
	}

	public void setRateTypeList(Map<String, String> rateTypeList) {
		this.rateTypeList = rateTypeList;
	}

	public String getRateType() {
		return rateType;
	}

	public void setRateType(String rateType) {
		this.rateType = rateType;
	}

	public Float getMakingLabourAmount() {
		return makingLabourAmount;
	}

	public void setMakingLabourAmount(Float makingLabourAmount) {
		this.makingLabourAmount = makingLabourAmount;
	}

	public Map<String, String> getLabourChargeTypeList() {
		return labourChargeTypeList;
	}

	public void setLabourChargeTypeList(Map<String, String> labourChargeTypeList) {
		this.labourChargeTypeList = labourChargeTypeList;
	}

	public String getLabourChargeType() {
		return labourChargeType;
	}

	public void setLabourChargeType(String labourChargeType) {
		this.labourChargeType = labourChargeType;
	}

	public String getAddLabourCharges() {
		return addLabourCharges;
	}

	public void setAddLabourCharges(String addLabourCharges) {
		this.addLabourCharges = addLabourCharges;
	}

	public Float getQuantity2() {
		return quantity2;
	}

	public void setQuantity2(Float quantity2) {
		this.quantity2 = quantity2;
	}

	public boolean isAddQuantity2() {
		return addQuantity2;
	}

	public void setAddQuantity2(boolean addQuantity2) {
		this.addQuantity2 = addQuantity2;
	}

	public Float getCashAmount() {
		return cashAmount;
	}

	public void setCashAmount(Float cashAmount) {
		this.cashAmount = cashAmount;
	}

	public Float getBankRtgsUpiAmount() {
		return bankRtgsUpiAmount;
	}

	public void setBankRtgsUpiAmount(Float bankRtgsUpiAmount) {
		this.bankRtgsUpiAmount = bankRtgsUpiAmount;
	}

	public Map<String, String> getDiscountTypeList() {
		return discountTypeList;
	}

	public void setDiscountTypeList(Map<String, String> discountTypeList) {
		this.discountTypeList = discountTypeList;
	}

	public String getDiscountType() {
		return discountType;
	}

	public void setDiscountType(String discountType) {
		this.discountType = discountType;
	}

	public Map<String, String> getAccountList() {
		return accountList;
	}

	public void setAccountList(Map<String, String> accountList) {
		this.accountList = accountList;
	}

	public List<String> getPaymentTypeList2() {
		return paymentTypeList2;
	}

	public void setPaymentTypeList2(List<String> paymentTypeList2) {
		this.paymentTypeList2 = paymentTypeList2;
	}

	public String getAccountId() {
		return accountId;
	}

	public void setAccountId(String accountId) {
		this.accountId = accountId;
	}


	public String getBatchId() {
		return batchId;
	}

	public void setBatchId(String batchId) {
		this.batchId = batchId;
	}

	public String getExpiryDate() {
		return expiryDate;
	}

	public void setExpiryDate(String expiryDate) {
		this.expiryDate = expiryDate;
	}

	public String getLastBillNumber() {
		return lastBillNumber;
	}

	public void setLastBillNumber(String lastBillNumber) {
		this.lastBillNumber = lastBillNumber;
	}

	public Float getDirectDiscountAmount() {
		return directDiscountAmount;
	}

	public void setDirectDiscountAmount(Float directDiscountAmount) {
		this.directDiscountAmount = directDiscountAmount;
	}

	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	public String getCustomerMobileNumber() {
		return customerMobileNumber;
	}

	public void setCustomerMobileNumber(String customerMobileNumber) {
		this.customerMobileNumber = customerMobileNumber;
	}

	public String getCustomerType() {
		return customerType;
	}

	public void setCustomerType(String customerType) {
		this.customerType = customerType;
	}

	public ArrayList<String> getCustomerTypeList() {
		return customerTypeList;
	}

	public void setCustomerTypeList(ArrayList<String> customerTypeList) {
		this.customerTypeList = customerTypeList;
	}

	public String getCustomerIdNameAll() {
		return customerIdNameAll;
	}

	public void setCustomerIdNameAll(String customerIdNameAll) {
		this.customerIdNameAll = customerIdNameAll;
	}

	public String getBuyerOrderNumber() {
		return buyerOrderNumber;
	}

	public void setBuyerOrderNumber(String buyerOrderNumber) {
		this.buyerOrderNumber = buyerOrderNumber;
	}

	public String getDispatchDocNumber() {
		return dispatchDocNumber;
	}

	public void setDispatchDocNumber(String dispatchDocNumber) {
		this.dispatchDocNumber = dispatchDocNumber;
	}

	public String getVehicleNumber() {
		return vehicleNumber;
	}

	public void setVehicleNumber(String vehicleNumber) {
		this.vehicleNumber = vehicleNumber;
	}

	public boolean isProductReturn() {
		return productReturn;
	}

	public void setProductReturn(boolean productReturn) {
		this.productReturn = productReturn;
	}

	
	
	
	
	
	

}
