package com.reallinkbilling.jspRedirect;


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.GetLastBillNumber;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class GenerateChallanToTaxInvoiceFinal extends ActionSupport implements SessionAware{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2563083431834111296L;
	private SessionMap<String,Object> sessionMap;  
	private String customerName;
	private List<BillProductInfoDAO> productInfoList ;
	private BillInformationDAO billInfoDAO = null;
	private Float cashAmount;
	private Float bankRtgsUpiAmount;

	private String billDateTime;
	
	private String lastBillNumber;	
	private Float totalAmount;
	private Float totalDiscount;
	private Float totalAmouAfterDisount;
	
	private Float amountPaid;	
	private String billNumber;
	private Float returnAmount;
	
	
	public String execute() {
		 
		String result = "login";
	
		
	        if(this.getSessionMap()==null || this.getSessionMap().get("login")==null)
			{ 
	        	addActionMessage("Please Logout and Login again !");
	        	result = "login";
	        }  
	        else{
	        	
	        	Date d = new Date();
	        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
	      
	        	this.setBillDateTime(dateFormat.format(d));
	        	
	          	ArrayList<ChallanToInvoiceProductDAO> productList =  (ArrayList<ChallanToInvoiceProductDAO>) this.getSessionMap().get("challanToInvProductList");
	        	
	          	this.setProductInfoList(new ArrayList<BillProductInfoDAO>());
	          	
				String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
	        	HashMap<String, String> settings = (HashMap<String, String>) this.getSessionMap().get("shop_settings");
	        	this.setLastBillNumber(GetLastBillNumber.getLastBillNumber("TAX-INVOICE", this.getSessionMap()));
	    
	        	
				Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
			
					
				String sql = "";
				String db = (String)  this.getSessionMap().get("db");
				
				try
				{
					connection = GetDBConnection.getDBConnection(db);
					
					int listSize = 1;
					
					float totalBillAmount = 0.0F;
					
					for(ChallanToInvoiceProductDAO dao : productList)
					{
						
						String challanNumber = dao.getChallanNumber();
						String productName = dao.getProductName();
						String productId = dao.getProductId();
						Float convertQuantity = Float.parseFloat(dao.getConvertQuantity());
						String challanDate = dao.getChallanDate();
						
						
						sql = "SELECT "
								+ "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,"
								+ "serial_no_batch_id "
								+ "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  = connection.prepareStatement(sql);
						
						preparedStatement.setString(1, challanNumber);
						preparedStatement.setString(2, challanDate);
						preparedStatement.setString(3, shopId);
						preparedStatement.setString(4, shopCode);
						preparedStatement.setString(5, productId);
						
						resultSet = preparedStatement.executeQuery();
						
						while(resultSet.next())
						{
							
							
							

							BillProductInfoDAO billProductInfoDAO = new BillProductInfoDAO();
							
							billProductInfoDAO.setId(null);	        	
				        	billProductInfoDAO.setSerialNumber(""+(listSize));
				        	billProductInfoDAO.setProductId(productId);
				        
			        		billProductInfoDAO.setProductName(productName);
			        		billProductInfoDAO.setProductNameMarathi("");			        	
				        		
				        	billProductInfoDAO.setProductCode("");				        
				        	billProductInfoDAO.setSalesUnit(resultSet.getString(2));
				        	billProductInfoDAO.setTaxId(resultSet.getString(3));
				        	billProductInfoDAO.setSalesRate(resultSet.getFloat(4));
				   
			        		billProductInfoDAO.setQuantity2(0.0F);
			        		
			        	
				        	billProductInfoDAO.setQuantity(convertQuantity);
				        	billProductInfoDAO.setDiscountPecentage(0.0f);
			        	
			      
			        	
			        		billProductInfoDAO.setDiscountRupees(0.0F);
			        	
			             	billProductInfoDAO.setProductReturn(false);
			        	
			     
				        	billProductInfoDAO.setAddedToDB(false);
				        	billProductInfoDAO.setShopId(shopId);
				        	billProductInfoDAO.setShopCode(shopCode);
			        	
			        	
			        		billProductInfoDAO.setMakingLaborCharge(0.0F);
			        	
			        	
			        		float salesRateAfterDiscount = resultSet.getFloat(9) / resultSet.getFloat(5);
			        		
			        		float qtyAmount = salesRateAfterDiscount*convertQuantity;
			        		
				        	float sgst = 0.0F;
				        	float cgst = 0.0F;
				        	float igst = 0.0F;
			        	
					
						
							Map<String,String> taxInfo = GetListResource.GetTaxNamePercentage(resultSet.getString(3),this.getSessionMap());
				        	
							String taxName = taxInfo.get("TAX-NAME");
							String taxPercentage = taxInfo.get("TAX-PERCENTAGE");
							
							billProductInfoDAO.setTaxName(taxName);
							billProductInfoDAO.setTaxPercentage(Float.parseFloat(taxPercentage));
							
						
								
								float floatTaxRate = Float.parseFloat(taxPercentage);	
								
								float basicTax = floatTaxRate+100.0F;
					        	
					        	float grossAmount = (qtyAmount / basicTax) * 100.0F;
					        	
					        	float totalTax = qtyAmount - grossAmount;
								
								if(taxName.toUpperCase().contains("IGST"))
								{
									igst = totalTax;
								}
								else
								{
									sgst = totalTax/2.0F;
						        	cgst = totalTax/2.0F;
								}
				        	
				        	     
								 DecimalFormat df = new DecimalFormat("0.00");
							        
						        	
					        	 billProductInfoDAO.setProductTotalDiscount(0.0f);
					        	 billProductInfoDAO.setGrossAmount(Float.valueOf(df.format(grossAmount)));
					        	 billProductInfoDAO.setSgst(Float.valueOf(df.format(sgst)));
					        	 billProductInfoDAO.setCgst(Float.valueOf(df.format(cgst)));
					        	 billProductInfoDAO.setIgst(Float.valueOf(df.format(igst)));
					        	
				           		 billProductInfoDAO.setAmountAfterDiscount(qtyAmount);
				        		 billProductInfoDAO.setAmount(resultSet.getFloat(4)*convertQuantity);
				       
						
				        		 totalBillAmount = totalBillAmount + billProductInfoDAO.getAmount();
				        		 
								 billProductInfoDAO.setBatchId("NA");
								 billProductInfoDAO.setExpiryDate("NA");
								 
								 this.getProductInfoList().add(billProductInfoDAO);
							
						}
						
						
						
						listSize++;
						
						if(resultSet != null)
						{
							resultSet.close();
							resultSet = null;
						}
						
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
						
						
						
					}
					
				this.setBillInfoDAO(new BillInformationDAO());

		        	String custData [] = null;
		        	try
		        	{
		        		custData = this.getCustomerName().split("-");
		        		
		        		if(custData.length > 2)
		        		{
			        		
			        		this.getBillInfoDAO().setCustId(custData[0]);
			        		this.getBillInfoDAO().setCustomerName(this.getCustomerName());
			        		this.getBillInfoDAO().setCustomerMobile(custData[2]);
		        		}
		        		else
		        		{
		        			this.getBillInfoDAO().setCustId("0");
			        		this.getBillInfoDAO().setCustomerName("0-"+custData[0]+"-"+custData[1]+"-REGULER");
			        		this.getBillInfoDAO().setCustomerMobile(custData[1]);
			        		
			        		this.setCustomerName("0-"+custData[0]+"-"+custData[1]+"-REGULER");
		        		}
		        		
		        	}catch(Exception e)
		        	{
		        		this.getBillInfoDAO().setCustId("0");
		        		this.getBillInfoDAO().setCustomerMobile("9999999999");
		        		this.getBillInfoDAO().setCustomerName("1-"+this.getCustomerName().trim().toUpperCase()+"-9999999999-REGULER");  
		        	}
		        	
		        	
		        	
		         	this.getBillInfoDAO().setBillNumber(getBillNumber());	     
		        	this.getBillInfoDAO().setBillDate(this.getBillDateTime());
		        	this.getBillInfoDAO().setPaymentType("CASH");
		        	this.getBillInfoDAO().setBillType("TAX-INVOICE");
		        		
		        	this.getBillInfoDAO().setBillSaved(false);
		        	this.getBillInfoDAO().setSendSMS(false);
		        	this.getBillInfoDAO().setTransportCharge(0.0f);
		        	String custMobNum  = "0";
		        	
		        	if(this.getBillInfoDAO().getCustomerMobile() == null || this.getBillInfoDAO().getCustomerMobile().equals(""))
		        	{
		        	
			        	String [] custData2 = new String[5];
			        	
			        	try
			        	{
			        		custData2 = this.getCustomerName().split("-");
			        		custMobNum = custData2[2];
			        		if(!(custMobNum.length() == 10) || custMobNum.contains("999999"))
			        		{
			        			this.getBillInfoDAO().setSendSMS(false);
			        		}
			        		
			        	}
			        	catch(Exception e)
			        	{
			        	}
			        	this.getBillInfoDAO().setCustomerMobile(custMobNum.trim());
		        	}
		        	//System.out.println("view : "+viewBill);
		        	
		        	this.setTotalAmount(this.getTotalAmouAfterDisount());	        	
		        	this.setTotalDiscount(0.0f);
		        	this.setTotalAmouAfterDisount(this.getTotalAmouAfterDisount());
		        	
		        	this.getBillInfoDAO().setTotalProductDiscount(0.0f);
		        	this.getBillInfoDAO().setTotalAfterDiscountBillAmount(this.getTotalAmouAfterDisount());
		        	
		        	if(this.getBillInfoDAO().getPaymentType().equals("CASH"))
			    	{
			    		this.setCashAmount(this.getTotalAmouAfterDisount());
			    	}
			    
			    	this.setBankRtgsUpiAmount(0.0F);
					
					this.setTotalAmouAfterDisount(totalBillAmount);
					this.setBillNumber("NA");
				
					result = SUCCESS;
					
				
				}
				catch (SQLException e) {
					result = "error";
					
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Something Went Wrong !");
				}
				catch (Exception e) {
						result = "error";
					
					addActionError(e.getMessage() +" || Something Went Wrong !");
				}
				finally {
					if(resultSet != null)
					{
						try {resultSet.close(); resultSet = null;} catch (SQLException e) {}
					}
					if(preparedStatement != null)
					{
						try {preparedStatement.close(); preparedStatement = null;} catch (SQLException e) {}
					}
					if(connection != null)
					{
						
						try {connection.close(); connection = null;}catch (SQLException e) {}
					}
					
				}
				
				
				this.getSessionMap().put("billInformation", this.getBillInfoDAO());
	        	this.getSessionMap().put("productList", this.getProductInfoList());
	        	
	        
	        	
	        
	        	result = SUCCESS;
	        }
	        return result;
	}
	
	@Override
	public void validate() {
		if(getCustomerName().equals("Customer_Not_Found"))
    	{
    		addActionError("Please Provide Correct Customer Name !");
    	}
		
		
		if(!hasActionErrors())
    	{
    		if(!getCustomerName().equals("Customer_Not_Found"))
    		{
    			
    			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("Please Check Customer Details !");
	    			}
    			}
    			catch(Exception e)
    			{
    				addActionError("Somthing went wrong Please try again!");
    			}
    					
    		}
    	}
	}
	
	
	public List<BillProductInfoDAO> getProductInfoList() {
		return productInfoList;
	}

	public void setProductInfoList(List<BillProductInfoDAO> productInfoList) {
		this.productInfoList = productInfoList;
	}

	public BillInformationDAO getBillInfoDAO() {
		return billInfoDAO;
	}

	public void setBillInfoDAO(BillInformationDAO billInfoDAO) {
		this.billInfoDAO = billInfoDAO;
	}

	public Float getCashAmount() {
		return cashAmount;
	}

	public void setCashAmount(Float cashAmount) {
		this.cashAmount = cashAmount;
	}

	public Float getBankRtgsUpiAmount() {
		return bankRtgsUpiAmount;
	}

	public void setBankRtgsUpiAmount(Float bankRtgsUpiAmount) {
		this.bankRtgsUpiAmount = bankRtgsUpiAmount;
	}

	public String getLastBillNumber() {
		return lastBillNumber;
	}

	public void setLastBillNumber(String lastBillNumber) {
		this.lastBillNumber = lastBillNumber;
	}

	public Float getTotalAmount() {
		return totalAmount;
	}

	public void setTotalAmount(Float totalAmount) {
		this.totalAmount = totalAmount;
	}

	public Float getTotalDiscount() {
		return totalDiscount;
	}

	public void setTotalDiscount(Float totalDiscount) {
		this.totalDiscount = totalDiscount;
	}

	public Float getTotalAmouAfterDisount() {
		return totalAmouAfterDisount;
	}

	public void setTotalAmouAfterDisount(Float totalAmouAfterDisount) {
		this.totalAmouAfterDisount = totalAmouAfterDisount;
	}

	public Float getAmountPaid() {
		return amountPaid;
	}

	public void setAmountPaid(Float amountPaid) {
		this.amountPaid = amountPaid;
	}

	public String getBillNumber() {
		return billNumber;
	}

	public void setBillNumber(String billNumber) {
		this.billNumber = billNumber;
	}

	public Float getReturnAmount() {
		return returnAmount;
	}

	public void setReturnAmount(Float returnAmount) {
		this.returnAmount = returnAmount;
	}

	public String getCustomerName() {
		return customerName;
	}


	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


	public String getBillDateTime() {
		return billDateTime;
	}

	public void setBillDateTime(String billDateTime) {
		this.billDateTime = billDateTime;
	}

	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}
	

}



