package com.reallinkbilling.add;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.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.reallinkbilling.DAO.BillInformationDAO;
import com.reallinkbilling.DAO.BillProductInfoDAO;
import com.reallinkbilling.DAO.ChallanToInvoiceProductDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.CheckAlreadyAvailable;
import com.reallinkbilling.resource.GetListResource;
import com.reallinkbilling.utils.GetAccountListForDrCr;

public class SaveChallanToInvoiceAndPrint 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 billNumber;
	private String billDateTime;
	private String totalAmount;
	private String totalDiscount;
	private String totalAmouAfterDisount;
	private String totalPaybleAmount;
	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 Map<String,String> rateTypeList = new LinkedHashMap<String,String>();
	private String rateType;
	private Float cashAmount;
	private Float bankRtgsUpiAmount;
	

	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;
	        	}
	        	
	        
	        		String shopId = (String) this.getSessionMap().get("shopId");
		    		String shopCode = (String) this.getSessionMap().get("shopCode");
		    		
		    		
	        	
		        	
		        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"));

	        	//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 [] custData = new String [5];
        		
        		String custId = "NA";
        		String custName = "NA";
        	
        		
        		if(this.getBillInfoDAO().getCustomerName() == null)
        		{
        			this.getBillInfoDAO().setCustomerName(this.getCustomerName());
        		}
        		try
        		{
        			custData = this.getBillInfoDAO().getCustomerName().split("-");
        			custId = custData[0];
        			custName = custData[1];
        		}
        		catch(Exception e)
        		{
        			//e.printStackTrace();
        			custId = "NA";
        			custName = "CASH-NA";
        		}
        		
        		String fianacialYear = (String) this.getSessionMap().get("financialyearstartdate");
        		
        		ArrayList <Integer> billNumbers = new ArrayList<Integer>();
        		
        		if(this.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);
				
					//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;
        		}
        		
	        	
	        	int countBillInfoInserted = 0;
	        	int countBillInfoUpdated = 0;
	        	
	        	float transportChargeFloat = 0.0F;
	        	
	        	if(!this.getBillInfoDAO().isBillInformationInserted())
	        	{
	        		transportChargeFloat = 0.0f;
	        		
	        	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,"
	        			+ "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.getBillDateTime());
	        	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, 0.0f);
	        	preparedStatement.setString(11,"");
	        	preparedStatement.setFloat(12,(floatTotalAmtAfterDiscount+transportChargeFloat));
	        	preparedStatement.setFloat(13,floatTotalAmtAfterDiscount);
	        	preparedStatement.setString(14,"0");
	        	preparedStatement.setString(15,billedBy);
	        	preparedStatement.setFloat(16,floatTotalAmtAfterDiscount);
	        	preparedStatement.setFloat(17,0.0f);
	        	preparedStatement.setFloat(18, this.getBillInfoDAO().getDirectDiscountAmount());
	        	preparedStatement.setString(19, "CHALLAN");
	        	
	        	//System.out.println(preparedStatement.toString());
	        	
	        	countBillInfoInserted = preparedStatement.executeUpdate();
	        	
	        	}
	        	else
	        	{
	        		
	        		
	        		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 = ? "		       			        			
		        			+ "WHERE "
		        			+ "bill_type = ? "
		        			+ "AND "
		        			+ "bill_number = ? "
		        			+ "AND "
		        			+ "customer_id = ? "
		        			+ "AND "
		        			+ "shop_id = ? "
		        			+ "AND "
		        			+ "shop_code = ? ";
	        		
	        		preparedStatement = connection.prepareStatement(sql);
		      	        	
		           	preparedStatement.setTime(1, time);
		        	preparedStatement.setString(2, this.getBillDateTime());
		        	preparedStatement.setString(3,this.getBillInfoDAO().getPaymentType());		        
		        	preparedStatement.setString(4,custId);
		        	preparedStatement.setString(5,this.getBillInfoDAO().getCustomerName());
		        	preparedStatement.setFloat(6,0.0f);
		        	preparedStatement.setString(7,"");
		        	preparedStatement.setFloat(8,(floatTotalAmtAfterDiscount+transportChargeFloat));
		        	preparedStatement.setFloat(9,floatTotalAmtAfterDiscount);
		        	preparedStatement.setString(10,"0");
		        	preparedStatement.setFloat(11,floatTotalAmtAfterDiscount);
		        	preparedStatement.setFloat(12,this.getBankRtgsUpiAmount());
		        	preparedStatement.setFloat(13, this.getBillInfoDAO().getDirectDiscountAmount());
		        	preparedStatement.setString(14, this.getBillInfoDAO().getBillType());
		        	preparedStatement.setString(15,this.getBillInfoDAO().getBillNumber());
		        	preparedStatement.setString(16,custId);
		        	preparedStatement.setString(17, shopId);
		        	preparedStatement.setString(18, shopCode);
		        	
		       	
		        	countBillInfoUpdated = preparedStatement.executeUpdate();
	        		
	        	}
	        	
	        	
	        	
	        	if(countBillInfoInserted>0 || countBillInfoUpdated > 0)
	        	{
	        		
	        		
	        		if(preparedStatement != null)
	        		{
	        			preparedStatement.close();
	        			preparedStatement = null;
	        		}
	        		
	        		int rowsDeleted = 0;
	        		
	        		sql = "SELECT "
	        				+ "product_id "        				
	        				+ "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();
	        		
	        		
	        		if(resultSet.next())
	        		{
	        			
	        	

		        		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);
	        			rowsDeleted = preparedStatement.executeUpdate(); ;
	        			
	        		}
	        		else
	        		{
	        			rowsDeleted = 1;
	        		}
	        	
	        		
	        		
	        			
	        			
	        		
	        	
	        		if(rowsDeleted>0)
					{
	        			
					
	        		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);
	        			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.getBillDateTime());
	        			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();
	        			
	        			
	        			}
	        			
	        			
	        			int[] productInserted  = insertProductListPSMT.executeBatch();
	        		
	        			
	        			if((productInserted.length == this.getProductInfoList().size()))
		        		{
		        				
	        				
		        				this.getSessionMap().remove("deletedProductList");
		        				
		        			
		        				if(countBillInfoInserted > 0)
		        				{
		        					this.getBillInfoDAO().setBillInformationInserted(true);
		        				}
		        				
		        			  	ArrayList<ChallanToInvoiceProductDAO> productList =  (ArrayList<ChallanToInvoiceProductDAO>) this.getSessionMap().get("challanToInvProductList");
		        		        
		        			  	boolean allChallanProQtyUpadted = true;

		        			  	if (productList == null || productList.isEmpty())
		        			  	{
		        			  	    allChallanProQtyUpadted = false;

		        			  	    System.out.println("ERROR: challanToInvProductList is NULL or EMPTY!");
		        			  	}
		        			  	else
		        			  	{
		        			  	    for(ChallanToInvoiceProductDAO dao : productList)
		        			  	    {
		        			  	        String challanNumber = dao.getChallanNumber();
		        			  	        String productName = dao.getProductName();
		        			  	        String productId = dao.getProductId();
		        			  	        String challanDate = dao.getChallanDate();

		        			  	        float convertQuantity = 0.0F;

		        			  	        try
		        			  	        {
		        			  	            if(dao.getConvertQuantity() != null &&
		        			  	               !dao.getConvertQuantity().trim().equals(""))
		        			  	            {
		        			  	                convertQuantity =
		        			  	                    Float.parseFloat(dao.getConvertQuantity().trim());
		        			  	            }
		        			  	            else
		        			  	            {
		        			  	                System.out.println(
		        			  	                    "ERROR: Convert quantity is NULL/EMPTY for product : "
		        			  	                    + productName
		        			  	                );

		        			  	                allChallanProQtyUpadted = false;
		        			  	                break;
		        			  	            }
		        			  	        }
		        			  	        catch(Exception e)
		        			  	        {
		        			  	            System.out.println(
		        			  	                "ERROR: Invalid convert quantity for product : "
		        			  	                + productName
		        			  	            );

		        			  	            e.printStackTrace();

		        			  	            allChallanProQtyUpadted = false;
		        			  	            break;
		        			  	        }

//		        			  	        System.out.println("--------------------------------------");
//		        			  	        System.out.println("Challan Number   : " + challanNumber);
//		        			  	        System.out.println("Challan Date     : " + challanDate);
//		        			  	        System.out.println("Product ID       : " + productId);
//		        			  	        System.out.println("Product Name     : " + productName);
//		        			  	        System.out.println("Convert Quantity : " + convertQuantity);

		        			  	        
		        			  	        
		        			  	        String getChallanProductQtySQL =
		        			  	            "SELECT remaining_quanity_for_invoice " +
		        			  	            "FROM shop_challan_product_info_master " +
		        			  	            "WHERE challan_number = ? " +
		        			  	            "AND challan_date = STR_TO_DATE(?,'%d-%m-%Y') " +
		        			  	            "AND shop_id = ? " +
		        			  	            "AND shop_code = ? " +
		        			  	            "AND product_id = ? ";

		        			  	        PreparedStatement getChallanProQtyPSMT =
		        			  	            connection.prepareStatement(getChallanProductQtySQL);

		        			  	        getChallanProQtyPSMT.setString(1, challanNumber);
		        			  	        getChallanProQtyPSMT.setString(2, challanDate);
		        			  	        getChallanProQtyPSMT.setString(3, shopId);
		        			  	        getChallanProQtyPSMT.setString(4, shopCode);
		        			  	        getChallanProQtyPSMT.setString(5, productId);

		        			  	        ResultSet getChallanProQtyRS =
		        			  	            getChallanProQtyPSMT.executeQuery();

		        			  	        float availableQty = 0.0F;
		        			  	        boolean challanProductFound = false;

		        			  	        if(getChallanProQtyRS.next())
		        			  	        {
		        			  	            challanProductFound = true;
		        			  	            availableQty = getChallanProQtyRS.getFloat(1);
		        			  	        }

		        			  	        getChallanProQtyRS.close();
		        			  	        getChallanProQtyPSMT.close();

		        			  	       // System.out.println("Available Quantity : " + availableQty);

		        			  	        if(!challanProductFound)
		        			  	        {
		        			  	            System.out.println(
		        			  	                "ERROR: Challan product NOT FOUND!"
		        			  	            );

		        			  	            System.out.println(
		        			  	                "Challan Number = " + challanNumber
		        			  	                + ", Date = " + challanDate
		        			  	                + ", Product ID = " + productId
		        			  	            );

		        			  	            allChallanProQtyUpadted = false;
		        			  	            break;
		        			  	        }

		        			  	        if(convertQuantity <= 0)
		        			  	        {
		        			  	            System.out.println(
		        			  	                "ERROR: Convert quantity must be greater than zero!"
		        			  	            );

		        			  	            allChallanProQtyUpadted = false;
		        			  	            break;
		        			  	        }

		        			  	        if(convertQuantity > availableQty)
		        			  	        {
		        			  	            System.out.println(
		        			  	                "ERROR: Convert quantity is greater than available quantity!"
		        			  	            );

		        			  	            System.out.println(
		        			  	                "Available = " + availableQty
		        			  	                + ", Convert = " + convertQuantity
		        			  	            );

		        			  	            allChallanProQtyUpadted = false;
		        			  	            break;
		        			  	        }

		        			  	        float newQty = availableQty - convertQuantity;

		        			  	      //  System.out.println("New Remaining Qty : " + newQty);

		        			  	        String updateChallanProductQtySQL =
		        			  	            "UPDATE shop_challan_product_info_master " +
		        			  	            "SET remaining_quanity_for_invoice = ? " +
		        			  	            "WHERE challan_number = ? " +
		        			  	            "AND challan_date = STR_TO_DATE(?,'%d-%m-%Y') " +
		        			  	            "AND shop_id = ? " +
		        			  	            "AND shop_code = ? " +
		        			  	            "AND product_id = ? ";

		        			  	        PreparedStatement updateChallanProQtyPSMT =
		        			  	            connection.prepareStatement(updateChallanProductQtySQL);

		        			  	        updateChallanProQtyPSMT.setFloat(1, newQty);
		        			  	        updateChallanProQtyPSMT.setString(2, challanNumber);
		        			  	        updateChallanProQtyPSMT.setString(3, challanDate);
		        			  	        updateChallanProQtyPSMT.setString(4, shopId);
		        			  	        updateChallanProQtyPSMT.setString(5, shopCode);
		        			  	        updateChallanProQtyPSMT.setString(6, productId);

		        			  	        int k = updateChallanProQtyPSMT.executeUpdate();

		        			  	        updateChallanProQtyPSMT.close();

		        			  	     //   System.out.println("Challan Quantity Update Rows : " + k);

		        			  	        if(k <= 0)
		        			  	        {
		        			  	            allChallanProQtyUpadted = false;
		        			  	            break;
		        			  	        }

		        			  	        String updateChallanStatus =
		        			  	            "UPDATE shop_challan_info_master " +
		        			  	            "SET challan_status = 'DEAD' " +
		        			  	            "WHERE challan_number = ? " +
		        			  	            "AND challan_date = STR_TO_DATE(?,'%d-%m-%Y') " +
		        			  	            "AND shop_id = ? " +
		        			  	            "AND shop_code = ? ";

		        			  	        PreparedStatement updateChallanStatusPSMT =
		        			  	            connection.prepareStatement(updateChallanStatus);

		        			  	        updateChallanStatusPSMT.setString(1, challanNumber);
		        			  	        updateChallanStatusPSMT.setString(2, challanDate);
		        			  	        updateChallanStatusPSMT.setString(3, shopId);
		        			  	        updateChallanStatusPSMT.setString(4, shopCode);

		        			  	        int m = updateChallanStatusPSMT.executeUpdate();

		        			  	        updateChallanStatusPSMT.close();

		        			  	       // System.out.println("Challan Status Update Rows : " + m);

		        			  	        if(m <= 0)
		        			  	        {
		        			  	            allChallanProQtyUpadted = false;
		        			  	            break;
		        			  	        }

		        			  	        System.out.println(
		        			  	            "SUCCESS: Challan quantity updated successfully."
		        			  	        );
		        			  	    }
		        			  	}
		        				
		        				if(allChallanProQtyUpadted)
		        				{
		        		
		        					
		        					
		        				
		        					
		        				
		        				connection.commit();
			        			
		        				
		        				this.getBillInfoDAO().setBillSaved(true);
		    	        		this.setBillSaved(true);
		    	       		
		    	        		this.getBillInfoDAO().setBillDate(this.getBillDateTime());
		    	        		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));
		    		      
		    	        		this.getBillInfoDAO().setBillInformationInserted(true);
		    	        		
		    	        		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");
		        				}
		        				else
		        				{
		        					connection.rollback();
			        				result = "error";
			        				addActionError("Bill Not Saved Properly ! Please check convert quantity!");
		        				}
		    	        		
		    	        	
		    	      
		    	        		
		        		}
	        			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) {
	        		result = "error";
	        		
	        		try {

	        			if(connection != null)
	        			{
	        				connection.rollback();
	        			}
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				
					e.printStackTrace();
					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);
	        		}
		        	
		        		
		        	
		        	
		        	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() {
		
		
    
		

		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();
    		
    	}
    	
    	if(this.getBillInfoDAO().getBillNumber() == null)
    	{
    		this.getBillInfoDAO().setBillNumber("NA");
    	}
    	
    	this.setBillNumber(billInfoDAO.getBillNumber());
    
	
			if(billInfoDAO.getDirectDiscountAmount() == null)
			{
				billInfoDAO.setDirectDiscountAmount(0.0f);
			}
		
			floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount-billInfoDAO.getDirectDiscountAmount();
       
			this.setTotalAmouAfterDisount(""+this.getBillInfoDAO().getTotalAfterDiscountBillAmount());
        	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();
    	
    	
    	
    	
    	
    	
    	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.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()))); 
		
		if(getCustomerName().equals("Customer_Not_Found"))
		{
			addActionError("Given customer name is not correct !");
		}
		
		
		
    	if(!hasActionErrors())
    	{
    		if(!getCustomerName().equals("Customer_Not_Found"))
    		{
    			setDefaultValue(getPaymentType());
    			String isCustomerAdded = "false";
    			String [] custData = new String [5];
    			try
    			{
	    			custData = getCustomerName().split("-");
	    			
	    			String [] result = new String[2];
	    			String condition  = " or mobile_number = '"+custData[2]+"' ";
	    			
	    			
	    			result = new CheckAlreadyAvailable().checkAvaibility("shop_customer_master", "customer_name", condition, custData[1], this.getSessionMap());
	    			
	    			isCustomerAdded = result[0];
	    			
	    			if(isCustomerAdded.equals("false"))
	    			{
	    				addActionError("Customer information must be added first! Please Check Customer Details First !");
	    			}
    			}
    			catch(Exception e)
    			{
    				addActionError("Customer information must be added first!");
    			}
    					
    		}
    	}
	}
	
	
 
	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 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 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;
	}
	

	
}
