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.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.opensymphony.xwork2.ActionSupport;
import com.stonecrusher.infrawhatsappmsg.CheckBalance;
import com.reallinkbilling.DAO.BillInformationDAO;
import com.reallinkbilling.DAO.BillProductInfoDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.stonecrusher.infrawhatsappmsg.SendWhatsAppMessage;
import com.reallinkbilling.resource.GetListResource;
import com.reallinkbilling.update.UpdateProductStockDetails;
import com.reallinkbilling.utils.GetCustomerCreditAmountById;
import com.reallinkbilling.utils.WhatsAppSettingsUtil;
import com.realllinkbilling.message.AddTextLocalResponseToDB;
import com.realllinkbilling.message.SendTextLocalMessage;

public class BillSaveBarcode extends ActionSupport implements SessionAware{
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 8028964576199571759L;
	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 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;
    // Salesman commission inputs
    private String salesmanIdName; // format: ID-NAME-MOBILE-% (from JSON)
    private Float commissionPercentage; // optional: not required from UI; resolved from master when null
    private String salesmanId; // preferred explicit salesman id if provided
	

	private ArrayList<String> customerTypeList = new ArrayList<String>();
	private String customerType;
	private String customerId;
	private String customerMobileNumber;

	private String customerIdNameAll;
	
	private ArrayList<String> serailBatchIdList = new ArrayList<String>();
	private String serailNoBatchId;
	
	@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((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.setTotalAmouAfterDisount(""+floatTotalAmtAfterDiscount);
		        	
	        		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"));

            	// Ensure latest mobile typed on the page is persisted
            	/*try{
            		
            		System,out.println("");
            		
            		String latestMobile = (this.getAlternateMobileNumber()!=null)? this.getAlternateMobileNumber().trim() : "";
            		if(latestMobile.length()>=8){
            			String combined = this.getBillInfoDAO().getCustomerName();
            			if(combined!=null){
            				String[] parts = combined.split("-");
            				if(parts.length>3){
            					parts[2] = latestMobile;
            					StringBuilder sb = new StringBuilder();
            					sb.append(parts[0]).append('-').append(parts[1]).append('-').append(parts[2]).append('-').append(parts[3]);
            					this.getBillInfoDAO().setCustomerName(sb.toString());
            					this.getBillInfoDAO().setCustomerMobile(latestMobile);
            				}
            			}
            		}
            	}catch(Exception ignore){}
*/
	        	//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();
		        		
		        	}
	        	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 [] custData = new String [5];
	        	String custId = "NA";
	        	try{
	        		custData = this.getBillInfoDAO().getCustomerName().split("-");
	        		custId = custData[0];
	        	}catch(Exception e){ custId = "NA"; }
	        	
	        	// Auto-create customer if not present based on latest mobile
	        	try{
	        		String latestMobile = this.getBillInfoDAO().getCustomerMobile();
	        		if(latestMobile==null || latestMobile.trim().length()==0){
	        			try{ latestMobile = this.getAlternateMobileNumber(); }catch(Exception ignore){}
	        		}
	        		String customerNameOnly = this.getBillInfoDAO().getCustomerName();
	        		try{ if(customerNameOnly!=null && customerNameOnly.contains("-")) customerNameOnly = customerNameOnly.split("-")[1]; }catch(Exception ignore){}
	        		
	        		if(customerNameOnly==null || customerNameOnly.trim().length()==0){ customerNameOnly = "NA"; }
	        		
	        		if(latestMobile!=null && latestMobile.trim().length()>=8){
	        			
	        			// check if mobile exists
	        			String checkSql = "SELECT customer_id, customer_name, customer_type FROM shop_customer_master WHERE shop_id=? AND shop_code=? AND mobile_number=?";
	        			PreparedStatement cps = connection.prepareStatement(checkSql);
	        			cps.setString(1, shopId);
	        			cps.setString(2, shopCode);
	        			cps.setString(3, latestMobile.trim());
	        			ResultSet crs = cps.executeQuery();
	        			if(crs.next()){
	        				custId = crs.getString(1);
	        				this.getBillInfoDAO().setCustomerName(custId+"-"+customerNameOnly+"-"+latestMobile.trim()+"-"+crs.getString(3));
	        				this.getBillInfoDAO().setCustomerMobile(latestMobile.trim());
	        			}else{
	        				// generate new customer id
	        				String maxSql = "SELECT customer_id FROM shop_customer_master WHERE shop_id=? AND shop_code=? ORDER BY customer_id DESC LIMIT 1";
	        				PreparedStatement mps = connection.prepareStatement(maxSql);
	        				mps.setString(1, shopId);
	        				mps.setString(2, shopCode);
	        				ResultSet mrs = mps.executeQuery();
	        				int newCustomerId = 1;
	        				if(mrs.next() && mrs.getString(1)!=null){ newCustomerId = mrs.getInt(1)+1; }
	        				mrs.close(); mps.close();
	        				// insert minimal customer row
	        				Date dNow = new Date();
	        				SimpleDateFormat dfmt = new SimpleDateFormat("dd-MM-yyyy");
	        				String today = dfmt.format(dNow);
	        				String insSql = "INSERT INTO shop_customer_master (customer_id,shop_id,shop_code,add_date,customer_name,cust_name_marathi,mobile_number,cust_secondary_mobile,gst_number,pan_number,tin_number,customer_type,billing_address,billing_address_marathi,birth_date,credit_limit,customer_image) values (?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?)";
	        				PreparedStatement ips = connection.prepareStatement(insSql);
	        				
	        				ips.setInt(1,newCustomerId);
	        				ips.setString(2, shopId);
	        				ips.setString(3, shopCode);
	        				ips.setString(4, today);
	        				ips.setString(5, customerNameOnly.trim().toUpperCase());
	        				ips.setString(6, "NA");
	        				ips.setString(7, latestMobile.trim());
	        				ips.setString(8, "NA");
	        				ips.setString(9, "NA");
	        				ips.setString(10, "NA");
	        				ips.setString(11, "NA");
	        				ips.setString(12, "REGULER");
	        				ips.setString(13, "NA");
	        				ips.setString(14, "NA");
	        				ips.setString(15, today);
	        				ips.setString(16, "0");
	        				ips.setBinaryStream(17, null);
	        				int added = ips.executeUpdate();
	        				
	        				
		        			
	        				ips.close();
	        				if(added>0){
	        					custId = String.valueOf(newCustomerId);
	        					this.getBillInfoDAO().setCustomerName(custId+"-"+customerNameOnly+"-"+latestMobile.trim()+"-REGULER");
	        					this.getBillInfoDAO().setCustomerMobile(latestMobile.trim());
	        					// persist customer immediately so later bill rollback won't undo customer creation
	        					connection.commit();
	        				}
	        			}
	        			crs.close(); cps.close();
	        		}
	        	}catch(Exception ignore){}
        		
        		String fianacialYear = (String) this.getSessionMap().get("financialyearstartdate");
        		
        		ArrayList <Integer> billNumbers = new ArrayList<Integer>();
            	
        		
        		if(this.getBillInfoDAO().getBillNumber().equalsIgnoreCase("NA"))
				{
        			
        			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);
				
					//System.out.print(preparedStatement.toString());
					
					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(), 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,"
                        + "bill_source) "
                        + "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,custId);
	        	preparedStatement.setString(9,this.getBillInfoDAO().getCustomerName());
	        	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.setString(18, "BARCODEBILL");
	       	
	        	countBillInfoInserted = preparedStatement.executeUpdate();
	        	
	        	}
	        	else
	        	{
	        		
	        		
	        		if(this.getBillInfoDAO().getOldCustomerId() == null || this.getBillInfoDAO().getOldCustomerId().equals(""))
	        		{
	        			this.getBillInfoDAO().setOldCustomerId(custId);
	        		}
	        		
	        		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=? "                                 
		        			+ "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,custId);
		        	preparedStatement.setString(5,this.getBillInfoDAO().getCustomerName());
		        	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.setString(13, this.getBillInfoDAO().getBillType());
	                preparedStatement.setString(14,this.getBillInfoDAO().getBillNumber());
	                preparedStatement.setString(15,this.getBillInfoDAO().getOldCustomerId());
	                preparedStatement.setString(16, this.getBillInfoDAO().getOldBillDate());
	                preparedStatement.setString(17, shopId);
	                preparedStatement.setString(18, shopCode);
		        	
		        	//System.out.println(preparedStatement.toString());
		        	
		        	countBillInfoUpdated = preparedStatement.executeUpdate();
	        		
	        	}
	        	
	        	//System.out.println("countBillInfoInserted : "+countBillInfoInserted);
	        	//System.out.println("countBillInfoUpdated : "+countBillInfoUpdated);
	        	
	        	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,"
        					+ "serial_no_batch_id) "
        					+ "values "
        					+ "(?,?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        			
	        			PreparedStatement insertProductListPSMT = null;
	        			insertProductListPSMT = connection.prepareStatement(insertProductSql);
	        			boolean stockMinus = false;
	        			boolean stockMinusFromPurchase = false;
	        			for(BillProductInfoDAO productInfoDAO : this.getProductInfoList())
	        			{
	        				
	        				
	        			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()!=null? productInfoDAO.getSalesRate():0.0F);
                        insertProductListPSMT.setFloat(12, productInfoDAO.getQuantity()!=null? productInfoDAO.getQuantity():0.0F);
                        insertProductListPSMT.setFloat(13, productInfoDAO.getDiscountPecentage()!=null? productInfoDAO.getDiscountPecentage():0.0F);
                        insertProductListPSMT.setFloat(14, productInfoDAO.getDiscountRupees()!=null? productInfoDAO.getDiscountRupees():0.0F);
                        insertProductListPSMT.setFloat(15, productInfoDAO.getAmount()!=null? productInfoDAO.getAmount():0.0F);
                        insertProductListPSMT.setFloat(16, productInfoDAO.getAmountAfterDiscount()!=null? productInfoDAO.getAmountAfterDiscount():0.0F);
                        insertProductListPSMT.setFloat(17, productInfoDAO.getGrossAmount()!=null? productInfoDAO.getGrossAmount():0.0F);
                        insertProductListPSMT.setFloat(18, productInfoDAO.getIgst()!=null? productInfoDAO.getIgst():0.0F);
                        insertProductListPSMT.setFloat(19, productInfoDAO.getCgst()!=null? productInfoDAO.getCgst():0.0F);
                        insertProductListPSMT.setFloat(20, productInfoDAO.getSgst()!=null? productInfoDAO.getSgst():0.0F);
                        insertProductListPSMT.setFloat(21, productInfoDAO.getMakingLaborCharge()!=null? productInfoDAO.getMakingLaborCharge():0.0F);
	        			insertProductListPSMT.setString(22, productInfoDAO.getProductNameMarathi());
	        			insertProductListPSMT.setFloat(23, productInfoDAO.getQuantity2());
	        			

	        			if( productInfoDAO.getSerialNoBatchId() != null)
	        			{
	        				insertProductListPSMT.setString(24, productInfoDAO.getSerialNoBatchId());
	        			}else
	        			{
	        				insertProductListPSMT.setString(24, "NA");
	        			}
	        			
	        			
	        			
	        			insertProductListPSMT.addBatch();
	        			
	        			if(productInfoDAO.getProductReturn() == null)
	        			{
	        				productInfoDAO.setProductReturn(false);
	        			}
	        			
	        			if(productInfoDAO.getProductReturn())
	        			{
	        				stockMinus  = UpdateProductStockDetails.addStockToCurrentStock(connection, this.getSessionMap(), productInfoDAO.getProductId(),  productInfoDAO.getProductName(),  productInfoDAO.getQuantity());
		        			
	        				if(this.getSessionMap().get("batchbased").equals("1"))
		    				{
	        					stockMinusFromPurchase = UpdateProductStockDetails
    							.addStockPurchaseDetail(connection, this.getSessionMap(), productInfoDAO.getProductId(), productInfoDAO.getProductName(), productInfoDAO.getQuantity(), productInfoDAO.getSerialNoBatchId());
    				    		
		    				}
	        			}
	        			else
	        			{
	        				stockMinus = UpdateProductStockDetails
	        						.minusStockToCurrentStock(connection, this.getSessionMap(), productInfoDAO.getProductId(), productInfoDAO.getProductName(), productInfoDAO.getQuantity(), productInfoDAO.getQuantity2());
	        	        	
	        				if(this.getSessionMap().get("batchbased").equals("1"))
		    				{
	        					stockMinusFromPurchase = UpdateProductStockDetails
	        							.minusStockToPurchaseDetails(connection, this.getSessionMap(), productInfoDAO.getProductId(), productInfoDAO.getProductName(), productInfoDAO.getQuantity(), productInfoDAO.getSerialNoBatchId());
		    				}
	        			}
	        			
	        				
	        			
	        			}
	        			
	        			int[] productInserted  = insertProductListPSMT.executeBatch();
	        		
	        			
	        			if((productInserted.length == this.getProductInfoList().size()) && stockMinus)
	        			{
	        				
	        				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());
                // Insert per-product salesman commission when enabled
                try{
                    @SuppressWarnings("unchecked")
                    HashMap<String,String> settings = (HashMap<String,String>) this.getSessionMap().get("shop_settings");
                    boolean commEnabled = settings!=null && "TRUE".equalsIgnoreCase(settings.getOrDefault("enable_salesman_commission","FALSE"));
                    // Fallback enable if salesman provided (per-line or header), to avoid silent skip when flag missing
                    if(!commEnabled){
                        boolean hasLineSalesman = false;
                        if(this.getProductInfoList()!=null){
                            for(BillProductInfoDAO p : this.getProductInfoList()){
                                if(p.getSalesmanId()!=null && p.getSalesmanId().trim().length()>0){ hasLineSalesman = true; break; }
                            }
                        }
                        boolean hasHeaderSalesman = (this.getSalesmanId()!=null && this.getSalesmanId().trim().length()>0)
                                || (this.getSalesmanIdName()!=null && this.getSalesmanIdName().contains("-"));
                        commEnabled = hasLineSalesman || hasHeaderSalesman;
                    }
                    
                    if(commEnabled){
                        // Clear existing entries for this bill
                        try{
                            String delComm = "DELETE FROM shop_salesman_commission WHERE shop_id=? AND shop_code=? AND bill_number=? AND bill_date=STR_TO_DATE(?,'%d-%m-%Y') AND bill_type=?";
                            PreparedStatement dps = connection.prepareStatement(delComm);
                            dps.setString(1, shopId);
                            dps.setString(2, shopCode);
                            dps.setString(3, this.getBillInfoDAO().getBillNumber());
                            dps.setString(4, this.getBillInfoDAO().getBillDate());
                            dps.setString(5, this.getBillInfoDAO().getBillType());
                            dps.executeUpdate();
                            dps.close();
                        }catch(Exception ig){}

                        String insComm = "INSERT INTO shop_salesman_commission (shop_id,shop_code,bill_number,bill_date,bill_type,employee_id,commission_percentage,bill_basic_amount,commission_amount) VALUES (?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?)";
                        PreparedStatement cps = connection.prepareStatement(insComm);
                        int linesAdded = 0;
                        for(BillProductInfoDAO p : this.getProductInfoList()){
                        	
                           String empId = p.getSalesmanId();
                            if(empId==null || empId.trim().isEmpty()) continue;
                            // Commission % from master
                            Float commPct = null;
                            PreparedStatement fps = connection.prepareStatement("SELECT commission_percentage FROM shop_salesman_master WHERE shop_id=? AND shop_code=? AND salesman_id=? AND active='Y'");
                            fps.setString(1, shopId);
                            fps.setString(2, shopCode);
                            fps.setString(3, empId.trim());
                            ResultSet frs = fps.executeQuery();
                            if(frs.next()){
                                try{ commPct = frs.getFloat(1);}catch(Exception ig){}
                            }
                            frs.close(); fps.close();
                            if(commPct==null || commPct<=0) continue;
                            Float lineBasic = p.getAmountAfterDiscount();
                            if(lineBasic==null || lineBasic==0){
                                lineBasic = p.getAmount();
                            }
                            if(lineBasic==null) lineBasic = 0.0F;
                            if(lineBasic<0) lineBasic = Math.abs(lineBasic);
                            if(lineBasic==0) continue; // skip zero-value lines
                            Float commAmt = (lineBasic*commPct)/100.0f;
                            cps.setString(1, shopId);
                            cps.setString(2, shopCode);
                            cps.setString(3, this.getBillInfoDAO().getBillNumber());
                            cps.setString(4, this.getBillInfoDAO().getBillDate());
                            cps.setString(5, this.getBillInfoDAO().getBillType());
                            try{
                                int empInt = Integer.parseInt(empId.trim());
                                cps.setInt(6, empInt);
                            }catch(Exception ex){
                                // skip if salesman id is not numeric
                                continue;
                            }
                            cps.setFloat(7, commPct);
                            cps.setFloat(8, lineBasic);
                            cps.setFloat(9, commAmt);
                            cps.addBatch();
                            
                            
                           linesAdded++;
                        }
                        cps.executeBatch();
                        cps.close();
                        // If no per-line salesman provided, fallback to bill-level salesman id
                        if(linesAdded==0){
                            try{
                                String empId = null;
                                if(this.getSalesmanId()!=null && this.getSalesmanId().trim().length()>0){
                                    empId = this.getSalesmanId().trim();
                                    try{ this.getBillInfoDAO().setSalesmanId(empId); }catch(Exception ig){}
                                } else if(this.getSalesmanIdName()!=null && this.getSalesmanIdName().contains("-")){
                                    String[] e = this.getSalesmanIdName().split("-");
                                    empId = e[0];
                                    try{ this.getBillInfoDAO().setSalesmanId(empId); }catch(Exception ig){}
                                }
                                if(empId!=null){
                                    Float commPct = null;
                                    PreparedStatement fps = connection.prepareStatement("SELECT commission_percentage FROM shop_salesman_master WHERE shop_id=? AND shop_code=? AND salesman_id=? AND active='Y'");
                                    fps.setString(1, shopId);
                                    fps.setString(2, shopCode);
                                    fps.setString(3, empId);
                                    ResultSet frs = fps.executeQuery();
                                    if(frs.next()){
                                        try{ commPct = frs.getFloat(1);}catch(Exception ig){}
                                    }
                                    frs.close(); fps.close();
                                    if(commPct!=null && commPct>0){
                                        Float billBasic = (floatTotalAmtAfterDiscount+transportChargeFloat);
                                        Float commAmt = (billBasic*commPct)/100.0f;
                                        PreparedStatement cps1 = connection.prepareStatement(insComm);
                                        cps1.setString(1, shopId);
                                        cps1.setString(2, shopCode);
                                        cps1.setString(3, this.getBillInfoDAO().getBillNumber());
                                        cps1.setString(4, this.getBillInfoDAO().getBillDate());
                                        cps1.setString(5, this.getBillInfoDAO().getBillType());
                                        try{ cps1.setInt(6, Integer.parseInt(empId)); }catch(Exception ex){ cps1.setString(6, empId); }
                                        cps1.setFloat(7, commPct);
                                        cps1.setFloat(8, billBasic);
                                        cps1.setFloat(9, commAmt);
                                        cps1.executeUpdate();
                                        cps1.close();
                                    }
                                }
                            }catch(Exception ig){}
                        }
                        connection.commit();
                    }
                }catch(Exception ignore){}
	        			result = "success";
	    	        	this.setBillSave("true");
	    	        	
	    	        	
	    	        	this.setCustomerIdNameAll(this.getBillInfoDAO().getCustomerName());
	    	        	this.setCustomerName(this.getBillInfoDAO().getCustomerName().split("-")[1]);
	    	        	this.setCustomerId(custId);
	    	        	this.setCustomerMobileNumber(this.getBillInfoDAO().getCustomerMobile());
	    	        	this.setCustomerType(this.getBillInfoDAO().getCustomerName().split("-")[3]);
	    	        		
	    	       		
	    	        		String messageServiceProvider = (String) this.getSessionMap().get("serviceprovider");
	    	        		if(messageServiceProvider == null || messageServiceProvider.trim().isEmpty())
	    	        		{
	    	        			messageServiceProvider = "BULKSMSGATEWAY";
	    	        		}
	    	        		
    	        	
	    	        		if(this.getBillInfoDAO().isSendSMS() || this.isSendDirectSMS())
	    	        		{
	    	        			HashMap<String,String> templateList = (HashMap<String,String>)this.getSessionMap().get("template_map_list");
	    	        			boolean allOkSMSSettings = true;
	    	        			boolean sendWhatsAppMessage = WhatsAppSettingsUtil.isWhatsAppSendingEnabled(this.getSessionMap());
    	        			
	    	        			String ownerMessage = "";
    	        			
	    	        			
	    	        			try{
	    	        				Float custCreditAmount =	GetCustomerCreditAmountById.getCustomerCreditAmountById(this.getBillInfoDAO().getCustId(), this.getSessionMap());
	    		    	        	
	    	        				if(this.getBillType().equals("CASH"))
	    	        				{
	    	        					ownerMessage = templateList.get("CASH_BILLING_MESSAGE_MARATHI");
	    	        					

	    	        					//System.out.println(ownerMessage);
	    	        					ownerMessage = ownerMessage.split("#")[1];
	    	        					ownerMessage = ownerMessage.replace("{shopname}",  (String)this.getSessionMap().get("shopnamemarathi"));	    	        					
	    	        					ownerMessage = ownerMessage.replace("{1var1}", this.getBillNumber());
	    	        					ownerMessage =	ownerMessage.replace("{2var2}", ""+(floatTotalAmtAfterDiscount+transportChargeFloat));	    	        		    
	    	        					ownerMessage = ownerMessage.replace("{3var3}", (String)this.getSessionMap().get("shopcustcarenumber"));
	    	        					
	    	        				}
	    	        				else
	    	        				{
	    	        					ownerMessage = templateList.get("CREDIT_BILLING_MESSAGE_MARATHI");
	    	        					

	    	        					//System.out.println(ownerMessage);
	    	        					ownerMessage = ownerMessage.split("#")[1];	
	    	        					ownerMessage = ownerMessage.replace("{shopname}", (String)this.getSessionMap().get("shopnamemarathi"));
	    	        					ownerMessage = ownerMessage.replace("{1var1}", this.getBillNumber());
	    	        					ownerMessage = ownerMessage.replace("{2var2}", ""+(floatTotalAmtAfterDiscount+transportChargeFloat));
	    	        					ownerMessage = ownerMessage.replace("{3var3}", ""+custCreditAmount);	    
	    	        					ownerMessage = ownerMessage.replace("{4var4}", (String)this.getSessionMap().get("shopcustcarenumber"));
	    	        					
	    	        					
	    	        					//{shopname} मधून खरेदी केल्याबद्दल धन्यवाद! बिल नं.-{1var1} आपली एकूण बिलाची रक्कम: {2var2} रु. आपली एकूण येणे बाकी: {3var3} रु. पुन्हा अवश्य भेट द्या. संपर्क: {4var4}
	    	        				}
    	        					
    	        	    			
    		    	        
    	        					
	    	        			}catch (Exception e) {
	    	        				
	    	        				e.printStackTrace();
		        					allOkSMSSettings = false;
	    	        			}
	    	        			String mobileNumber = WhatsAppSettingsUtil.resolveTargetMobile(this.getSessionMap(), this.getBillInfoDAO().getCustomerMobile());
	    	        			
	    	        			
		    	        		
	    	        		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[] 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());
									/*
									 * System.out.println("Barcode Bill WhatsApp mode => selected: " +
									 * this.getBillWhatsAppMessageType() + ", sendWithPdf: " + sendWithPdf);
									 */
									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, ownerMessage,
												tokenNumber, fileUrl, fileName);
									}
									else
									{
										resp = SendWhatsAppMessage.sendMessageOnly(userName, mobileNumber, ownerMessage, 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 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("Sorry! Bill details not saved!");
	        	}
	        		
	        	}
	        	catch (SQLException e) {
	        		boolean duplicateBillSave = isDuplicateBillSaveException(e);
	        		
	        		try {
	        			if(connection != null)
	        			{
	        				connection.rollback();
	        			}
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
	        		
	        		if(duplicateBillSave)
	        		{
	        			result = SUCCESS;
	        			this.setBillSave("true");
	        			this.setBillSaved(true);
	        			if(this.getBillInfoDAO() != null)
	        			{
	        				this.getBillInfoDAO().setBillSaved(true);
	        			}
	        			addActionMessage("Bill already saved. Duplicate save request ignored.");
	        		}
	        		else
	        		{
						this.setBillSave("false");
						result = "error";
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" ||1 Bill details not Saved Successfully !");
	        		}
				} catch (IOException e) {
					//e.printStackTrace();
					
					result = "error";
					this.setBillSave("false");
					addActionError(e.getMessage()+" || "+e.getCause()+" ||2 Bill details not Saved Successfully !");
				}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() {
		
		
	 	this.setCustomerTypeList(GetListResource.getCustomerTypeList());
	       
		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");
    	
    	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.setCustomerName(billInfoDAO.getCustomerName());
    	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!");
	    	
    	}
    	
		
    	
        	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!");
    			}
    		}
    	}
    	
    	
    	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"));
        
    	
		this.getSessionMap().put("billInformation", this.getBillInfoDAO());
		this.getSessionMap().put("productList", this.getProductInfoList());
	}
	
	
 
	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 String getSalesmanIdName() {
		return salesmanIdName;
	}
	public void setSalesmanIdName(String salesmanIdName) {
		this.salesmanIdName = salesmanIdName;
	}
	public Float getCommissionPercentage() {
		return commissionPercentage;
	}
	public void setCommissionPercentage(Float commissionPercentage) {
		this.commissionPercentage = commissionPercentage;
	}
    public String getSalesmanId() {
        return salesmanId;
    }
    public void setSalesmanId(String salesmanId) {
        this.salesmanId = salesmanId;
    }
	public ArrayList<String> getSerailBatchIdList() {
		return serailBatchIdList;
	}
	public void setSerailBatchIdList(ArrayList<String> serailBatchIdList) {
		this.serailBatchIdList = serailBatchIdList;
	}
	public String getSerailNoBatchId() {
		return serailNoBatchId;
	}
	public void setSerailNoBatchId(String serailNoBatchId) {
		this.serailNoBatchId = serailNoBatchId;
	}
	public ArrayList<String> getCustomerTypeList() {
		return customerTypeList;
	}
	public void setCustomerTypeList(ArrayList<String> customerTypeList) {
		this.customerTypeList = customerTypeList;
	}
	public String getCustomerType() {
		return customerType;
	}
	public void setCustomerType(String customerType) {
		this.customerType = customerType;
	}
	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 getCustomerIdNameAll() {
		return customerIdNameAll;
	}
	public void setCustomerIdNameAll(String customerIdNameAll) {
		this.customerIdNameAll = customerIdNameAll;
	}
	
	private boolean isDuplicateBillSaveException(SQLException e) {
		if (e == null) {
			return false;
		}
		String sqlState = e.getSQLState();
		String message = e.getMessage();
		if (message == null) {
			return false;
		}
		String normalized = message.toLowerCase();
		boolean duplicateState = "23000".equals(sqlState) || "23505".equals(sqlState);
		boolean duplicateMessage = normalized.contains("duplicate entry")
				&& normalized.contains("shop_bill_info_master.primary");
		return duplicateState || duplicateMessage;
	}
	
	private boolean isBillHeaderAlreadyPresent(Connection connection, String billType, String billNumber, 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 shop_id = ? AND shop_code = ? LIMIT 1";
			localPS = connection.prepareStatement(sql);
			localPS.setString(1, billType);
			localPS.setString(2, billNumber);
			localPS.setString(3, shopId);
			localPS.setString(4, 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) {}
			}
		}
	}

	
}

