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.ChallanInformationDAO;
import com.reallinkbilling.DAO.ChallanProductInfoDAO;
import com.reallinkbilling.bulksmsgateway.AddBulkSMSGatewayResponseToDB;
import com.reallinkbilling.bulksmsgateway.SendBulkSMSGatewayMessage;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.GetListResource;
import com.reallinkbilling.update.UpdateProductStockDetails;
import com.reallinkbilling.utils.GetAccountListForDrCr;
import com.reallinkbilling.utils.GetCustomerCreditAmountById;
import com.reallinkbilling.utils.MaintainCloseingBalUtil;
import com.realllinkbilling.message.AddTextLocalResponseToDB;
import com.realllinkbilling.message.SendTextLocalMessage;

public class SaveAndPrintChallan extends ActionSupport implements SessionAware{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -4205886934505595095L;
	private HttpSession session;
	private SessionMap<String,Object> sessionMap;
	private ChallanInformationDAO challanInfoDAO = null;
	private List<ChallanProductInfoDAO> productInfoList = null;
	private List<ChallanProductInfoDAO> 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> printTypeList = new LinkedHashMap<String,String>();
	private String defaultValue;
	private String printType;
	private String customerName;
	private String challanNumber;
	private String challanDateTime;
	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 challanSave;
	private boolean challanSaved;
	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>();
	
	private String vehicleNumber;
	
	@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<ChallanProductInfoDAO>) this.getSessionMap().get("productList"));		        	
		        	this.setChallanInfoDAO((ChallanInformationDAO) this.getSessionMap().get("challanInformation"));
		        	this.setDeletedProductInfoList((List<ChallanProductInfoDAO>) this.getSessionMap().get("deletedProductList"));

		        	
		        	float floatTotalAmount = 0.0F;
		        	float floatTotalDiscount = 0.0F;
		        	float floatTotalAmtAfterDiscount = 0.0F;
		        	
		        	for(ChallanProductInfoDAO infoDAO : this.getProductInfoList())
		        	{
		        		floatTotalAmount  = floatTotalAmount+ infoDAO.getAmount();
		        		floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount +infoDAO.getAmountAfterDiscount();
		        		floatTotalDiscount = floatTotalDiscount + infoDAO.getProductTotalDiscount();
		        		
		        	}
		        	
		        	this.setCustomerName(challanInfoDAO.getCustomerName());
		        	this.setChallanNumber(challanInfoDAO.getChallanNumber());
		     	
		        	this.setTotalAmount(""+floatTotalAmount);	        	
		        	this.setTotalDiscount(""+(floatTotalDiscount+this.getChallanInfoDAO().getDirectDiscountAmount()));
		        	this.setTotalAmouAfterDisount(""+(floatTotalAmtAfterDiscount-this.getChallanInfoDAO().getDirectDiscountAmount()));
		        	
	        		this.getPaymentTypeList().put("CASH","CASH");
	        		this.getPaymentTypeList().put("CREDIT","CREDIT");
		        	
		        	this.setDefaultValue(this.getChallanInfoDAO().getPaymentType());
		        	

		        	try {this.setTaxList((Map<String, String>) this.getSessionMap().get("tax_list"));}catch (Exception e) {}
		        	
		        	unitList = GetListResource.GetUnitList();
		        	
		        	
		        	addActionError("Please Provide Amount Paid and Amount Return !");
	        		
	        		this.getSessionMap().put("challanInformation", challanInfoDAO);
	        		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.getChallanInfoDAO().getChallanDate();
	        		
	        		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<ChallanProductInfoDAO>) this.getSessionMap().get("productList"));
	        	
	        	this.setChallanInfoDAO((ChallanInformationDAO) this.getSessionMap().get("challanInformation"));
	        	this.setDeletedProductInfoList((List<ChallanProductInfoDAO>) this.getSessionMap().get("deletedProductList"));

	        	//System.out.print("Is Bill Saved : "+billInfoDAO.isBillSaved());
	        	
	        	if(!this.getChallanInfoDAO().isChallanSaved())	        	
	        	{
	        		/*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(ChallanProductInfoDAO infoDAO : this.getProductInfoList())
		        	{
		        		floatTotalAmount  = floatTotalAmount+ infoDAO.getAmount();
		        		floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount + infoDAO.getAmountAfterDiscount();
		        		floatTotalDiscount = floatTotalDiscount + infoDAO.getProductTotalDiscount();
		        		
		        	}
		        	
		        	floatTotalDiscount = floatTotalDiscount + this.getChallanInfoDAO().getDirectDiscountAmount();
		        	
		        	floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount - this.getChallanInfoDAO().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";
        		try
        		{
        			custData = this.getChallanInfoDAO().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> challanNumbers = new ArrayList<Integer>();
        		
        		if(this.getChallanInfoDAO().getChallanNumber().equalsIgnoreCase("NA"))
				{
        			String fy = "24/25";
        			
        		
        			
					sql = "SELECT "
							+ "challan_number "
							+ "FROM "
							+ "shop_challan_info_master "
							+ "WHERE "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code= ? "
							+ "AND "
							+ "challan_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
						{
							challanNumbers.add(Integer.parseInt(resultSet.getString(1).split("-")[1]));
						}catch (Exception e) {
							challanNumbers.add(Integer.parseInt(resultSet.getString(1)));
						}
					}
					
					
					 Collections.sort(challanNumbers);
					 
					 if(challanNumbers.size() > 0)
						{
							
							
						 
							 newBillNumber = challanNumbers.get(challanNumbers.size()-1);
							 
							
									 this.getChallanInfoDAO().setChallanNumber(""+(newBillNumber+1));
						}
						
						else
						{
							newBillNumber = 1;
							
			        			
			        				this.getChallanInfoDAO().setChallanNumber(""+(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;
	        	
	        	if(!this.getChallanInfoDAO().isChallanInformationInserted())
	        	{
	        		transportChargeFloat = this.getTransportCharge();
	        		
	        	sql = "INSERT INTO "
	        			+ "shop_challan_info_master"
	        			+ "( "
	        			+ "shop_id,"
	        			+ "shop_code,"
	        			+ "challan_number,"	        			
	        			+ "challan_time,"
	        			+ "challan_date,"
	        			+ "payment_type,"
	        			+ "customer_id,"
	        			+ "customer_name,"
	        			+ "transportation_charges,"
	        			+ "comments,"
	        			+ "challan_total_amount,"
	        			+ "challan_amount_received,"
	        			+ "challan_amount_retrurn,"
	        			+ "challan_by,"
	        			+ "cash_amount,"
	        			+ "bank_rtgs_upi_amount,"
	        			+ "direct_discount_amount,"
	        			+ "challan_status,"
	        			+ "vehicle_number) "
    					+ "VALUES "
    					+ "(?,?,?,?,STR_TO_DATE(?, '%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	        			
	        	
	        	preparedStatement = connection.prepareStatement(sql);
	        	
	        	
	        	preparedStatement.setString(1, shopId);
	        	preparedStatement.setString(2, shopCode);
	        	preparedStatement.setString(3,this.getChallanInfoDAO().getChallanNumber());
	           	preparedStatement.setTime(4, time);
	        	preparedStatement.setString(5,this.getChallanInfoDAO().getChallanDate());
	        	preparedStatement.setString(6,this.getChallanInfoDAO().getPaymentType());
	        	preparedStatement.setString(7,custId);
	        	preparedStatement.setString(8,this.getChallanInfoDAO().getCustomerName());
	        	preparedStatement.setFloat(9, this.getTransportCharge());
	        	preparedStatement.setString(10,this.getComments());
	        	preparedStatement.setFloat(11,(floatTotalAmtAfterDiscount+transportChargeFloat));
	        	preparedStatement.setFloat(12,this.getAmountPaid());
	        	preparedStatement.setString(13,this.getReturnAmount());
	        	preparedStatement.setString(14,billedBy);
	        	preparedStatement.setFloat(15,this.getCashAmount());
	        	preparedStatement.setFloat(16,this.getBankRtgsUpiAmount());
	        	preparedStatement.setFloat(17, this.getChallanInfoDAO().getDirectDiscountAmount());
	        	preparedStatement.setString(18, "CREATED-ALIVE");
	        	preparedStatement.setString(19, this.getVehicleNumber().trim().toUpperCase());
	        	
	        	//System.out.println(preparedStatement.toString());
	        	
	        	countBillInfoInserted = preparedStatement.executeUpdate();
	        	
	        	}
	        	else
	        	{
	        		
	        		
	        		sql = "UPDATE "
	        				+ "shop_challan_info_master "
	        				+ "SET "
	        				+ "challan_time=?,"
		        			+ "challan_date=STR_TO_DATE(?,'%d-%m-%Y'),"
		        			+ "payment_type=?,"		        			
		        			+ "customer_id = ?,"
		        			+ "customer_name=?,"
		        			+ "transportation_charges=?,"
		        			+ "comments=?,"
		        			+ "challan_total_amount=?,"
		        			+ "challan_amount_received=?,"
		        			+ "challan_amount_retrurn=?,"
		        			+ "cash_amount=?,"
		        			+ "bank_rtgs_upi_amount=?,"
		        			+ "direct_discount_amount = ?,"
		        			+ "challan_status = ?,"
		        			+ "vehicle_number = ? "		       			        			
		        			+ "WHERE "
		        			+ "challan_number = ? "
		        			+ "AND "
		        			+ "customer_id = ? "
		        			+ "AND "
		        			+ "shop_id = ? "
		        			+ "AND "
		        			+ "shop_code = ? ";
	        		
	        		preparedStatement = connection.prepareStatement(sql);
		      	        	
		           	preparedStatement.setTime(1, time);
		        	preparedStatement.setString(2, billDateTime);
		        	preparedStatement.setString(3,this.getChallanInfoDAO().getPaymentType());		        
		        	preparedStatement.setString(4,custId);
		        	preparedStatement.setString(5,this.getChallanInfoDAO().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.setFloat(13, this.getChallanInfoDAO().getDirectDiscountAmount());
		        	preparedStatement.setString(14, "UPDATED-ALIVE");
		        	preparedStatement.setString(15, this.getVehicleNumber().trim().toUpperCase());
		        	preparedStatement.setString(16,this.getChallanInfoDAO().getChallanNumber());		        	
		        	preparedStatement.setString(17,custId);
		        	preparedStatement.setString(18, shopId);
		        	preparedStatement.setString(19, shopCode);
		        	
		       	
		        	countBillInfoUpdated = preparedStatement.executeUpdate();
	        		
	        	}
	        	
	        	
	        	
	        	if(countBillInfoInserted>0 || countBillInfoUpdated > 0)
	        	{
	        		
	        		
	        		if(preparedStatement != null)
	        		{
	        			preparedStatement.close();
	        			preparedStatement = null;
	        		}
	        		
	        		
	        		sql = "SELECT "
	        				+ "product_id,"
	        				+ "product_quantity,"
	        				+ "product_quantity_2 "	        				
	        				+ "FROM "
	        				+ "shop_challan_product_info_master "
	        				+ "where "
	        				+ "challan_number = '"+this.getChallanInfoDAO().getChallanNumber()+"' "
    						+ "AND "
    						+ "shop_id = ? "
    						+ "AND "
    						+ "shop_code = ? ";
	        		
	        		
	        		preparedStatement = connection.prepareStatement(sql);
	        		preparedStatement.setString(1, shopId);
	        		preparedStatement.setString(2, 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_challan_product_info_master "
	        					+ "WHERE "
	        					+ "challan_number = ? "
	        							+ "AND "
	        							+ "shop_id = ? "
	        							+ "AND "
	        							+ "shop_code = ?";
	        			
	        			preparedStatement = connection.prepareStatement(sql);
	        			preparedStatement.setString(1, this.getChallanInfoDAO().getChallanNumber());
	        			preparedStatement.setString(2, shopId);
	        			preparedStatement.setString(3, shopCode);
	        			int rowDeleted = preparedStatement.executeUpdate(); ;
	        			rowsDeleted = rowsDeleted + rowDeleted;	
	        			
	        			
	        		}
	        	
	        		if(rowCountTodelete == rowsDeleted && stockAdded)
					{
	        			
					
	        		sql = "SELECT "
							+ "entry_id "
							+ "FROM "
							+ "shop_challan_product_info_master "
							+ "WHERE "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ? "
							+ "ORDER BY "
							+ "challan_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_challan_product_info_master "
        					+ "("
        					+ "entry_id,"
        					+ "shop_id,"
        					+ "shop_code,"
        					+ "challan_number,"
        					+ "challan_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,"
        					+ "remaining_quanity_for_invoice) "
        					+ "values "
        					+ "(?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        			
	        			PreparedStatement insertProductListPSMT = null;
	        			insertProductListPSMT = connection.prepareStatement(insertProductSql);
	        			boolean stockMinus = false;
	        			for(ChallanProductInfoDAO 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.getChallanInfoDAO().getChallanNumber());
	        			insertProductListPSMT.setString(5, this.getChallanInfoDAO().getChallanDate());
	        			insertProductListPSMT.setString(6, productInfoDAO.getProductId());
	        			insertProductListPSMT.setString(7, productInfoDAO.getProductName());
	        			insertProductListPSMT.setString(8, productInfoDAO.getSalesUnit());
	        			insertProductListPSMT.setString(9, productInfoDAO.getTaxId());
	        			insertProductListPSMT.setFloat(10, productInfoDAO.getSalesRate());
	        			insertProductListPSMT.setFloat(11, productInfoDAO.getQuantity());
	        			insertProductListPSMT.setFloat(12, productInfoDAO.getDiscountPecentage());
	        			insertProductListPSMT.setFloat(13, productInfoDAO.getDiscountRupees());
	        			insertProductListPSMT.setFloat(14, productInfoDAO.getAmount());
	        			insertProductListPSMT.setFloat(15, productInfoDAO.getAmountAfterDiscount());
	        			insertProductListPSMT.setFloat(16, productInfoDAO.getGrossAmount());
	        			insertProductListPSMT.setFloat(17, productInfoDAO.getIgst());
	        			insertProductListPSMT.setFloat(18, productInfoDAO.getCgst());
	        			insertProductListPSMT.setFloat(19, productInfoDAO.getSgst());
	        			insertProductListPSMT.setFloat(20, productInfoDAO.getMakingLaborCharge());
	        			insertProductListPSMT.setString(21, productInfoDAO.getProductNameMarathi());
	        			insertProductListPSMT.setFloat(22, productInfoDAO.getQuantity2());
	        			insertProductListPSMT.setString(23, productInfoDAO.getBatchId());
	        			insertProductListPSMT.setString(24, productInfoDAO.getExpiryDate());
	        			
	        			
	        			System.out.println("Remaining Quantity:"+  productInfoDAO.getQuantity());
	        			
	        			
	        			insertProductListPSMT.setFloat(25, productInfoDAO.getQuantity());
	        			
	        			insertProductListPSMT.addBatch();
	        			if(productInfoDAO.getProductReturn() != null)
	        			{
		        			if(productInfoDAO.getProductReturn())
		        			{
		        				stockMinus  = UpdateProductStockDetails.addStockToCurrentStock(connection, this.getSessionMap(), productInfoDAO.getProductId(),  productInfoDAO.getProductName(),  productInfoDAO.getQuantity());
			        			
		        			}
		        			else
		        			{
		        				stockMinus = UpdateProductStockDetails.minusStockToCurrentStock(connection, this.getSessionMap(), productInfoDAO.getProductId(), productInfoDAO.getProductName(), productInfoDAO.getQuantity(), productInfoDAO.getQuantity2());
		        	        	
		        			}
	        			}
	        			
	        			}
	        			
	        			
	        			int[] productInserted  = insertProductListPSMT.executeBatch();
	        		
	        			
	        			if((productInserted.length == this.getProductInfoList().size()) && stockMinus)
		        		{
		        				
	        				int rowInsetred = 0;
	        				boolean isCloseingBalMaintained = false;
	        				
	        				if(this.getAmountPaid() > 0)
		        				{
		        				
			        				if(preparedStatement != null)
									{
										preparedStatement.close();
										preparedStatement = null;
									}
								
								
								sql = "SELECT "
										+ "entry_id "
										+ "FROM "
										+ "bank_account_credit_debit_master "
										+ "ORDER BY "
										+ "entry_id "
										+ "DESC LIMIT 1;";
								
							
							preparedStatement = connection.prepareStatement(sql);
							resultSet = preparedStatement.executeQuery();
							
							int creditEntryId = 1;
						
							if(resultSet.next())
							{
								if(!(resultSet.getString(1) == null))
								{
									creditEntryId = Integer.parseInt(resultSet.getString(1));
									creditEntryId = creditEntryId + 1;
									
								}
								
							}
							else
							{	creditEntryId =1;
								
							}
							
			        		if(resultSet != null)
			        		{
			        			resultSet.close();
			        			resultSet = null;
			        		}
			        		if(preparedStatement!= null)
			        		{
			        			preparedStatement.close();
			        			preparedStatement = null;
			        		}
			        		
			        		String accountNumber = "";
			        		sql = "SELECT "
			        				+ "account_number "
			        				+ "FROM "
			        				+ "bank_account "
			        				+ "WHERE "
			        				+ "account_id  = ?";
			        			
			        		preparedStatement = connection.prepareStatement(sql);
			        		
			        		preparedStatement.setString(1, this.getAccountId());
			        		
			        		resultSet = preparedStatement.executeQuery();
			        		if(resultSet.next())
			        		{
			        			accountNumber = resultSet.getString(1);
			        		}
			        		
			        		if(resultSet != null)
			        		{
			        			resultSet.close();
			        			resultSet = null;
			        		}
			        		if(preparedStatement!= null)
			        		{
			        			preparedStatement.close();
			        			preparedStatement = null;
			        		}
			        		
			        		
								sql = "INSERT "
										+ "INTO "
										+ "bank_account_credit_debit_master "
										+ "("
										+ "entry_id,"
										+ "shop_id,"
										+ "shop_code,"									
										+ "account_id,"
										+ "account_number,"
										+ "entry_date,"
										+ "entry_time,"
										+ "entry_type,"
										+ "amount,"
										+ "payment_type,"
										+ "entry_by,"
										+ "entry_details) "
										+ "VALUES "
										+ "(?,?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?)";
								
								preparedStatement = connection.prepareStatement(sql);
								
								preparedStatement.setInt(1, creditEntryId);
								preparedStatement.setString(2, shopId);
								preparedStatement.setString(3, shopCode);
								preparedStatement.setString(4, this.getAccountId());
								preparedStatement.setString(5, accountNumber);
								preparedStatement.setString(6, this.getChallanDateTime());
								preparedStatement.setTime(7, time);
								preparedStatement.setString(8, "CREDIT");
								preparedStatement.setFloat(9, this.getAmountPaid());
								preparedStatement.setString(10, this.getModeOfPayment());
								preparedStatement.setString(11, billedBy);
								preparedStatement.setString(12, "PAID BY "+custName+" AGAINST Challan No: "+this.getChallanInfoDAO().getChallanNumber());
								
								 rowInsetred = preparedStatement.executeUpdate();
								
								
								 isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(this.getAccountId(),"CREDIT", this.getChallanDateTime(), this.getAmountPaid(), billedBy, connection, this.getSessionMap());
								
	        				}
	        				else
	        				{
	        					rowInsetred = 1;
	        					isCloseingBalMaintained = true;
	        				}
							
    						if(rowInsetred > 0 && isCloseingBalMaintained)
    						{
		        				
		        				
		        				this.getSessionMap().remove("deletedProductList");
		        				
		        				connection.commit();
		        				
		        				if(countBillInfoInserted > 0)
		        				{
		        					this.getChallanInfoDAO().setChallanInformationInserted(true);
		        				}
		        				
		        				
		        				
		        				this.getChallanInfoDAO().setChallanSaved(true);
		    	        		this.setChallanSaved(true);
		    	        		this.setChallanDateTime(this.getChallanInfoDAO().getChallanDate());
		    	        		this.setCustomerName(this.getChallanInfoDAO().getCustomerName());
		    	        		this.setChallanNumber(this.getChallanInfoDAO().getChallanNumber());
		    	        		this.setAlternateMobileNumber(this.getChallanInfoDAO().getCustomerMobile());
		    	        		this.setSendSMS(this.getChallanInfoDAO().isSendSMS());
		    	        		this.setTotalAmount(""+(floatTotalAmount+transportChargeFloat));	        	
		    	        		this.setTotalDiscount(""+floatTotalDiscount);
		    	        		this.setTotalAmouAfterDisount(""+(floatTotalAmtAfterDiscount+transportChargeFloat));
		    		      
		    	        		
		    	        		paymentTypeList.put("CASH","CASH");
		    		        	paymentTypeList.put("CREDIT","CREDIT");
		    		        	
		    		        	this.setDefaultValue(this.getChallanInfoDAO().getPaymentType());
		    		        	
	
		    		        	try {taxList = GetListResource.GetTaxList(this.getSessionMap());}catch (Exception e) {}
		    		        	
		    		        	unitList = GetListResource.GetUnitList();
		    		        	
		    		        	
		    		        	
		    		        	
		    	        		addActionMessage("Challan details Saved Successfully !");
		    	        		
		    	        		this.getSessionMap().put("challanInformation", this.getChallanInfoDAO());
		    	        		this.getSessionMap().put("productList", this.getProductInfoList());
		    	        		result =  SUCCESS;
		    	        		this.setChallanSave("true");
		    	        		
		    	        		
		    	        		
		    	        		
		    	        		String messageServiceProvider = "BULKSMSGATEWAY";
		    	        		
	    	        			
		    	        		if(this.getChallanInfoDAO().isSendSMS() || this.isSendDirectSMS())
		    	        		{
		    	        			String messageApiKey = (String) this.getSessionMap().get("message_key");
		    						String messageSendrId = (String) this.getSessionMap().get("message_sender_id");
		    	        			
		    	        			String [] templateIdDetails = new String[3];
		    	        			String templateId = "";
		    	        			String brandName = "";
		    	        			
		    	        			HashMap<String,String> templateList = (HashMap<String,String>)this.getSessionMap().get("template_map_list");
		    	        			HashMap<String,String> settsingMap = (HashMap<String,String>)this.getSessionMap().get("shop_settings");
		    	        			String msg= "";
		    	        			boolean allOkSMSSettings = true;
		    	        			String sendOwnerBillMessage = (String) settsingMap.get("send_billing_message_to_owner");
	    	        			
		    	        			String ownerMessage = "";
	    	        			try{
		    	        				if(this.getChallanInfoDAO().getPaymentType().equals("CASH"))
			    	        			{
		    	        					
		    	        					if(sendOwnerBillMessage != null && sendOwnerBillMessage.equals("TRUE"))
											{
		    	        						templateIdDetails = templateList.get("CASH_BILLING_MESSAGE_MARATHI").split("#");
				    	        				templateId = templateIdDetails[0];
				    	        				brandName = templateIdDetails[1];
				    	        				
				    	        				ownerMessage = brandName
				    	        						+"\n"+this.getSessionMap().get("shopnamemarathi")+" à¤®à¤§à¥‚à¤¨ à¤–à¤°à¥‡à¤¦à¥€ à¤•à¥‡à¤²à¥�à¤¯à¤¾à¤¬à¤¦à¥�à¤¦à¤² à¤§à¤¨à¥�à¤¯à¤µà¤¾à¤¦!"
				    	        						+"\nà¤¬à¤¿à¤² à¤¨à¤‚.-"+this.getChallanInfoDAO().getChallanNumber()+","+this.getChallanInfoDAO().getCustomerName().split("-")[1]
				    	        						+"\nà¤†à¤ªà¤²à¥€ à¤�à¤•à¥‚à¤£ à¤¬à¤¿à¤²à¤¾à¤šà¥€ à¤°à¤•à¥�à¤•à¤®: "+(floatTotalAmtAfterDiscount+transportChargeFloat)+" à¤°à¥�."
				    	        						+"\nà¤ªà¥�à¤¨à¥�à¤¹à¤¾ à¤…à¤µà¤¶à¥�à¤¯ à¤­à¥‡à¤Ÿ à¤¦à¥�à¤¯à¤¾. à¤¸à¤‚à¤ªà¤°à¥�à¤•:"+this.getSessionMap().get("shopcustcarenumber");
											}
		    	        					
			    	        				templateIdDetails = templateList.get("CASH_BILLING_MESSAGE_MARATHI").split("#");
			    	        				templateId = templateIdDetails[0];
			    	        				brandName = templateIdDetails[1];
			    	        				
			    	        				msg = brandName
			    	        						+"\n"+this.getSessionMap().get("shopnamemarathi")+" à¤®à¤§à¥‚à¤¨ à¤–à¤°à¥‡à¤¦à¥€ à¤•à¥‡à¤²à¥�à¤¯à¤¾à¤¬à¤¦à¥�à¤¦à¤² à¤§à¤¨à¥�à¤¯à¤µà¤¾à¤¦!"
			    	        						+"\nà¤¬à¤¿à¤² à¤¨à¤‚.-"+this.getChallanInfoDAO().getChallanNumber()
			    	        						+"\nà¤†à¤ªà¤²à¥€ à¤�à¤•à¥‚à¤£ à¤¬à¤¿à¤²à¤¾à¤šà¥€ à¤°à¤•à¥�à¤•à¤®: "+(floatTotalAmtAfterDiscount+transportChargeFloat)+" à¤°à¥�."
			    	        						+"\nà¤ªà¥�à¤¨à¥�à¤¹à¤¾ à¤…à¤µà¤¶à¥�à¤¯ à¤­à¥‡à¤Ÿ à¤¦à¥�à¤¯à¤¾. à¤¸à¤‚à¤ªà¤°à¥�à¤•:"+this.getSessionMap().get("shopcustcarenumber");
											
			    	        				
			    	        			}
		    	        				else if(this.getChallanInfoDAO().getPaymentType().equals("CREDIT"))
		    	        				{
		    	        					if(sendOwnerBillMessage != null && sendOwnerBillMessage.equals("TRUE"))
											{
		    	        						templateIdDetails = templateList.get("CREDIT_BILLING_MESSAGE_MARATHI").split("#");
				    	        				templateId = templateIdDetails[0];
				    	        				brandName = templateIdDetails[1];
				    	        				
				    	        				float creditAmt = GetCustomerCreditAmountById.getCustomerCreditAmountById(custId, this.getSessionMap());
				    	        				
				    	        				ownerMessage = brandName
				    	        						+"\n"+this.getSessionMap().get("shopnamemarathi")+" à¤®à¤§à¥‚à¤¨ à¤–à¤°à¥‡à¤¦à¥€ à¤•à¥‡à¤²à¥�à¤¯à¤¾à¤¬à¤¦à¥�à¤¦à¤² à¤§à¤¨à¥�à¤¯à¤µà¤¾à¤¦!"
				    	        						+"\nà¤¬à¤¿à¤² à¤¨à¤‚.-"+this.getChallanInfoDAO().getChallanNumber()+","+this.getChallanInfoDAO().getCustomerName().split("-")[1]
				    	        						+"\nà¤†à¤ªà¤²à¥€ à¤�à¤•à¥‚à¤£ à¤¬à¤¿à¤²à¤¾à¤šà¥€ à¤°à¤•à¥�à¤•à¤®: "+(floatTotalAmtAfterDiscount+transportChargeFloat)+" à¤°à¥�."
														+"\nà¤�à¤•à¥‚à¤£ à¤¯à¥‡à¤£à¥‡ à¤¬à¤¾à¤•à¥€: "+creditAmt+" à¤°à¥�."
														+"\nà¤ªà¥�à¤¨à¥�à¤¹à¤¾ à¤…à¤µà¤¶à¥�à¤¯ à¤­à¥‡à¤Ÿ à¤¦à¥�à¤¯à¤¾. à¤¸à¤‚à¤ªà¤°à¥�à¤•:"+this.getSessionMap().get("shopcustcarenumber");	
											}
		    	        					
		    	        					templateIdDetails = templateList.get("CREDIT_BILLING_MESSAGE_MARATHI").split("#");
			    	        				templateId = templateIdDetails[0];
			    	        				brandName = templateIdDetails[1];
			    	        				
			    	        				float creditAmt = GetCustomerCreditAmountById.getCustomerCreditAmountById(custId, this.getSessionMap());
			    	        				
			    	        				msg = brandName
			    	        						+"\n"+this.getSessionMap().get("shopnamemarathi")+" à¤®à¤§à¥‚à¤¨ à¤–à¤°à¥‡à¤¦à¥€ à¤•à¥‡à¤²à¥�à¤¯à¤¾à¤¬à¤¦à¥�à¤¦à¤² à¤§à¤¨à¥�à¤¯à¤µà¤¾à¤¦!"
			    	        						+"\nà¤¬à¤¿à¤² à¤¨à¤‚.-"+this.getChallanInfoDAO().getChallanNumber()
			    	        						+"\nà¤†à¤ªà¤²à¥€ à¤�à¤•à¥‚à¤£ à¤¬à¤¿à¤²à¤¾à¤šà¥€ à¤°à¤•à¥�à¤•à¤®: "+(floatTotalAmtAfterDiscount+transportChargeFloat)+" à¤°à¥�."
													+"\nà¤�à¤•à¥‚à¤£ à¤¯à¥‡à¤£à¥‡ à¤¬à¤¾à¤•à¥€: "+creditAmt+" à¤°à¥�."
													+"\nà¤ªà¥�à¤¨à¥�à¤¹à¤¾ à¤…à¤µà¤¶à¥�à¤¯ à¤­à¥‡à¤Ÿ à¤¦à¥�à¤¯à¤¾. à¤¸à¤‚à¤ªà¤°à¥�à¤•:"+this.getSessionMap().get("shopcustcarenumber");	
		    	        					
		    	        				}
		    	        			}catch (Exception e) {
			        					allOkSMSSettings = false;
		    	        			}
		    	        			String mobileNumber = this.getChallanInfoDAO().getCustomerMobile();
		    	        			
		    	        			
			    	        		
		    	        			
		    	        			if(messageServiceProvider.equals("TEXTLOCAL"))
		    						{
									
		    							
		    	    	        			String resp = new SendTextLocalMessage().sendSms(mobileNumber, msg);
		    	    	        			
		    		    	        			if(resp.contains("Invalid"))
		    		    	        			{
		    										
		    										addActionMessage("Message Not Sent. Invalid Number !!!");
		    										
		    									}
		    									else
		    									{
		    											AddTextLocalResponseToDB responseToDB = new AddTextLocalResponseToDB();
		    											Map<String,String> responseDetails = responseToDB.addTextLocalResponseToDB(resp, mobileNumber, messageServiceProvider,"BIILING");
		    											if(responseDetails != null)
		    			    	        				{
		    			    	        					String dbAdded = responseDetails.get("DBADDED");
		    			    	        					
		    			    	        					if(dbAdded.equals("TRUE"))
		    			    	        					{
		    			    	        						addActionMessage("Message details added!" + responseDetails.get("MESSAGE"));
		    			    	        					}
		    			    	        					else
		    			    	        					{
		    			    	        						addActionError("Message details not added! "+responseDetails.get("MESSAGE"));
		    			    	        					}
		    			    	        				}
		    									}
		    							
		    					}
								else if(messageServiceProvider.equals("BULKSMSGATEWAY") && allOkSMSSettings)
								{
									
										try
										{
										String [] keyDetails =  messageApiKey.split("#");
										String userName = keyDetails[0];
										String password = keyDetails[1];
										
										
									
										if(sendOwnerBillMessage != null && sendOwnerBillMessage.equals("TRUE"))
										{
											//System.out.println(ownerMessage);
											String ownerMobileNumber = (String) this.getSessionMap().get("shopcustcarenumber");
											String response = SendBulkSMSGatewayMessage.sendLanguageSms(userName, password, ownerMobileNumber, ownerMessage, messageSendrId, templateId);
											
											//System.out.println(response);
											if(response.contains("failed"))
				    	        			{
				    	        				addActionError("Counldn't send message" + response);
				    	        			}
				    	        			else
				    	        			{
				    	        				AddBulkSMSGatewayResponseToDB gatewayResponseToDB = new AddBulkSMSGatewayResponseToDB();
				    	        				Map<String,String> responseDetails = gatewayResponseToDB.addBulkSMSGatewayResponseToDB(this.getSessionMap(),response, mobileNumber, messageServiceProvider, messageSendrId, ownerMessage, "OWNER-BILLING");
				    	        				
				    	        				if(responseDetails != null)
				    	        				{
				    	        					String dbAdded = responseDetails.get("DBADDED");
				    	        					
				    	        					if(dbAdded.equals("TRUE"))
				    	        					{
				    	        						addActionMessage("Message details added!" + responseDetails.get("MESSAGE"));
				    	        					}
				    	        					else
				    	        					{
				    	        						addActionError("Message details not added! "+responseDetails.get("MESSAGE"));
				    	        					}
				    	        				}
				    	        				
				    	        			}
										}
			    	        			String resp  = SendBulkSMSGatewayMessage.sendLanguageSms(userName, password, mobileNumber, msg, messageSendrId, templateId);
			    	        			
			    	        			
			    	        			if(resp.contains("failed"))
			    	        			{
			    	        				addActionError("Counldn't send message" + resp);
			    	        			}
			    	        			else
			    	        			{
			    	        				AddBulkSMSGatewayResponseToDB gatewayResponseToDB = new AddBulkSMSGatewayResponseToDB();
			    	        				Map<String,String> responseDetails = gatewayResponseToDB.addBulkSMSGatewayResponseToDB(this.getSessionMap(),resp, mobileNumber, messageServiceProvider, messageSendrId, msg, "BILLING");
			    	        				
			    	        				if(responseDetails != null)
			    	        				{
			    	        					String dbAdded = responseDetails.get("DBADDED");
			    	        					
			    	        					if(dbAdded.equals("TRUE"))
			    	        					{
			    	        						addActionMessage("Message details added!" + responseDetails.get("MESSAGE"));
			    	        					}
			    	        					else
			    	        					{
			    	        						addActionError("Message details not added! "+responseDetails.get("MESSAGE"));
			    	        					}
			    	        				}
			    	        				
			    	        			}
		    									
										}catch (Exception e) {
											//e.printStackTrace();
											addActionError("Couldn't send message to customer !"+e.getMessage()+"|"+e.getCause());
										}
								}
								else
								{
									addActionError("Couldn't send message to customer !");
								}
		    	        	} // Hello
						}else
						{
							connection.rollback();
	        				result = "error";
	        				addActionError("Challan Not Saved ! Error while cr entry and closing bal. entry! Please try again!");
						}
		    	        		
		        		}
	        			else
	        			{
	        				connection.rollback();
	        				result = "error";
	        				addActionError("Challan 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! Challan 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.setChallanSave("false");
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" ||1 Challan details not Saved Successfully !");
				} catch (IOException e) {
					e.printStackTrace();
					
					result = "error";
					this.setChallanSave("false");
					addActionError(e.getMessage()+" || "+e.getCause()+" ||2 Challan 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(ChallanProductInfoDAO infoDAO : productInfoList)
		        	{
		        		floatTotalAmount  = floatTotalAmount+ infoDAO.getAmount();
		        		floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount + infoDAO.getAmountAfterDiscount();
		        		floatTotalDiscount = floatTotalDiscount + infoDAO.getProductTotalDiscount();
		        		
		        	}
		        	
		        	
		        	
	        		this.getSessionMap().put("productList", this.getProductInfoList());
	        		
	        		this.setCustomerName(this.getChallanInfoDAO().getCustomerName());
	        		this.setChallanNumber(this.getChallanInfoDAO().getChallanNumber());
	        		//System.out.println(getAlternateMobileNumber());
	        		
	        		this.setAlternateMobileNumber(this.getChallanInfoDAO().getCustomerMobile());
	        		this.setSendSMS(this.getChallanInfoDAO().isSendSMS());
	        		float transportCharge = 0.0F;
	        		
	        		if(this.getChallanInfoDAO().getTransportCharge()==null || this.getChallanInfoDAO().getTransportCharge().equals(""))
	        		{
	        			this.getChallanInfoDAO().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.getChallanInfoDAO().getPaymentType());
		        	

		        	taxList = GetListResource.GetTaxList(this.getSessionMap());
		        	
		        	unitList = GetListResource.GetUnitList();
		        	this.getSessionMap().put("challanInformation", this.getChallanInfoDAO());
		        	this.getSessionMap().put("productList", this.getProductInfoList());
	        		result = "success";
	        		addActionError("Challan Already Saved !");
	        		
	        		this.setChallanSaved(true);
	        	}
	        	}	
	        }
	       // System.out.print(result);
	        return result;
		
	}
	@SuppressWarnings("unchecked")
	@Override
	public void validate() {
		
		
    	
		if(this.getAmountPaid() == null || this.getAmountPaid().equals(""))
		{
			addActionError("Amount Paid Null ! Challan Cannot be Saved !");
		}
		
		if(!hasActionErrors())
		{
			if(this.getReturnAmount() == null || getReturnAmount().equals(""))
			{
				addActionError("Return amount Null ! Challan Cannot be Saved !");
			}
		}
		

		productInfoList = (List<ChallanProductInfoDAO>) this.getSessionMap().get("productList");		        	
    	challanInfoDAO = (ChallanInformationDAO) this.getSessionMap().get("challanInformation");
    	
    	float floatTotalAmount = 0.0F;
    	float floatTotalDiscount = 0.0F;
    	float floatTotalAmtAfterDiscount = 0.0F;
    	
    	for(ChallanProductInfoDAO infoDAO : productInfoList)
    	{
    		floatTotalAmount  = floatTotalAmount+ infoDAO.getAmount();
    		floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount + infoDAO.getAmountAfterDiscount();
    		floatTotalDiscount = floatTotalDiscount + infoDAO.getProductTotalDiscount();
    		
    	}
    	
    	this.setCustomerName(challanInfoDAO.getCustomerName());
    	this.setChallanNumber(challanInfoDAO.getChallanNumber());
    	this.setChallanDateTime(challanInfoDAO.getChallanDate());
		
		
		if(this.getTransportCharge() == null || this.getTransportCharge() < 0)
		{
    		
			
	    			addActionError("Please provide correct transportaion amount!");
	    	
    	}
    	
			if(challanInfoDAO.getDirectDiscountAmount() == null)
			{
				challanInfoDAO.setDirectDiscountAmount(0.0f);
			}
			
			if(this.getTransportCharge() == null)
			{
				this.setTransportCharge(0.0F);
			}
		
			floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount-challanInfoDAO.getDirectDiscountAmount();
        	this.setTotalAmount(""+(floatTotalAmount+this.getTransportCharge()));	        	
        	this.setTotalDiscount(""+floatTotalDiscount);
        	this.setTotalPaybleAmount(""+(floatTotalAmount+transportCharge));
        	this.setTotalAmouAfterDisount(""+(floatTotalAmtAfterDiscount+transportCharge));
        	addActionMessage("Product added successfully to list !");
    	
    	
        	this.paymentTypeList.put("CASH","CASH");
        	this.paymentTypeList.put("CREDIT","CREDIT");
    	
        	this.setDefaultValue(challanInfoDAO.getPaymentType());
    	

        	taxList = GetListResource.GetTaxList(this.getSessionMap());
    	
    	unitList = GetListResource.GetUnitList();
    	
    	if(!hasActionErrors())
    	{
    		if(this.getChallanInfoDAO().getPaymentType().equals("CASH"))
    		{
    			if(this.getAmountPaid() <  floatTotalAmtAfterDiscount)
    			{
    				addActionError("CHallan type is cash! Paid amount cannot be less than amount payble!");
    			}
    				
    		}
    		else if(this.getChallanInfoDAO().getPaymentType().equals("CREDIT"))
    		{
    			if(this.getAmountPaid() > 0)
    			{
    				addActionError("Challan type is credit! Paid amount cannot be more than 0!");
    			}
    		}
    	}
    	
    	if(!hasActionErrors())
    	{
    		if(this.getAccountId() == null || this.getAccountId().equals(""))
    		{
    			addActionError("Please select account for Credit entry! ");
    		}
    		
    	}
    	
    	
    	this.getRateTypeList().put("INCLUDEGST", "WITH GST");
    	this.getRateTypeList().put("EXCLUDEGST", "WITH-OUT GST");
    	
    	this.setRateType( ((HashMap<String, String>) this.getSessionMap().get("shop_settings")).get("default_rate_type"));
        
    	this.setDirectDiscountAmount(challanInfoDAO.getDirectDiscountAmount());
		this.getSessionMap().put("challanInformation", this.getChallanInfoDAO());
		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(this.getVehicleNumber() == null || this.getVehicleNumber().equals(""))
		{
			this.setVehicleNumber("NA");
		}
		
	}
	
	
 
	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 ChallanInformationDAO getChallanInfoDAO() {
		return challanInfoDAO;
	}
	public void setChallanInfoDAO(ChallanInformationDAO challanInfoDAO) {
		this.challanInfoDAO = challanInfoDAO;
	}
	public List<ChallanProductInfoDAO> getProductInfoList() {
		return productInfoList;
	}
	public void setProductInfoList(List<ChallanProductInfoDAO> productInfoList) {
		this.productInfoList = productInfoList;
	}
	public List<ChallanProductInfoDAO> getDeletedProductInfoList() {
		return deletedProductInfoList;
	}
	public void setDeletedProductInfoList(List<ChallanProductInfoDAO> deletedProductInfoList) {
		this.deletedProductInfoList = deletedProductInfoList;
	}
	public String getChallanNumber() {
		return challanNumber;
	}
	public void setChallanNumber(String challanNumber) {
		this.challanNumber = challanNumber;
	}
	public String getChallanDateTime() {
		return challanDateTime;
	}
	public void setChallanDateTime(String challanDateTime) {
		this.challanDateTime = challanDateTime;
	}
	public String getChallanSave() {
		return challanSave;
	}
	public void setChallanSave(String challanSave) {
		this.challanSave = challanSave;
	}
	public boolean isChallanSaved() {
		return challanSaved;
	}
	public void setChallanSaved(boolean challanSaved) {
		this.challanSaved = challanSaved;
	}
	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> 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 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 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 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 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;
	}
	public String getVehicleNumber() {
		return vehicleNumber;
	}
	public void setVehicleNumber(String vehicleNumber) {
		this.vehicleNumber = vehicleNumber;
	}
	

	
}

