package com.reallinkbilling.add;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
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.stonecrusher.infrawhatsappmsg.CheckBalance;
import com.stonecrusher.infrawhatsappmsg.SendWhatsAppMessage;
import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.DAO.BillInformationDAO;
import com.reallinkbilling.DAO.BillProductInfoDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.GetListResource;
import com.reallinkbilling.update.UpdateProductStockDetails;
import com.reallinkbilling.utils.GetAccountListForDrCr;
import com.reallinkbilling.utils.GetCustomerCreditAmountById;
import com.reallinkbilling.utils.MaintainCloseingBalUtil;
import com.reallinkbilling.utils.WhatsAppSettingsUtil;
import com.realllinkbilling.message.AddTextLocalResponseToDB;
import com.realllinkbilling.message.SendTextLocalMessage;


public class BillSave extends ActionSupport implements SessionAware{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -4205886934505595095L;
	private HttpSession session;
	private SessionMap<String,Object> sessionMap;
	private BillInformationDAO billInfoDAO = null;
	private List<BillProductInfoDAO> productInfoList = null;
	private List<BillProductInfoDAO> deletedProductInfoList = null;
	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 Map<String,String> printTypeList = new LinkedHashMap<String,String>();
	private String defaultValue;
	private String billType;
	private String printType;
	private String customerName;
	private String customerId;
	private String customerMobileNumber;
	private String customerType;
	private ArrayList<String> customerTypeList = new ArrayList<String>();
	private String customerIdNameAll;
	private String discountType;
	private String billNumber;
	private String billDateTime;
	private String totalAmount;
	private String totalDiscount;
	private String totalAmouAfterDisount;
	private String totalPaybleAmount;
	private Float amountPaid;
	private Float transportCharge;
	private String paymentType;
	private String returnAmount;
	private String alternateMobileNumber;
	private boolean sendSMS;
	private String billSave;
	private boolean billSaved;
	private String comments;
	private boolean sendDirectSMS;
	private String billWhatsAppMessageType;
	private String billWhatsAppPdfType;
	private Map<String,String> rateTypeList = new LinkedHashMap<String,String>();
	private String rateType;
	private Float cashAmount;
	private Float bankRtgsUpiAmount;
	
	private String buyerOrderNumber;
	private String dispatchDocNumber;
	private String vehicleNumber;
	

	private Float directDiscountAmount;
	private List<String> paymentTypeList2 = new ArrayList<String>();
	private String modeOfPayment;
	private String accountId;
	private Map<String,String> accountList = new LinkedHashMap<String,String>();
	
	@SuppressWarnings("unchecked")
	synchronized public String execute() {
		
		
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        else{
	        	
	        	

        		String fullUserName = (String) this.getSessionMap().get("userFullName");
	        	
	        	String splitUserName [] = new String[5];
	        	
	        	String billedBy = "";
	        	try
	        	{
	        		splitUserName = fullUserName.split(" ");
	        		billedBy = splitUserName[0];
	        		
	        	}catch(Exception e)
	        	{
	        		billedBy =fullUserName;
	        	}
	        	
	        	if(this.getDispatchDocNumber() == null || this.getDispatchDocNumber().equals(""))
	        	{
	        		this.setDispatchDocNumber("NA");
	        	}
	        	
	        	if(this.getBuyerOrderNumber() == null || this.getBuyerOrderNumber().equals(""))
	        	{
	        		this.setBuyerOrderNumber("NA");
	        	}
	        	if(this.getVehicleNumber() == null || this.getVehicleNumber().equals(""))
	        	{
	        		this.setVehicleNumber("NA");
	        	}
	        	
	        	if((getAmountPaid() == null || getAmountPaid().equals("")) && (getReturnAmount() == null || getReturnAmount().equals("")))
	        	{
	        		
	        		
	        		this.setProductInfoList((List<BillProductInfoDAO>) this.getSessionMap().get("productList"));		        	
		        	this.setBillInfoDAO((BillInformationDAO) this.getSessionMap().get("billInformation"));
		        	this.setDeletedProductInfoList((List<BillProductInfoDAO>) this.getSessionMap().get("deletedProductList"));

		        	
		        	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();
		        		
		        	}
		        	
		        	this.setCustomerName(billInfoDAO.getCustomerName());
		        	this.setBillNumber(billInfoDAO.getBillNumber());
		        	this.setBillType(billInfoDAO.getBillType());
	        		
		        	this.setTotalAmount(""+floatTotalAmount);	        	
		        	this.setTotalDiscount(""+(floatTotalDiscount+this.getBillInfoDAO().getDirectDiscountAmount()));
		        	this.setTotalAmouAfterDisount(""+(floatTotalAmtAfterDiscount-this.getBillInfoDAO().getDirectDiscountAmount()));
		        	
	        		this.getPaymentTypeList().put("CASH","CASH");
	        		this.getPaymentTypeList().put("CREDIT","CREDIT");
		        	
		        	this.setDefaultValue(this.getBillInfoDAO().getPaymentType());
		        	

		        	try {this.setTaxList((Map<String, String>) this.getSessionMap().get("tax_list"));}catch (Exception e) {}
		        	
		        	unitList = GetListResource.GetUnitList();
		        	billTypeList = GetListResource.GetBillTypeList();
		        	
		        	
		        	addActionError("Please Provide Amount Paid and Amount Return !");
	        		
	        		this.getSessionMap().put("billInformation", billInfoDAO);
	        		this.getSessionMap().put("productList", productInfoList);
	        		result = "error";
		        	
	        	}
	        	else
	        	{
	        		String shopId = (String) this.getSessionMap().get("shopId");
		    		String shopCode = (String) this.getSessionMap().get("shopCode");
		    		
		    		
	        		String billDateTime = "";
	        		
	        		billDateTime = this.getBillInfoDAO().getBillDate();
	        		
	        		if(billDateTime == null || billDateTime == "" )
	        		{
	        			Date d = new Date();
			        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
			        	billDateTime = dateFormat.format(d);
	        			
	        		}
	        		
	        	
		        	
		        Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
				
				String sql = "";
				String db = (String) this.getSessionMap().get("db");
				
				
				this.setProductInfoList((List<BillProductInfoDAO>) this.getSessionMap().get("productList"));
	        	
	        	this.setBillInfoDAO((BillInformationDAO) this.getSessionMap().get("billInformation"));
	        	this.setDeletedProductInfoList((List<BillProductInfoDAO>) this.getSessionMap().get("deletedProductList"));
	        	
	        	if(this.getBillInfoDAO() == null || this.getProductInfoList() == null || this.getProductInfoList().isEmpty())
	        	{
	        		addActionError("Bill session expired or product list is empty. Please add product again and save.");
	        		result = "error";
	        		return result;
	        	}

	        	//System.out.print("Is Bill Saved : "+billInfoDAO.isBillSaved());
	        	
	        	if(!this.getBillInfoDAO().isBillSaved())	        	
	        	{
	        		/*System.out.println("In Save Bill");
	        		
		        	Date d = new Date();
		        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");*/
		        	//String billDateTime = dateFormat.format(d);	        	
		        	
		        	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();
		        		
		        	}
		        	
		        	floatTotalDiscount = floatTotalDiscount + this.getBillInfoDAO().getDirectDiscountAmount();
		        	
		        	floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount - this.getBillInfoDAO().getDirectDiscountAmount(); 
	        	try
	        	{
	        		
	        		  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);
	        	
        		String fianacialYear = (String) this.getSessionMap().get("financialyearstartdate");
        		
        		ArrayList <Integer> billNumbers = new ArrayList<Integer>();
        		
        		if(this.getBillInfoDAO().getBillNumber() == null || this.getBillInfoDAO().getBillNumber().equalsIgnoreCase("NA"))
				{
        			String fy = "24/25";
        			
        			if(this.getBillInfoDAO().getBillType().equals("TAX-INVOICE"))
        			{
        				sql = "SELECT "
    							+ "bill_number "
    							+ "FROM "
    							+ "shop_bill_info_master "
    							+ "WHERE "
    							+ "bill_type = 'TAX-INVOICE' "
    							+ "AND "
    							+ "shop_id = ? "
    							+ "AND "
    							+ "shop_code= ? "
    							+ "AND "
    							+ "bill_date >= ?";
        				
        			}else
        			{
        			
					sql = "SELECT "
							+ "bill_number "
							+ "FROM "
							+ "shop_bill_info_master "
							+ "WHERE "
							+ "bill_type <> 'TAX-INVOICE' "
							+ "AND "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code= ? "
							+ "AND "
							+ "bill_date >= ?";
					}
					
				
				preparedStatement = connection.prepareStatement(sql);
				preparedStatement.setString(1, shopId);
				preparedStatement.setString(2, shopCode);
				preparedStatement.setString(3, fianacialYear);
				
					
					resultSet = preparedStatement.executeQuery();
					int newBillNumber = 0;
					while(resultSet.next())
					{
						try
						{
							billNumbers.add(Integer.parseInt(resultSet.getString(1).split("-")[1]));
						}catch (Exception e) {
							billNumbers.add(Integer.parseInt(resultSet.getString(1)));
						}
					}
					
					
					 Collections.sort(billNumbers);
					 
					 if(billNumbers.size() > 0)
						{
						 
							 newBillNumber = billNumbers.get(billNumbers.size()-1);
							 
							 if(this.getBillInfoDAO().getBillType().equals("TAX-INVOICE"))
			        			{
							
								 	this.getBillInfoDAO().setBillNumber(""+(newBillNumber+1));
			        			}
								 else
								 {
									 this.getBillInfoDAO().setBillNumber(""+(newBillNumber+1));
								 }
						}
						else
						{
							newBillNumber = 1;
							 if(this.getBillInfoDAO().getBillType().equals("TAX-INVOICE"))
			        			{
							
								 	this.getBillInfoDAO().setBillNumber(""+(newBillNumber));
			        			}else
			        			{
			        				this.getBillInfoDAO().setBillNumber(""+(newBillNumber));
			        			}
						
							
						}
				}
        		if(resultSet != null)
        		{
        			resultSet.close();
        			resultSet = null;
        		}
        		if(preparedStatement!= null)
        		{
        			preparedStatement.close();
        			preparedStatement = null;
        		}
        		
        		
        		
	        	if(getReturnAmount() == null || getReturnAmount().equals(""))
	        	{
	        		
	        		float amountPaid = 0.0F;
	        		try
	        		{
	        			amountPaid =this.getAmountPaid();
	        			
	        			this.setReturnAmount(""+(floatTotalAmtAfterDiscount-amountPaid));
	        		}
	        		catch(Exception e)
	        		{}
	        		
	        	}
	        	int countBillInfoInserted = 0;
	        	int countBillInfoUpdated = 0;
	        	
	        	float transportChargeFloat = 0.0F;
	        	
	        	boolean shouldUpdateBillHeader = this.getBillInfoDAO().isBillInformationInserted();
	        	if(!shouldUpdateBillHeader)
	        	{
	        		shouldUpdateBillHeader = isBillHeaderAlreadyPresent(connection, this.getBillInfoDAO().getBillType(),
	        				this.getBillInfoDAO().getBillNumber(), billDateTime, shopId, shopCode);
	        		if(shouldUpdateBillHeader)
	        		{
	        			this.getBillInfoDAO().setBillInformationInserted(true);
	        		}
	        	}
	        	
	        	if(!shouldUpdateBillHeader)
	        	{
	        		transportChargeFloat = this.getTransportCharge();
	        		
	        	sql = "INSERT INTO "
	        			+ "shop_bill_info_master"
	        			+ "( "
	        			+ "shop_id,"
	        			+ "shop_code,"
	        			+ "bill_number,"	        			
	        			+ "bill_time,"
	        			+ "bill_date,"
	        			+ "payment_type,"
	        			+ "bill_type,"
	        			+ "customer_id,"
	        			+ "customer_name,"
	        			+ "transportation_charges,"
	        			+ "comments,"
	        			+ "bill_total_amount,"
	        			+ "bill_amount_received,"
	        			+ "bill_amount_retrurn,"
	        			+ "billed_by,"
	        			+ "cash_amount,"
	        			+ "bank_rtgs_upi_amount,"
	        			+ "direct_discount_amount,"
	        			+ "buyer_order_number,"
	        			+ "dispatch_doc_number,"
	        			+ "vehicle_number) "
    					+ "VALUES "
    					+ "(?,?,?,?,STR_TO_DATE(?, '%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	        			
	        	
	        	preparedStatement = connection.prepareStatement(sql);
	        	
	        	preparedStatement.setString(1, shopId);
	        	preparedStatement.setString(2, shopCode);
	        	preparedStatement.setString(3,this.getBillInfoDAO().getBillNumber());
	           	preparedStatement.setTime(4, time);
	        	preparedStatement.setString(5,this.getBillInfoDAO().getBillDate());
	        	preparedStatement.setString(6,this.getBillInfoDAO().getPaymentType());
	        	preparedStatement.setString(7,this.getBillInfoDAO().getBillType());
	        	preparedStatement.setString(8,this.getBillInfoDAO().getCustId());
	        	preparedStatement.setString(9,this.getBillInfoDAO().getCustId()+"-"+this.getBillInfoDAO().getCustomerName()+"-"+this.getBillInfoDAO().getCustomerMobile()+"-"+this.getBillInfoDAO().getCustomerType());
	        	preparedStatement.setFloat(10, this.getTransportCharge());
	        	preparedStatement.setString(11,this.getComments());
	        	preparedStatement.setFloat(12,(floatTotalAmtAfterDiscount+transportChargeFloat));
	        	preparedStatement.setFloat(13,this.getAmountPaid());
	        	preparedStatement.setString(14,this.getReturnAmount());
	        	preparedStatement.setString(15,billedBy);
	        	preparedStatement.setFloat(16,this.getCashAmount());
	        	preparedStatement.setFloat(17,this.getBankRtgsUpiAmount());
	        	preparedStatement.setFloat(18, this.getBillInfoDAO().getDirectDiscountAmount());
	        	preparedStatement.setString(19, this.getBuyerOrderNumber().trim().toUpperCase());
	        	preparedStatement.setString(20, this.getDispatchDocNumber().trim().toUpperCase());
	        	preparedStatement.setString(21, this.getVehicleNumber().trim().toUpperCase());
	        	
	        	
	        	//System.out.println(preparedStatement.toString());
	        	
	        	countBillInfoInserted = preparedStatement.executeUpdate();
	        	
	        	}
	        	else
	        	{
	        		if(this.getBillInfoDAO().getOldCustomerId() == null || this.getBillInfoDAO().getOldCustomerId().equals(""))
	        		{
	        			this.getBillInfoDAO().setOldCustomerId(this.getBillInfoDAO().getCustId());
	        		}
	        		
	        		if(this.getBillInfoDAO().getOldBillDate() == null || this.getBillInfoDAO().getOldBillDate().equals(""))
	        		{
	        			this.getBillInfoDAO().setOldBillDate(this.getBillInfoDAO().getBillDate());
	        		}
	        		
	        		
	        		sql = "UPDATE "
	        				+ "shop_bill_info_master "
	        				+ "SET "
	        				+ "bill_time=?,"
		        			+ "bill_date=STR_TO_DATE(?,'%d-%m-%Y'),"
		        			+ "payment_type=?,"		        			
		        			+ "customer_id = ?,"
		        			+ "customer_name=?,"
		        			+ "transportation_charges=?,"
		        			+ "comments=?,"
		        			+ "bill_total_amount=?,"
		        			+ "bill_amount_received=?,"
		        			+ "bill_amount_retrurn=?,"
		        			+ "cash_amount=?,"
		        			+ "bank_rtgs_upi_amount=?,"
		        			+ "direct_discount_amount = ?, "
		        			+ "buyer_order_number = ?,"
		        			+ "dispatch_doc_number = ?,"
		        			+ "vehicle_number = ? "		       			        			
		        			+ "WHERE "
		        			+ "bill_type = ? "
		        			+ "AND "
		        			+ "bill_number = ? "
		        			+ "AND "
		        			+ "customer_id = ? "
		        			+ "AND "
		        			+ "bill_date=STR_TO_DATE(?,'%d-%m-%Y') "
		        			+ "AND "
		        			+ "shop_id = ? "
		        			+ "AND "
		        			+ "shop_code = ? ";
	        		
	        		preparedStatement = connection.prepareStatement(sql);
		      	        	
		           	preparedStatement.setTime(1, time);
		        	preparedStatement.setString(2, billDateTime);
		        	preparedStatement.setString(3,this.getBillInfoDAO().getPaymentType());		        
		        	preparedStatement.setString(4,this.getBillInfoDAO().getCustId());
		        	preparedStatement.setString(5,this.getBillInfoDAO().getCustId()+"-"+this.getBillInfoDAO().getCustomerName()+"-"+this.getBillInfoDAO().getCustomerMobile()+"-"+this.getBillInfoDAO().getCustomerType());
		        	preparedStatement.setFloat(6,this.getTransportCharge());
		        	preparedStatement.setString(7,this.getComments());
		        	preparedStatement.setFloat(8,(floatTotalAmtAfterDiscount+transportChargeFloat));
		        	preparedStatement.setFloat(9,this.getAmountPaid());
		        	preparedStatement.setString(10,this.getReturnAmount());
		        	preparedStatement.setFloat(11,this.getCashAmount());
		        	preparedStatement.setFloat(12,this.getBankRtgsUpiAmount());
		        	preparedStatement.setFloat(13, this.getBillInfoDAO().getDirectDiscountAmount());
		        	preparedStatement.setString(14, this.getBuyerOrderNumber().trim().toUpperCase());
		        	preparedStatement.setString(15, this.getDispatchDocNumber().trim().toUpperCase());
		        	preparedStatement.setString(16, this.getVehicleNumber().trim().toUpperCase());
		        	preparedStatement.setString(17, this.getBillInfoDAO().getBillType());
		        	preparedStatement.setString(18,this.getBillInfoDAO().getBillNumber());
		        	preparedStatement.setString(19, this.getBillInfoDAO().getOldCustomerId());
		        	preparedStatement.setString(20, this.getBillInfoDAO().getOldBillDate());		        	
		        	preparedStatement.setString(21, shopId);
		        	preparedStatement.setString(22, shopCode);
		        	
		        	//System.out.println(preparedStatement.toString());
		        	
		        	countBillInfoUpdated = preparedStatement.executeUpdate();
		        	
		        	// Fallback for edited bills where old customer/date keys may not match exactly.
		        	if(countBillInfoUpdated == 0)
		        	{
		        		if(preparedStatement != null)
		        		{
		        			preparedStatement.close();
		        			preparedStatement = null;
		        		}
		        		
		        		sql = "UPDATE "
		        				+ "shop_bill_info_master "
		        				+ "SET "
		        				+ "bill_time=?,"
		        			+ "bill_date=STR_TO_DATE(?,'%d-%m-%Y'),"
		        			+ "payment_type=?,"		        			
		        			+ "customer_id = ?,"
		        			+ "customer_name=?,"
		        			+ "transportation_charges=?,"
		        			+ "comments=?,"
		        			+ "bill_total_amount=?,"
		        			+ "bill_amount_received=?,"
		        			+ "bill_amount_retrurn=?,"
		        			+ "cash_amount=?,"
		        			+ "bank_rtgs_upi_amount=?,"
		        			+ "direct_discount_amount = ?, "
		        			+ "buyer_order_number = ?,"
		        			+ "dispatch_doc_number = ?,"
		        			+ "vehicle_number = ? "
		        			+ "WHERE "
		        			+ "bill_type = ? "
		        			+ "AND "
		        			+ "bill_number = ? "
		        			+ "AND "
		        			+ "shop_id = ? "
		        			+ "AND "
		        			+ "shop_code = ? ";
		        		
		        		preparedStatement = connection.prepareStatement(sql);
		        		
		           	preparedStatement.setTime(1, time);
		        	preparedStatement.setString(2, billDateTime);
		        	preparedStatement.setString(3,this.getBillInfoDAO().getPaymentType());		        
		        	preparedStatement.setString(4,this.getBillInfoDAO().getCustId());
		        	preparedStatement.setString(5,this.getBillInfoDAO().getCustId()+"-"+this.getBillInfoDAO().getCustomerName()+"-"+this.getBillInfoDAO().getCustomerMobile()+"-"+this.getBillInfoDAO().getCustomerType());
		        	preparedStatement.setFloat(6,this.getTransportCharge());
		        	preparedStatement.setString(7,this.getComments());
		        	preparedStatement.setFloat(8,(floatTotalAmtAfterDiscount+transportChargeFloat));
		        	preparedStatement.setFloat(9,this.getAmountPaid());
		        	preparedStatement.setString(10,this.getReturnAmount());
		        	preparedStatement.setFloat(11,this.getCashAmount());
		        	preparedStatement.setFloat(12,this.getBankRtgsUpiAmount());
		        	preparedStatement.setFloat(13, this.getBillInfoDAO().getDirectDiscountAmount());
		        	preparedStatement.setString(14, this.getBuyerOrderNumber().trim().toUpperCase());
		        	preparedStatement.setString(15, this.getDispatchDocNumber().trim().toUpperCase());
		        	preparedStatement.setString(16, this.getVehicleNumber().trim().toUpperCase());
		        	preparedStatement.setString(17, this.getBillInfoDAO().getBillType());
		        	preparedStatement.setString(18,this.getBillInfoDAO().getBillNumber());
		        	preparedStatement.setString(19, shopId);
		        	preparedStatement.setString(20, shopCode);
		        	
		        	countBillInfoUpdated = preparedStatement.executeUpdate();
		        	}
	        		
	        	}
	        	
	        	
	       	
	        	// Final fallback: if update count is still 0, but bill header already exists,
	        	// continue with product refresh flow instead of hard fail.
	        	if(countBillInfoInserted == 0 && countBillInfoUpdated == 0)
	        	{
	        		if(preparedStatement != null)
	        		{
	        			preparedStatement.close();
	        			preparedStatement = null;
	        		}
	        		if(resultSet != null)
	        		{
	        			resultSet.close();
	        			resultSet = null;
	        		}
	        		
	        		sql = "SELECT 1 FROM shop_bill_info_master "
	        				+ "WHERE bill_type = ? "
	        				+ "AND bill_number = ? "
	        				+ "AND shop_id = ? "
	        				+ "AND shop_code = ? "
	        				+ "LIMIT 1";
	        		preparedStatement = connection.prepareStatement(sql);
	        		preparedStatement.setString(1, this.getBillInfoDAO().getBillType());
	        		preparedStatement.setString(2, this.getBillInfoDAO().getBillNumber());
	        		preparedStatement.setString(3, shopId);
	        		preparedStatement.setString(4, shopCode);
	        		resultSet = preparedStatement.executeQuery();
	        		if(resultSet.next())
	        		{
	        			countBillInfoUpdated = 1;
	        		}
	        		
	        		// Secondary fallback: if header not matched but product rows already exist,
	        		// allow refresh flow to continue for edited bills.
	        		if(countBillInfoUpdated == 0)
	        		{
	        			if(resultSet != null)
	        			{
	        				resultSet.close();
	        				resultSet = null;
	        			}
	        			if(preparedStatement != null)
	        			{
	        				preparedStatement.close();
	        				preparedStatement = null;
	        			}
	        			
	        			sql = "SELECT 1 FROM shop_bill_product_info_master "
	        					+ "WHERE bill_type = ? "
	        					+ "AND bill_number = ? "
	        					+ "AND shop_id = ? "
	        					+ "AND shop_code = ? "
	        					+ "LIMIT 1";
	        			preparedStatement = connection.prepareStatement(sql);
	        			preparedStatement.setString(1, this.getBillInfoDAO().getBillType());
	        			preparedStatement.setString(2, this.getBillInfoDAO().getBillNumber());
	        			preparedStatement.setString(3, shopId);
	        			preparedStatement.setString(4, shopCode);
	        			resultSet = preparedStatement.executeQuery();
	        			if(resultSet.next())
	        			{
	        				countBillInfoUpdated = 1;
	        			}
	        		}
	        	}
	        	
	    
	        	if(countBillInfoInserted>0 || countBillInfoUpdated > 0)
	        	{
	        		
	        		
	        		if(preparedStatement != null)
	        		{
	        			preparedStatement.close();
	        			preparedStatement = null;
	        		}
	        		
	        		
	        		sql = "SELECT "
	        				+ "product_id,"
	        				+ "product_quantity,"
	        				+ "product_quantity_2 "	        				
	        				+ "FROM "
	        				+ "shop_bill_product_info_master "
	        				+ "where "
	        				+ "bill_type = ? "
		        			+ "AND "
	        				+ "bill_number = '"+this.getBillInfoDAO().getBillNumber()+"' "
    						+ "AND "
    						+ "shop_id = ? "
    						+ "AND "
    						+ "shop_code = ? ";
	        		
	        		
	        		preparedStatement = connection.prepareStatement(sql);
	        		preparedStatement.setString(1, this.getBillInfoDAO().getBillType());
	        		preparedStatement.setString(2, shopId);
	        		preparedStatement.setString(3, shopCode);
	        	
	        		resultSet = preparedStatement.executeQuery();
	        		
	        	
	        		int rowCountTodelete = 0;
	        		boolean stockAdded = true;
	        		while(resultSet.next())
	        		{
	        			
	        			stockAdded = UpdateProductStockDetails.addStockToCurrentStock(connection, this.getSessionMap(), resultSet.getString(1),  resultSet.getFloat(2),  resultSet.getFloat(3));
	        			rowCountTodelete = rowCountTodelete + 1;
	        		}
	        		
	        		int rowsDeleted = 0;
	        		
	        		if(rowCountTodelete > 0)
	        		{
	        			
	        			if(preparedStatement != null)
		        		{
		        			preparedStatement.close();
		        			preparedStatement = null;
		        		}
	        			
	        			sql = "DELETE "
	        					+ "FROM "
	        					+ "shop_bill_product_info_master "
	        					+ "WHERE "
	        					+ "bill_type = ? "
			        			+ "AND "
	        					+ "bill_number = ? "
	        							+ "AND "
	        							+ "shop_id = ? "
	        							+ "AND "
	        							+ "shop_code = ?";
	        			
	        			preparedStatement = connection.prepareStatement(sql);
	        			preparedStatement.setString(1, this.getBillInfoDAO().getBillType());
	        			preparedStatement.setString(2, this.getBillInfoDAO().getBillNumber());
	        			preparedStatement.setString(3, shopId);
	        			preparedStatement.setString(4, shopCode);
	        			int rowDeleted = preparedStatement.executeUpdate(); ;
	        			rowsDeleted = rowsDeleted + rowDeleted;	
	        			
	        			
	        		}
	        	
	        		if(rowCountTodelete == rowsDeleted && stockAdded)
					{
	        			
					
	        		sql = "SELECT "
							+ "entry_id "
							+ "FROM "
							+ "shop_bill_product_info_master "
							+ "WHERE "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ? "
							+ "ORDER BY "
							+ "bill_number  "
							+ "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 = resultSet.getInt(1)+ 1;
						
					}
					
				}
	        		
	        		String insertProductSql = "INSERT INTO "
	        				+ "shop_bill_product_info_master "
        					+ "("
        					+ "entry_id,"
        					+ "shop_id,"
        					+ "shop_code,"
        					+ "bill_number,"
        					+ "bill_type,"
        					+ "bill_date,"
        					+ "product_id,"
        					+ "product_name,"
        					+ "sales_unit,"
        					+ "id_tax_table,"
        					+ "sales_rate,"
        					+ "product_quantity,"
        					+ "discount_percentage,"
        					+ "discount_ruppees,"
        					+ "product_total_amount,"
        					+ "product_total_amount_aft_discount,"
        					+ "product_net_amount,"
        					+ "product_igst_amount,"
        					+ "product_cgst_amount,"
        					+ "product_sgst_amount,"
        					+ "making_labor_charge,"
        					+ "product_name_in_marathi,"
        					+ "product_quantity_2,"
        					+ "product_batch_id,"
        					+ "product_expiry_date) "
        					+ "values "
        					+ "(?,?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        			
	        			PreparedStatement insertProductListPSMT = null;
	        			insertProductListPSMT = connection.prepareStatement(insertProductSql);
	        			boolean stockMinus = false;
	        			for(BillProductInfoDAO productInfoDAO : this.getProductInfoList())
	        			{
	        				if(preparedStatement != null)
	    	        		{
	    	        			preparedStatement.close();
	    	        			preparedStatement = null;
	    	        		}
	        				
	        			insertProductListPSMT.setInt(1, entryId++);
	        			insertProductListPSMT.setString(2, shopId);
	        			insertProductListPSMT.setString(3, shopCode);
	        			insertProductListPSMT.setString(4, this.getBillInfoDAO().getBillNumber());
	        			insertProductListPSMT.setString(5, this.getBillInfoDAO().getBillType());
	        			insertProductListPSMT.setString(6, this.getBillInfoDAO().getBillDate());
	        			insertProductListPSMT.setString(7, productInfoDAO.getProductId());
	        			insertProductListPSMT.setString(8, productInfoDAO.getProductName());
	        			insertProductListPSMT.setString(9, productInfoDAO.getSalesUnit());
	        			insertProductListPSMT.setString(10, productInfoDAO.getTaxId());
	        			insertProductListPSMT.setFloat(11, productInfoDAO.getSalesRate());
	        			insertProductListPSMT.setFloat(12, productInfoDAO.getQuantity());
	        			insertProductListPSMT.setFloat(13, productInfoDAO.getDiscountPecentage());
	        			insertProductListPSMT.setFloat(14, productInfoDAO.getDiscountRupees());
	        			insertProductListPSMT.setFloat(15, productInfoDAO.getAmount());
	        			insertProductListPSMT.setFloat(16, productInfoDAO.getAmountAfterDiscount());
	        			insertProductListPSMT.setFloat(17, productInfoDAO.getGrossAmount());
	        			insertProductListPSMT.setFloat(18, productInfoDAO.getIgst());
	        			insertProductListPSMT.setFloat(19, productInfoDAO.getCgst());
	        			insertProductListPSMT.setFloat(20, productInfoDAO.getSgst());
	        			insertProductListPSMT.setFloat(21, productInfoDAO.getMakingLaborCharge());
	        			insertProductListPSMT.setString(22, productInfoDAO.getProductNameMarathi());
	        			insertProductListPSMT.setFloat(23, productInfoDAO.getQuantity2());
	        			insertProductListPSMT.setString(24, productInfoDAO.getBatchId());
	        			insertProductListPSMT.setString(25, productInfoDAO.getExpiryDate());
	        			
	        			insertProductListPSMT.addBatch();
	        			if(productInfoDAO.getProductReturn() != null)
	        			{
		        			if(productInfoDAO.getProductReturn())
		        			{
		        				stockMinus  = UpdateProductStockDetails.addStockToCurrentStock(connection, this.getSessionMap(), productInfoDAO.getProductId(),  productInfoDAO.getProductName(),  productInfoDAO.getQuantity());
			        			
		        			}

		        			else
		        			{
		        			    String assignedGodownCode =
		        			        (String) this.getSessionMap().get("assignedGodownCode");

		        			    System.out.println("Assigned Godown Code = " + assignedGodownCode);

		        			    if (assignedGodownCode == null ||
		        			        assignedGodownCode.trim().isEmpty())
		        			    {
		        			        throw new SQLException("Assigned Godown code is missing.");
		        			    }

		        			    if ("MAIN".equalsIgnoreCase(assignedGodownCode.trim()))
		        			    {
		        			        // MAIN stock: shop_product_master
		        			        stockMinus = UpdateProductStockDetails.minusStockToCurrentStock(
		        			            connection,
		        			            this.getSessionMap(),
		        			            productInfoDAO.getProductId(),
		        			            productInfoDAO.getProductName(),
		        			            productInfoDAO.getQuantity(),
		        			            productInfoDAO.getQuantity2()
		        			        );

		        			        if (!stockMinus)
		        			        {
		        			            throw new SQLException("Could not deduct MAIN stock.");
		        			        }
		        			    }
		        			    else
		        			    {
		        			        // Assigned Godown stock: warehouse_stock_master
		        			        stockMinus =
		        			            UpdateProductStockDetails.minusStockFromAssignedGodown(
		        			                connection,
		        			                this.getSessionMap(),
		        			                productInfoDAO.getProductId(),
		        			                productInfoDAO.getQuantity()
		        			            );

		        			        if (!stockMinus)
		        			        {
		        			            throw new SQLException(
		        			                "Insufficient stock or product not found in Godown: "
		        			                + assignedGodownCode
		        			            );
		        			        }
		        			    }
		        			}

	        			}
	        			
	        			}
	        			
	        			
	        			int[] productInserted  = insertProductListPSMT.executeBatch();
	        		
	        			
	        			if((productInserted.length == this.getProductInfoList().size()) && stockMinus)
		        		{
	        				

							sql = "SELECT "
		  							+ "account_credit_debit_id "
		  							+ "FROM "
		  							+ "shop_bill_info_master "
		  							+ "WHERE "
				        			+ "bill_number = ? "
				        			+ "AND "
				        			+ "bill_type = ? "
				        			+ "AND "
				        			+ "customer_id = ? "
				        			+ "AND "
				        			+ "shop_id = ? "
									+ "AND "
									+ "shop_code = ?";
							
							preparedStatement = connection.prepareStatement(sql);
						
							preparedStatement.setString(1,this.getBillInfoDAO().getBillNumber());
							preparedStatement.setString(2,this.getBillInfoDAO().getBillType());
				        	preparedStatement.setString(3,this.getBillInfoDAO().getCustId());   
				        	preparedStatement.setString(4, shopId);
							preparedStatement.setString(5, shopCode);
							
							resultSet = preparedStatement.executeQuery();
							
							
							if(resultSet.next()){
								String accCrditDebitId = resultSet.getString(1);
								
								if(accCrditDebitId != null && !accCrditDebitId.equals("") )
								{
								
									if(preparedStatement != null)
									{
										preparedStatement.close();
										preparedStatement = null;
									}
									if(resultSet != null)
									{
										resultSet.close();
										resultSet = null;
									}
									
									
								sql = "SELECT "
										+ "entry_id,"
										+ "account_id,"
										+ "account_number,"
										+ "entry_date,"
										+ "entry_time,"
										+ "entry_type,"
										+ "amount,"
										+ "payment_type,"
										+ "entry_by,"
										+ "entry_details "
										+ "FROM "
										+ "bank_account_credit_debit_master "
										+ "WHERE "
										+ "entry_id = ? "
										+ "AND "
										+ "shop_id = ? "
										+ "AND "
										+ "shop_code = ? ";
								
								preparedStatement = connection.prepareStatement(sql);
								preparedStatement.setString(1, accCrditDebitId);
								preparedStatement.setString(2, shopId);
								preparedStatement.setString(3, shopCode);

								
								resultSet = preparedStatement.executeQuery();
								
								int m = 0;
								if(resultSet.next())
								{
									
									PreparedStatement  insertIntoDeletedPSMT = null;
									
									String inertDeletedSQL = "INSERT "
											+ "INTO "
											+ "bank_account_credit_debit_updated_entry_master "
											+ "("
											+ "entry_id,"
											+ "shop_id,"
											+ "shop_code,"
											+ "account_id,"
											+ "account_number,"
											+ "entry_date,"
											+ "entry_time,"
											+ "entry_type,"
											+ "amount,"
											+ "payment_type,"
											+ "entry_by,"
											+ "entry_details) "
											+ "VALUES "
											+ "(?,?,?,?,?,?,?,?,?,?,?,?)";
									
									insertIntoDeletedPSMT = connection.prepareStatement(inertDeletedSQL);
									
									insertIntoDeletedPSMT.setString(1, accCrditDebitId);
									insertIntoDeletedPSMT.setString(2, shopId);
									insertIntoDeletedPSMT.setString(3, shopCode);
									insertIntoDeletedPSMT.setString(4, resultSet.getString(2));
									insertIntoDeletedPSMT.setString(5, resultSet.getString(3));
									insertIntoDeletedPSMT.setString(6, resultSet.getString(4));
									insertIntoDeletedPSMT.setTime(7, resultSet.getTime(5));
									insertIntoDeletedPSMT.setString(8, resultSet.getString(6));
									insertIntoDeletedPSMT.setFloat(9, this.getAmountPaid());
									insertIntoDeletedPSMT.setString(10, resultSet.getString(8));
									insertIntoDeletedPSMT.setString(11, billedBy);
									insertIntoDeletedPSMT.setString(12, resultSet.getString(10));
									
									
									  m = insertIntoDeletedPSMT.executeUpdate();
									  
									  String paymentType = resultSet.getString(6);
									  
									  
									  SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
										Date parsedDate = null;

										try {
										    parsedDate = inputDateFormat.parse(resultSet.getString(4)); 
										} catch (ParseException e) {
										    e.printStackTrace();  
										}

										if (parsedDate != null) {
										     SimpleDateFormat outputDateFormat = new SimpleDateFormat("dd-MM-yyyy");
										    String formattedDate = outputDateFormat.format(parsedDate); 
							
										    
									 
									    
									    
									  boolean isCloseingBalMaintained = false;
									  
									  if (paymentType.equals("CREDIT")) {
									   isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(resultSet.getString(2),"DEBIT", formattedDate, resultSet.getFloat(7), billedBy, connection, this.getSessionMap());
									  }else {
										   isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(resultSet.getString(2),"CREDIT", formattedDate, resultSet.getFloat(7), billedBy, connection, this.getSessionMap());
										  
									  }
										}
									  
									if(insertIntoDeletedPSMT != null)
									{
										insertIntoDeletedPSMT.close();
										insertIntoDeletedPSMT = null;
									}
									
								}
								if(resultSet != null)
								{
									resultSet.close();
									resultSet = null;
								}
								if(preparedStatement != null)
								{
									preparedStatement.close();
									preparedStatement = null;
								}
								
								
								if(m>0)
								{
									
									
								
								sql = "DELETE "
										+ "FROM "
										+ "bank_account_credit_debit_master "
										+ "WHERE "
										+ "entry_id = ? "
										+ "AND "
										+ "shop_id = ? "
										+ "AND "
										+ "shop_code = ? ";
								
								preparedStatement = connection.prepareStatement(sql);
								preparedStatement.setString(1, accCrditDebitId);
								preparedStatement.setString(2, shopId);
								preparedStatement.setString(3, shopCode);
								
								int k = preparedStatement.executeUpdate();
								
								if(k > 0 )

								{
									
									sql = "UPDATE "
            	        					+ "shop_bill_info_master "
            	        					+ "SET "
            	        					+ "account_credit_debit_id = ? "
            	        					+ "WHERE "
            			        			+ "bill_number = ? "
            			        			+ "AND "
            			        			+ "bill_type = ? "
            			        			+ "AND "
            			        			+ "customer_id = ? "
            			        			+ "AND "
            			        			+ "shop_id = ? "
            								+ "AND "
            								+ "shop_code = ?";
            	        			
            	        			
    	    						preparedStatement = connection.prepareStatement(sql);
    	    						
    	    						preparedStatement.setString(1, null);
    	    						preparedStatement.setString(2,this.getBillInfoDAO().getBillNumber());
    	    						preparedStatement.setString(3,this.getBillInfoDAO().getBillType());
    	    			        	preparedStatement.setString(4,this.getBillInfoDAO().getCustId());   
    	    			        	preparedStatement.setString(5, shopId);
    	    						preparedStatement.setString(6, shopCode);
    	    						
    	    						 preparedStatement.executeUpdate();
    	        				
    	    						
    	    						
									
								}
				    		}
						}
								
								
							}
	        				
							
		        				
	        				int rowInsetred = 0;
	        				boolean isCloseingBalMaintained = false;
	        				int rowCreditDebitIdInsetred = 0;
							
	        				if(this.getAmountPaid() > 0)
		        				{
		        				
			        				if(preparedStatement != null)
									{
										preparedStatement.close();
										preparedStatement = null;
									}
								
								
								sql = "SELECT "
										+ "entry_id "
										+ "FROM "
										+ "bank_account_credit_debit_master "
										+ "ORDER BY "
										+ "entry_id "
										+ "DESC LIMIT 1;";
								
							
							preparedStatement = connection.prepareStatement(sql);
							resultSet = preparedStatement.executeQuery();
							
							int creditEntryId = 1;
						
							if(resultSet.next())
							{
								if(!(resultSet.getString(1) == null))
								{
									creditEntryId = Integer.parseInt(resultSet.getString(1));
									creditEntryId = creditEntryId + 1;
									
								}
								
							}
							else
							{	creditEntryId =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  = ?";
			        			
			        		preparedStatement = connection.prepareStatement(sql);
			        		
			        		preparedStatement.setString(1, this.getAccountId());
			        		
			        		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, creditEntryId);
								preparedStatement.setString(2, shopId);
								preparedStatement.setString(3, shopCode);
								preparedStatement.setString(4, this.getAccountId());
								preparedStatement.setString(5, accountNumber);
								preparedStatement.setString(6, this.getBillDateTime());
								preparedStatement.setTime(7, time);
								preparedStatement.setString(8, "CREDIT");
								preparedStatement.setFloat(9, this.getAmountPaid());
								preparedStatement.setString(10, this.getModeOfPayment());
								preparedStatement.setString(11, billedBy);
								preparedStatement.setString(12, "PAID BY "+this.getBillInfoDAO().getCustomerName()+" AGAINST BILL No: "+this.getBillInfoDAO().getBillNumber());
								
								 rowInsetred = preparedStatement.executeUpdate();
								
								
								 isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(this.getAccountId(),"CREDIT", this.getBillDateTime(), this.getAmountPaid(), billedBy, connection, this.getSessionMap());
								
								 if(rowInsetred > 0 && isCloseingBalMaintained)
	    							{
	    								

	    								sql = "UPDATE "
	            	        					+ "shop_bill_info_master "
	            	        					+ "SET "
	            	        					+ "account_credit_debit_id = ? "
	            	        					+ "WHERE "
	            			        			+ "bill_number = ? "
	            			        			+ "AND "
	            			        			+ "customer_id = ? "
	            			        			+ "AND "
	            			        			+ "bill_type = ? "
	            			        			+ "AND "
	            			        			+ "shop_id = ? "
	            								+ "AND "
	            								+ "shop_code = ?";
	            	        			
	            	        			
	    	    						preparedStatement = connection.prepareStatement(sql);
	    	    						
	    	    						preparedStatement.setInt(1, creditEntryId);
	    	    						preparedStatement.setString(2,this.getBillInfoDAO().getBillNumber());
	    	    			        	preparedStatement.setString(3,this.getBillInfoDAO().getCustId());   
	    	    			        	preparedStatement.setString(4, this.getBillInfoDAO().getBillType());
	    	    			        	preparedStatement.setString(5, shopId);
	    	    						preparedStatement.setString(6, shopCode);
	    	    						
	    	    						 rowCreditDebitIdInsetred = preparedStatement.executeUpdate();
	    	        				
	    							}
	        				}
	        				else
	        				{
	        					rowInsetred = 1;
	        					isCloseingBalMaintained = true;
	        				}
	        				
	        				
    						if(rowInsetred > 0 && isCloseingBalMaintained)
    						{
		        				
		        				
		        				this.getSessionMap().remove("deletedProductList");
		        				
		        				connection.commit();
		        				
		        				if(countBillInfoInserted > 0)
		        				{
		        					this.getBillInfoDAO().setBillInformationInserted(true);
		        				}
		        				
		        				
		        				
		        				this.getBillInfoDAO().setBillSaved(true);
		    	        		this.setBillSaved(true);
		    	        		this.setBillDateTime(this.getBillInfoDAO().getBillDate());
		    	        		this.setCustomerName(this.getBillInfoDAO().getCustomerName());
		    	        		this.setBillNumber(this.getBillInfoDAO().getBillNumber());
		    	        		this.setBillType(this.getBillInfoDAO().getBillType());
		    	        		this.setAlternateMobileNumber(this.getBillInfoDAO().getCustomerMobile());
		    	        		this.setSendSMS(this.getBillInfoDAO().isSendSMS());
		    	        		this.setTotalAmount(""+(floatTotalAmount+transportChargeFloat));	        	
		    	        		this.setTotalDiscount(""+floatTotalDiscount);
		    	        		this.setTotalAmouAfterDisount(""+(floatTotalAmtAfterDiscount+transportChargeFloat));
		    		      
		    	        		
		    	        		paymentTypeList.put("CASH","CASH");
		    		        	paymentTypeList.put("CREDIT","CREDIT");
		    		        	
		    		        	this.setDefaultValue(this.getBillInfoDAO().getPaymentType());
		    		        	
	
		    		        	try {taxList = GetListResource.GetTaxList(this.getSessionMap());}catch (Exception e) {}
		    		        	
		    		        	unitList = GetListResource.GetUnitList();
		    		        	billTypeList = GetListResource.GetBillTypeList();
		    		        	
		    		        	
		    		        	
		    		        	
		    		        	
		    	        		addActionMessage("Bill details Saved Successfully !");
		    	        		
		    	        		this.getSessionMap().put("billInformation", this.getBillInfoDAO());
		    	        		this.getSessionMap().put("productList", this.getProductInfoList());
		    	        		result =  SUCCESS;
		    	        		this.setBillSave("true");
		    	        		
		    	        		
		    	        		
		    	        		String messageServiceProvider = (String) this.getSessionMap().get("serviceprovider");
		    	        		if(messageServiceProvider == null || messageServiceProvider.trim().isEmpty())
		    	        		{
		    	        			messageServiceProvider = "BULKSMSGATEWAY";
		    	        		}
		    	        		
	    	        			
		    	        		if(this.getBillInfoDAO().isSendSMS() || this.isSendDirectSMS())
		    	        		{
		    	        			boolean allOkSMSSettings = true;
		    	        			boolean sendWhatsAppMessage = WhatsAppSettingsUtil.isWhatsAppSendingEnabled(this.getSessionMap());
	    	        			
		    	        			String shopNameMarathi=(String) this.getSessionMap().get("shopnamemarathi");
		    	        		
		    	        			String mobileNumber = WhatsAppSettingsUtil.resolveTargetMobile(this.getSessionMap(), this.getBillInfoDAO().getCustomerMobile());
		    	        			
		    	        			
		    	        		Float custCreditAmount =	GetCustomerCreditAmountById.getCustomerCreditAmountById(this.getBillInfoDAO().getCustId(), this.getSessionMap());
		    	        			
		    	        			
		    	        		if(!sendWhatsAppMessage)
								{
									addActionMessage("WhatsApp message sending is disabled in settings.");
								}
								else if(!WhatsAppSettingsUtil.isValidMobileNumber(mobileNumber))
								{
									addActionMessage("Invalid mobile number. WhatsApp message not sent.");
								}
								else if("INFRAINFOTECH".equals(messageServiceProvider) && allOkSMSSettings)
								{
		    	        			

		    	        			String defaultMessageLang = "MARATHI";
		    	        			
		    	        			String msg = "";
		    	        			
		    	        			if(defaultMessageLang.equals("MARATHI"))
		    	        			{
		    	        				msg = "*" + shopNameMarathi + "* मधून खरेदी केल्याबद्दल धन्यवाद!";
		    	        				msg = msg + "\nबिल नंबर : "+this.getBillInfoDAO().getBillNumber();
		    	        				msg = msg + "\nबिल तारीख : "+this.getBillInfoDAO().getBillDate();
		    	        				msg = msg + "\nएकूण बिल रक्कम : "+this.getBillInfoDAO().getTotalAfterDiscountBillAmount();
		    	        				msg = msg + "\nएकूण येणे बाकी : "+custCreditAmount;
			    	        			
										
		    	        			}

		    						
									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 = "";
										boolean sendWithPdf = WhatsAppSettingsUtil.shouldSendWhatsAppWithPdf(this.getSessionMap(),
												this.getBillWhatsAppMessageType());
								
										if(sendWithPdf)
										{
											String pageSize = WhatsAppSettingsUtil.resolveWhatsAppPdfBillType(this.getBillWhatsAppPdfType());
											String key = WhatsAppSettingsUtil.encryptWithoutSessionKeyPart(this.getBillInfoDAO().getBillNumber()) + "."
													+ WhatsAppSettingsUtil.encryptWithoutSessionKeyPart(pageSize) + "."
													+ WhatsAppSettingsUtil.encryptWithoutSessionKeyPart("eng") + "."
													+ WhatsAppSettingsUtil.encryptWithoutSessionKeyPart(this.getBillType()) + "."
													+ WhatsAppSettingsUtil.encryptWithoutSessionKeyPart(shopId) + "."
													+ WhatsAppSettingsUtil.encryptWithoutSessionKeyPart(shopCode) + ".";
											String encodedKey = URLEncoder.encode(key, "UTF-8");
											String attachmentAction = "THERMAL".equalsIgnoreCase(pageSize)
													? "printBillWithOutSessionThermal"
													: "printBillWithOutSession";
											String fileUrl = "https://easysbill.com/" + attachmentAction + "?key=" + encodedKey + "pdf";
											
											if(!"THERMAL".equalsIgnoreCase(pageSize))
											{
												fileUrl = fileUrl + "&billType=" + URLEncoder.encode(pageSize, "UTF-8");
											}
										
											String fileName = "bill.pdf";
											resp = SendWhatsAppMessage.sendMessageWithFile(userName, mobileNumber, msg,
													tokenNumber, fileUrl, fileName);
										}
										else
										{
											resp = SendWhatsAppMessage.sendMessageOnly(userName, mobileNumber, msg, tokenNumber);
										}
										
									
			    	        			
			    	        			if(WhatsAppSettingsUtil.isFailedResponse(resp))
			    	        			{
			    	        				addActionMessage("Bill saved, but couldn't send WhatsApp 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) {
											addActionMessage("Bill saved, but couldn't send WhatsApp message: "+e.getMessage());
										}
									}
									else
									{
										addActionMessage("Bill saved. WhatsApp token mapping not found for defaultWhatsAppNumber.");
									}
		    					
		    					
								}
								else
								{
									addActionMessage("Bill saved, but WhatsApp message was not sent.");
								}
		    	        	} // Hello
						}else
						{
							connection.rollback();
	        				result = "error";
	        				addActionError("Bill Not Saved ! Error while cr entry and closing bal. entry! Please try again!");
						}
		    	        		
		        		}
	        			else
	        			{
	        				connection.rollback();
	        				result = "error";
	        				addActionError("Bill Not Saved Properly ! Please check product stock!");
	        			}
	        			if(insertProductListPSMT != null)
        				{
        					insertProductListPSMT.close();
        					insertProductListPSMT = null;
        				}
					}else
					{
						connection.rollback();
						result = "error";
						addActionError("Problem occered while deleted old rows! Please try again!");
					}
	        			
	        		
	        	}
	        	else
	        	{
	        		connection.rollback();
	        		result = "error";
	        		addActionError("Bill details not saved! Please try again!");
	        	}
	        		
	        	}
	        	catch (SQLException e) {
	        		
	        		e.printStackTrace();
	        		
	        		boolean duplicateBillSave = isDuplicateBillSaveException(e);
	        		
	        		try {
	        			if(connection != null)
	        			{
	        				connection.rollback();
	        			}
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
	        		
	        		if(duplicateBillSave)
	        		{
	        			boolean alreadySaved = false;
	        			try
	        			{
	        				if(connection != null && this.getBillInfoDAO() != null)
	        				{
	        					alreadySaved = isBillHeaderAlreadyPresent(connection, this.getBillInfoDAO().getBillType(),
	        							this.getBillInfoDAO().getBillNumber(), billDateTime, shopId, shopCode);
	        				}
	        			}
	        			catch (SQLException checkEx)
	        			{
	        				checkEx.printStackTrace();
	        			}
	        			
	        			if(alreadySaved)
	        			{
	        				result = SUCCESS;
	        				this.setBillSave("true");
	        				this.setBillSaved(true);
	        				if(this.getBillInfoDAO() != null)
	        				{
	        					this.getBillInfoDAO().setBillSaved(true);
	        				}
	        				addActionMessage("Bill was already saved. Duplicate save request ignored.");
	        			}
	        			else
	        			{
		        			result = ERROR;
		        			this.setBillSave("false");
		        			this.setBillSaved(false);
		        			if(this.getBillInfoDAO() != null)
		        			{
		        				this.getBillInfoDAO().setBillSaved(false);
		        			}
		        			addActionError("Duplicate save request ignored. Bill Not Saved!");
	        			}
	        		}
	        		else
	        		{
						e.printStackTrace();
						result = "error";
						this.setBillSave("false");
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" ||1 Bill details not Saved ! Please try again!");
	        		}
				} catch (IOException e) {
					e.printStackTrace();
					
					result = "error";
					this.setBillSave("false");
					addActionError(e.getMessage()+" || "+e.getCause()+" ||2 Bill details not Saved! Please try again!");
				}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) {}
					}
					
					}
	        	}
	        	else
	        	{
	        		
		        	float floatTotalAmount = 0.0F;
		        	float floatTotalDiscount = 0.0F;
		        	float floatTotalAmtAfterDiscount = 0.0F;
		        	
		        	for(BillProductInfoDAO infoDAO : productInfoList)
		        	{
		        		floatTotalAmount  = floatTotalAmount+ infoDAO.getAmount();
		        		floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount + infoDAO.getAmountAfterDiscount();
		        		floatTotalDiscount = floatTotalDiscount + infoDAO.getProductTotalDiscount();
		        		
		        	}
		        	
		        	
		        	
	        		this.getSessionMap().put("productList", this.getProductInfoList());
	        		
	        		this.setCustomerName(this.getBillInfoDAO().getCustomerName());
	        		this.setBillNumber(this.getBillInfoDAO().getBillNumber());
	        		this.setBillType(this.getBillInfoDAO().getBillType());
	        		//System.out.println(getAlternateMobileNumber());
	        		
	        		this.setAlternateMobileNumber(this.getBillInfoDAO().getCustomerMobile());
	        		this.setSendSMS(this.getBillInfoDAO().isSendSMS());
	        		float transportCharge = 0.0F;
	        		
	        		if(this.getBillInfoDAO().getTransportCharge()==null || this.getBillInfoDAO().getTransportCharge().equals(""))
	        		{
	        			this.getBillInfoDAO().setTransportCharge(0.0F);
	        		}
		        	
		        		
		        		try
		        		{
		        			transportCharge = this.getBillInfoDAO().getTransportCharge();
		        			
		        		}catch(NumberFormatException nfe)
		        		{
		        			addActionError("Please provide correct transportaion amount!");
		        		}
		        	
		        	
		        	if(!hasActionErrors())
		        	{
			        	this.setTotalAmount(""+(floatTotalAmount+transportCharge));	        	
			        	this.setTotalDiscount(""+floatTotalDiscount);
			        	this.setTotalAmouAfterDisount(""+(floatTotalAmtAfterDiscount+transportCharge));
			        	addActionMessage("Product added successfully to list !");
		        	}
		        	else
		        	{
		        		this.setTotalAmount(""+floatTotalAmount);	        	
		        		this.setTotalDiscount(""+floatTotalDiscount);
		        		this.setTotalAmouAfterDisount(""+floatTotalAmtAfterDiscount);
			        	addActionMessage("Product added successfully to list !");
		        	}
		        	
	        		paymentTypeList.put("CASH","CASH");
		        	paymentTypeList.put("CREDIT","CREDIT");
		        	
		        	this.setDefaultValue(this.getBillInfoDAO().getPaymentType());
		        	

		        	taxList = GetListResource.GetTaxList(this.getSessionMap());
		        	
		        	unitList = GetListResource.GetUnitList();
		        	billTypeList = GetListResource.GetBillTypeList();
		        	this.getSessionMap().put("billInformation", this.getBillInfoDAO());
		        	this.getSessionMap().put("productList", this.getProductInfoList());
	        		result = "success";
	        		addActionError("Bill Already Saved !");
	        		
	        		this.setBillSaved(true);
	        	}
	        	}	
	        }
	       // System.out.print(result);
	        return result;
		
	}
	@SuppressWarnings("unchecked")
	@Override
	public void validate() {
		
		
    	
		if(this.getAmountPaid() == null || this.getAmountPaid().equals(""))
		{
			addActionError("Amount Paid Null ! Bill Cannot be Saved !");
		}
		
		if(!hasActionErrors())
		{
			if(this.getReturnAmount() == null || getReturnAmount().equals(""))
			{
				addActionError("Return amount Null ! Bill Cannot be Saved !");
			}
		}
		

		productInfoList = (List<BillProductInfoDAO>) sessionMap.get("productList");		        	
    	billInfoDAO = (BillInformationDAO) sessionMap.get("billInformation");
    	
    	if(productInfoList == null || productInfoList.isEmpty() || billInfoDAO == null)
    	{
    		addActionError("Bill session expired or no product available. Please add product again.");
    		return;
    	}
    	
    	float floatTotalAmount = 0.0F;
    	float floatTotalDiscount = 0.0F;
    	float floatTotalAmtAfterDiscount = 0.0F;
    	
    	for(BillProductInfoDAO infoDAO : productInfoList)
    	{
    		floatTotalAmount  = floatTotalAmount+ infoDAO.getAmount();
    		floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount + infoDAO.getAmountAfterDiscount();
    		floatTotalDiscount = floatTotalDiscount + infoDAO.getProductTotalDiscount();
    		
    	}
    	
    
    	this.setCustomerIdNameAll(billInfoDAO.getCustId()+"-"+billInfoDAO.getCustomerName()+"-"+billInfoDAO.getCustomerMobile()+"-REGULER");
    	this.setCustomerName(billInfoDAO.getCustomerName());
    	this.setCustomerId(billInfoDAO.getCustId());
    	this.setCustomerMobileNumber(billInfoDAO.getCustomerMobile());
    	this.setCustomerType(billInfoDAO.getCustomerType());
    	this.setBillNumber(billInfoDAO.getBillNumber());
    	this.setBillType(billInfoDAO.getBillType());
    	this.setBillDateTime(billInfoDAO.getBillDate());
		
		
		if(this.getTransportCharge() == null || this.getTransportCharge() < 0)
		{
    		
			
	    			addActionError("Please provide correct transportaion amount!");
	    	
    	}
    	
			if(billInfoDAO.getDirectDiscountAmount() == null)
			{
				billInfoDAO.setDirectDiscountAmount(0.0f);
			}
		
			floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount-billInfoDAO.getDirectDiscountAmount();
        	this.setTotalAmount(""+(floatTotalAmount+this.getTransportCharge()));	        	
        	this.setTotalDiscount(""+floatTotalDiscount);
        	this.setTotalPaybleAmount(""+(floatTotalAmount+transportCharge));
        	this.setTotalAmouAfterDisount(""+(floatTotalAmtAfterDiscount+transportCharge));
        	addActionMessage("Product added successfully to list !");
    	
    	
        	this.paymentTypeList.put("CASH","CASH");
        	this.paymentTypeList.put("CREDIT","CREDIT");
    	
        	this.setDefaultValue(billInfoDAO.getPaymentType());
    	
        	taxList = GetListResource.GetTaxList(this.getSessionMap());
    	
    	unitList = GetListResource.GetUnitList();
    	billTypeList = GetListResource.GetBillTypeList();
    	
    	if(!hasActionErrors())
    	{
    		if(this.getBillInfoDAO().getPaymentType().equals("CASH"))
    		{
    			if(this.getAmountPaid() <  floatTotalAmtAfterDiscount)
    			{
    				addActionError("Bill type is cash! Paid amount cannot be less than amount payble!");
    			}
    				
    		}
    		else if(this.getBillInfoDAO().getPaymentType().equals("CREDIT"))
    		{
    			if(this.getAmountPaid() > 0)
    			{
    				addActionError("Bill type is credit! Paid amount cannot be more than 0!");
    			}
    		}
    	}
    	
    	if(!hasActionErrors())
    	{
    		if(this.getAccountId() == null || this.getAccountId().equals(""))
    		{
    			addActionError("Please select account for Credit entry! ");
    		}
    		
    	}
    	
    	
    	this.getRateTypeList().put("INCLUDEGST", "WITH GST");
    	this.getRateTypeList().put("EXCLUDEGST", "WITH-OUT GST");
    	
    	this.setRateType( ((HashMap<String, String>) this.getSessionMap().get("shop_settings")).get("default_rate_type"));
        
    	HashMap<String, String> settings = (HashMap<String, String>) this.getSessionMap().get("shop_settings");
        
    	this.setDiscountType(settings.get("discount_type"));
        
    	this.setDirectDiscountAmount(billInfoDAO.getDirectDiscountAmount());
		this.getSessionMap().put("billInformation", this.getBillInfoDAO());
		this.getSessionMap().put("productList", this.getProductInfoList());
		
		paymentTypeList2.add("CASH");
    	paymentTypeList2.add("UPI");
    	paymentTypeList2.add("RTGS");
    	paymentTypeList2.add("NEFT");
    	paymentTypeList2.add("CHEQUE");
    	
		this.setAccountList(GetAccountListForDrCr.getAccountList((this.getSessionMap()))); 
	   	this.setCustomerTypeList(GetListResource.getCustomerTypeList());
	      
	}
	
	
 
	public Float getDirectDiscountAmount() {
		return directDiscountAmount;
	}
	public void setDirectDiscountAmount(Float directDiscountAmount) {
		this.directDiscountAmount = directDiscountAmount;
	}
	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	public BillInformationDAO getBillInfoDAO() {
		return billInfoDAO;
	}

	public void setBillInfoDAO(BillInformationDAO billInfoDAO) {
		this.billInfoDAO = billInfoDAO;
	}

	public List<BillProductInfoDAO> getProductInfoList() {
		return productInfoList;
	}

	public void setProductInfoList(List<BillProductInfoDAO> productInfoList) {
		this.productInfoList = productInfoList;
	}
	
	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 Map<String, String> getPrintTypeList() {
		return printTypeList;
	}

	public void setPrintTypeList(Map<String, String> printTypeList) {
		this.printTypeList = printTypeList;
	}

	public String getDefaultValue() {
		return defaultValue;
	}

	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}

	public String getBillType() {
		return billType;
	}

	public void setBillType(String billType) {
		this.billType = billType;
	}

	public String getPrintType() {
		return printType;
	}

	public void setPrintType(String printType) {
		this.printType = printType;
	}

	public String getCustomerName() {
		return customerName;
	}

	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}

	public String getBillNumber() {
		return billNumber;
	}

	public void setBillNumber(String billNumber) {
		this.billNumber = billNumber;
	}

	public String getTotalAmount() {
		return totalAmount;
	}

	public void setTotalAmount(String totalAmount) {
		this.totalAmount = totalAmount;
	}

	public String getTotalDiscount() {
		return totalDiscount;
	}

	public void setTotalDiscount(String totalDiscount) {
		this.totalDiscount = totalDiscount;
	}

	public String getTotalAmouAfterDisount() {
		return totalAmouAfterDisount;
	}

	public void setTotalAmouAfterDisount(String totalAmouAfterDisount) {
		this.totalAmouAfterDisount = totalAmouAfterDisount;
	}

	public String getTotalPaybleAmount() {
		return totalPaybleAmount;
	}

	public void setTotalPaybleAmount(String totalPaybleAmount) {
		this.totalPaybleAmount = totalPaybleAmount;
	}

	
	


	public Float getAmountPaid() {
		return amountPaid;
	}
	public void setAmountPaid(Float amountPaid) {
		this.amountPaid = amountPaid;
	}
	public String getReturnAmount() {
		return returnAmount;
	}

	public void setReturnAmount(String returnAmount) {
		this.returnAmount = returnAmount;
	}



	public String getAlternateMobileNumber() {
		return alternateMobileNumber;
	}



	public void setAlternateMobileNumber(String alternateMobileNumber) {
		this.alternateMobileNumber = alternateMobileNumber;
	}



	public boolean isSendSMS() {
		return sendSMS;
	}



	public void setSendSMS(boolean sendSMS) {
		this.sendSMS = sendSMS;
	}
	public boolean isBillSaved() {
		return billSaved;
	}
	public void setBillSaved(boolean billSaved) {
		this.billSaved = billSaved;
	}
	public String getBillDateTime() {
		return billDateTime;
	}
	public void setBillDateTime(String billDateTime) {
		this.billDateTime = billDateTime;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	
	public Float getTransportCharge() {
		return transportCharge;
	}
	public void setTransportCharge(Float transportCharge) {
		this.transportCharge = transportCharge;
	}
	public String getComments() {
		return comments;
	}
	public void setComments(String comments) {
		this.comments = comments;
	}
	public String getBillSave() {
		return billSave;
	}
	public void setBillSave(String billSave) {
		this.billSave = billSave;
	}
	public List<BillProductInfoDAO> getDeletedProductInfoList() {
		return deletedProductInfoList;
	}
	public void setDeletedProductInfoList(List<BillProductInfoDAO> deletedProductInfoList) {
		this.deletedProductInfoList = deletedProductInfoList;
	}
	public String getPaymentType() {
		return paymentType;
	}
	public void setPaymentType(String paymentType) {
		this.paymentType = paymentType;
	}
	public boolean isSendDirectSMS() {
		return sendDirectSMS;
	}
	public void setSendDirectSMS(boolean sendDirectSMS) {
		this.sendDirectSMS = sendDirectSMS;
	}
	public String getBillWhatsAppMessageType() {
		return billWhatsAppMessageType;
	}
	public void setBillWhatsAppMessageType(String billWhatsAppMessageType) {
		this.billWhatsAppMessageType = billWhatsAppMessageType;
	}
	public String getBillWhatsAppPdfType() {
		return billWhatsAppPdfType;
	}
	public void setBillWhatsAppPdfType(String billWhatsAppPdfType) {
		this.billWhatsAppPdfType = billWhatsAppPdfType;
	}
	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 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 List<String> getPaymentTypeList2() {
		return paymentTypeList2;
	}
	public void setPaymentTypeList2(List<String> paymentTypeList2) {
		this.paymentTypeList2 = paymentTypeList2;
	}
	public String getModeOfPayment() {
		return modeOfPayment;
	}
	public void setModeOfPayment(String modeOfPayment) {
		this.modeOfPayment = modeOfPayment;
	}
	public String getAccountId() {
		return accountId;
	}
	public void setAccountId(String accountId) {
		this.accountId = accountId;
	}
	public Map<String, String> getAccountList() {
		return accountList;
	}
	public void setAccountList(Map<String, String> accountList) {
		this.accountList = accountList;
	}
	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 getDiscountType() {
		return discountType;
	}
	public void setDiscountType(String discountType) {
		this.discountType = discountType;
	}
	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;
	}
	
	private boolean isDuplicateBillSaveException(SQLException e) {
		if (e == null) {
			return false;
		}
		String sqlState = e.getSQLState();
		int errorCode = e.getErrorCode();
		String message = e.getMessage();
		if (message == null) {
			return false;
		}
		String normalized = message.toLowerCase();
		boolean duplicateCode = errorCode == 1062;
		boolean duplicateState = "23000".equals(sqlState) || "23505".equals(sqlState);
		boolean duplicateMessage = normalized.contains("duplicate entry")
				&& normalized.contains("shop_bill_info_master.primary");
		return duplicateCode || (duplicateState && duplicateMessage);
	}
	
	private boolean isBillHeaderAlreadyPresent(Connection connection, String billType, String billNumber, String billDate, String shopId,
			String shopCode) throws SQLException {
		PreparedStatement localPS = null;
		ResultSet localRS = null;
		try {
			String sql = "SELECT 1 FROM shop_bill_info_master "
					+ "WHERE bill_type = ? AND bill_number = ? AND bill_date=STR_TO_DATE(?,'%d-%m-%Y') AND shop_id = ? AND shop_code = ? LIMIT 1";
			localPS = connection.prepareStatement(sql);
			localPS.setString(1, billType);
			localPS.setString(2, billNumber);
			localPS.setString(3, billDate);
			localPS.setString(4, shopId);
			localPS.setString(5, shopCode);
			localRS = localPS.executeQuery();
			return localRS.next();
		} finally {
			if(localRS != null)
			{
				try { localRS.close(); } catch (SQLException e) {}
			}
			if(localPS != null)
			{
				try { localPS.close(); } catch (SQLException e) {}
			}
		}
	}
	

	
}
