package main_package;

import group_head_package.DataBaseIncomeExpense;
import other_package.DataBaseMethodsOther;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FlowEvent;

@ManagedBean(name = "secureLoan")
@ViewScoped

public class SecureLoanBean implements Serializable
{   
	
	Date requestDate,chequeDate;
	private boolean showDownPayment;
	public static List<String> list;
	ArrayList<SelectItem> planList,centerList, secureTypeList, dsaList, dealerList,productList;
	ArrayList<UserInfo> docList;
	ArrayList<LoanInfo> otherList=new ArrayList<>();
	boolean show,showField,renderDoc=false, skip, reqMudraFin, renAutoLoanNo, renManualLoanNo;
	String shareHolderNo,guarantor1,guarantor2,loanNo,plan_no,fileCharge="0", insuranceFee="0",reason,selectedScheme,rd_fdNo,emiType="flat",center;	
	double loanAmount,interst,duration, emiPayment,extraAmt, commission=0;
	int frequency,discount;
	String[] idProof;
	UserInfo selectedUser,guarantorUser1,guarantoruser2;
	String appChqNo, appAccNo, appBankName, appBankBranch, g1ChqNo, g1AccNo, g1BankName, g1BankBranch, g2ChqNo, g2AccNo, g2BankName, g2BankBranch, emiMode="both";
	String dsaCode;
	DsaListInfo dsa_info;
	DataBaseMethods obj=new DataBaseMethods();
	ArrayList<SelectItem> bankList, bankNameList;
	String companyName, paymentMode="Cash",chequeNo,bankBranch,bankName,submittedBankName, label, description, securityType,product,dealer,imeiNoI,imeiNoII;
	boolean guarantorTabView=true,showCheque,showFields,showMode,showMobile,showVehicle,showProductI,showProductII;
	int branchId;

	DataBaseMethodsRaviK dbrk =new DataBaseMethodsRaviK();
	
	
	
	

	String loanName;



	ArrayList<incomeListInfo>inlist=new ArrayList<>();
	DbYashwant dby = new DbYashwant();
	

	double billAmount,downPayment,dptCharge,cardFee;
	
	int x1;
	boolean showBillAmount,showDealer;
	DataBaseMethodTaheer dbmt= new DataBaseMethodTaheer();
	String companyNames;
	
	
	ArrayList<SelectItem> productListByCategoryType;
	ArrayList<SelectItem> categoryList;
	String category;
	ArrayList<LoanInfo> allLoanList;	

	
	public SecureLoanBean() 
	{
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		branchId = (int) ss.getAttribute("branchId");
		companyName = (String) ss.getAttribute("companyName");
		companyNames = dbmt.companyNameByBranchId(branchId);
		System.out.println("company names is:"+companyNames);
		Connection conn = DataBaseConnection.JAVAConnection();
		dsaList = obj.allDsaList(branchId,"Loan",conn);
		bankNameList = obj.bankNameSelectItemList(conn);
		bankList = new DataBaseIncomeExpense().allBankList(conn);
		centerList = obj.allcenter(branchId,"all",conn);
		secureTypeList = obj.secureLoanTypeList(branchId,conn);

		if("DELIGHTS MICRO CREDIT INDIA FOUNDATION".equals(companyNames)) 
		{	
			guarantorTabView = false;
		}
				
//		inlist= dby.selectLoan(conn);
//		dby.insertFileCharge1(inlist);

		dealerList = dby.dealerList(conn);
		productList = dby.productList(conn);
		
		if(otherList.size() == 0)
		{
			 x1 = 1;
			
			if(otherList.size()<1)
			{
				for(int i = 1; i <= 1; i++)
				{
					LoanInfo info=new LoanInfo();
					info.setSno(i);
					otherList.add(info);
				}
			}
		}

		
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
	public void addMore()
	{
		x1=otherList.size()+1;
		System.out.println(x1+"hlo");
		for(int i=1;i<=1;i++)
		{
			LoanInfo info=new LoanInfo();
			info.setSno(x1);
			otherList.add(info);
		}
	}
	
	public String onFlowProcess(FlowEvent event) 
	{
        if(skip) {
            skip = false;   //reset in case user goes back
            return "confirm";
        }
        else {
            return event.getNewStep();
        }
    }
	
	
	public void checkPaymentMode()
	{
		if(paymentMode.equalsIgnoreCase("Cash"))
		{
			showCheque=false;
			bankBranch=bankName=chequeNo="";
			chequeDate=null;
			
		}
		else
		{
			label=paymentMode;
			showCheque=true;
			bankBranch=bankName=chequeNo="";
			chequeDate=null;
		}
	}
	
	
	public void search()
	{
		if(idProof.length>0)
		{
			renderDoc=true;
			docList= new ArrayList<>();
			int count=1;
			for(int i=0;i<idProof.length;i++)
			{
				UserInfo us= new UserInfo();
				us.setSno(count++);
				us.setDocName(idProof[i]);
				us.setDocPath("");
				docList.add(us);
			}
		}
		else
		{
			renderDoc=false;
		}
		
		
	}
	
	
	public void categoryChange()
	{
	    System.out.println("Selected Category = " + category);
	    System.out.println("SECURITY TYPE = " + securityType);
	    showProductII = false;
	    Connection conn = DataBaseConnection.JAVAConnection();

	    try
	    {
	        if (category != null && !category.trim().isEmpty())
	        {	
	            productListByCategoryType = dbrk.productListByCategory(conn, category);
	            showProductII = true;
	            
	            if (securityType.equalsIgnoreCase("14")) {
	            	showMobile=true;
				}
	        }
	        else
	        {
	            productListByCategoryType = new ArrayList<>();
	            showProductII = false;
	            showMobile= false;
	        }
	    }
	    catch (Exception e)
	    {
	        e.printStackTrace();
	    }
	    finally
	    {
	        try
	        {
	            conn.close();
	        }
	        catch (Exception e)
	        {
	            e.printStackTrace();
	        }
	    }
	}
	
	
	public void loanTypeMode() {
		Connection conn = DataBaseConnection.JAVAConnection();

	    // Default values
	    showMobile = false;
	    showProductI = false;
	    showProductII = false;
	    showVehicle = false;
	    showDownPayment = false;
	    showBillAmount=false;
	    showDealer=false;

	    // Vehicle Loan
	    if (securityType.equalsIgnoreCase("13")) 
	    {
	        showVehicle = true;
	        showDealer = true;
	    }

	    // Mobile Loan
	    if (securityType.equalsIgnoreCase("14")) 
	    {   
	        categoryList=dbrk.categoryListBySecurityType(conn, securityType);
	      //productListBySecurityType = dbrk.productListBySecurityType(conn, securityType);  //by ravi kumar
	        showMobile=false;
	        showProductI = true;
	        showProductII = false;
	        showDownPayment = true;
	        loanName = "Mobile";
	        showBillAmount=true;
	        showDealer=true;
	        
	      
//	        if ("SUDERSHANA FINANCE".equalsIgnoreCase(companyName))
//	        {
//	            showProductII = false;   // Hide Product II for Sudershana
//	        } else {
//	            showProductII = true;
//	        }
	    }
	    
	    //for mobile finance
	    

	    // Consumer Loan
	    else if (securityType.equalsIgnoreCase("15")) 
	    {	//productListBySecurityType = dbrk.productListBySecurityType(conn, securityType);  //by ravi kumar
	    	categoryList=dbrk.categoryListBySecurityType(conn, securityType);
	        loanName = "";
	        showProductI = true;
	        showProductII = false;
	        showDownPayment = true; 
	        showMobile=false;
	        showDealer=true;
	        
            showBillAmount=true;
	        
	        if ("SUDERSHANA FINANCE".equalsIgnoreCase(companyName) ||  
	        	"SILVER ROCK MICRO CARE ASSOCIATION".equalsIgnoreCase(companyName)) 
	        {         
	            showProductII = false;  
	            showMobile=false;
	        } 	        
	        else 
	        {
	            
	            showProductII = false;            
	        }
	        
	    }
	}

		
	public void calculateLoanAmount()
	{
		loanAmount=billAmount-downPayment;
		checkPlan();
	}
	
	public void shareHolderDetails()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();

		if(shareHolderNo.contains("/"))
		{
			shareHolderNo=shareHolderNo.substring(0,shareHolderNo.indexOf("/"));
		}
		
		// Age eligibility check by ravi kumar
		if (!dbrk.isShareHolderEligibleForLoan(shareHolderNo, branchId)) {
		    show = false;

		    FacesContext.getCurrentInstance().addMessage(null,
		     new FacesMessage(FacesMessage.SEVERITY_ERROR, "The customer must be under 60 years of age.", "The applicant is not eligible for the loan because of the age criteria."));

		    return;
		}
		
		selectedUser=obj.userInfoByShareHolderNo(shareHolderNo, conn);
		allLoanList = new DataBaseMethodsOther().allLoanList(shareHolderNo);	
		for (LoanInfo ll : allLoanList) {
			
			 FacesContext.getCurrentInstance().addMessage("form5:messages", new FacesMessage(FacesMessage.SEVERITY_WARN,		            
			            "Loan No: " + ll.getLoanNo()
			            + " | Loan Amount: " + ll.getLoanAmount()
			            + " | Paid Status: " + ll.getPaidStatus(),"Loan Already Exists"));

			}
		if(selectedUser!=null)
		{
			show=true;
	        loanNo=obj.secureLoanNo(branchId); 	
	        requestDate=new Date();
	        planList=obj.allPlans(branchId,"Loan");
		}
		
		else
		{
			show=false;
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Invalid Share Holder No"));
		}
		
		HeaderBean hh=new HeaderBean();
		if(hh.getName().equalsIgnoreCase("MUDRABAZAAR FINCAP FOUNDATION") || hh.getName().equalsIgnoreCase("AADHUNIK GROUP"))
		{
			reqMudraFin=true;
			emiType="reducing";
		}
		else
		{
			reqMudraFin=false;
		}
		
		if(loanNo.equalsIgnoreCase(""))
        {
        	renManualLoanNo=true;
			renAutoLoanNo=false;
        }
        else
        {
        	renManualLoanNo=false;
			renAutoLoanNo=true;
        }
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void checkPlan()
	{
		double fc=0;
		double insFee=0;
		//interst=obj.interestByPlanNo(plan_no);
		CenterInfo cf = obj.selectedPlanInfo(plan_no);
		interst = cf.getInterestRate();
		
		if (loanAmount == 0) 
		{
			loanAmount = cf.getLoanAmount();
		}

		emiPayment = cf.getEmi();
		emiType = cf.getEmiType();
		frequency = cf.getFrequency();
		duration = cf.getTerms();
		System.out.println("duration is:"+duration);
		
		if (loanAmount > 0) {
			fc = ((loanAmount * cf.getFileChargePlan()) / 100);
			insFee = ((loanAmount * cf.getInsuranceFeePlan()) / 100);
			
			fileCharge=String.valueOf(fc);
			insuranceFee=String.valueOf(insFee);
		}
	}
	
	public void checkScheme()
	{
		if(!selectedScheme.equals(""))
		{
			showField=true;
		}
		else
		{
			showField=false;
		}
	}
	
	public void calculateEMI()
	{
		System.out.println(interst);
		
		emiPayment=discount=0;
		if(emiType.equals("reducing"))
		{
			if(emiMode.equalsIgnoreCase("both"))
			{
				emiPayment=obj.calculateLoanEmi(loanAmount,duration, interst, frequency);  	
				if(loanAmount==0)
				{
					emiPayment=0;discount=0;
				}
				
				if(emiPayment>0)
				{
						double totalPayment=emiPayment*duration;
						double falseInterest=totalPayment-loanAmount;
						double trueInterest=obj.totalInterestForDiscount(loanAmount,duration,interst,frequency,emiPayment);
						trueInterest=Math.round(trueInterest);
						discount=(int) (falseInterest-trueInterest);
						discount=Math.round(discount);
				}
			}
			else
			{
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Reducing Interest Calculation Mode Not Applicable For Only Interest EMI. Please Select Flat Interest Mode..."));
			}
		}
		
		else
		{
			emiPayment=obj.calculateLoanEmiForCalculator(loanAmount,duration, interst, frequency, emiMode);  	
			if(loanAmount==0)
			{
				emiPayment=0;discount=0;
			}
			
			if(emiPayment>0)
			{
				double falseInterest=0;
				
				double totalPayment=emiPayment*duration;
				if(emiMode.equals("both"))
				{
					
					falseInterest=totalPayment-loanAmount;
					
					
				}
				else
				{
					falseInterest=totalPayment;
				}
				double trueInterest=(loanAmount*interst*duration)/(100*frequency);
				trueInterest=Math.round(trueInterest);
				discount=(int) (falseInterest-trueInterest);
				discount=Math.round(discount);	
			}
		}
		
		if(securityType.equalsIgnoreCase("14")||securityType.equalsIgnoreCase("15"))
		{
			
			System.out.println(emiPayment);
			if("DELIGHTS MICRO CREDIT INDIA FOUNDATION".equalsIgnoreCase(companyName))
			{
				Double amt= (Double.parseDouble(fileCharge)+ Double.valueOf(insuranceFee) +dptCharge+cardFee+loanAmount)/duration;
				emiPayment=Math.round(amt);
			}
			
			System.out.println("noob"+emiPayment);
			discount=0;
			
		}
	}
	
	public List<String> completeFirstGuarantorText(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		list=new DataBaseAutoCompAndDuplicate().shareHolderForFirstGuarantor(branchId,name,shareHolderNo);
     	return list;
	}
	
	public void firstGuantorDetails()
	{
		Connection conn=DataBaseConnection.JAVAConnection();

		String g1=guarantor1.substring(0,guarantor1.indexOf("/"));
		guarantorUser1=obj.userInfoByShareHolderNo(g1,conn);
		if(guarantorUser1!=null)
		{
			RequestContext.getCurrentInstance().execute("PF('detailDialog').show()");	
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
		 	fc.addMessage(null, new FacesMessage("First Guarantor User Not Valid"));
	        guarantor1=""; 
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void viewDetailsFirst()
	{
		Connection conn=DataBaseConnection.JAVAConnection();

		
		String g1=guarantor1.substring(0,guarantor1.indexOf("/"));
		guarantorUser1=obj.userInfoByShareHolderNo(g1, conn);
		if(guarantorUser1!=null)
		{
			HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			ss.setAttribute("viewselecteduser", guarantorUser1);
			
	        RequestContext.getCurrentInstance().execute("window.open('viewCompleteDetails.xhtml')");
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("First Guarantor User Not Valid"));
			guarantor1="";
		}
		
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public List<String> completeSecondGuarantorText(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		list=new DataBaseAutoCompAndDuplicate().shareHolderForSecondGuarantor(branchId,name,shareHolderNo,guarantor1);
     	return list;
	}
	
	public void secondGuantorDetails()
	{
		Connection conn=DataBaseConnection.JAVAConnection();

		String g2=guarantor2.substring(0,guarantor2.indexOf("/"));
		guarantoruser2=obj.userInfoByShareHolderNo(g2, conn);
		if(guarantoruser2!=null)
		{
			RequestContext.getCurrentInstance().execute("PF('detailDialog').show()");
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Second Guarantor User Not Valid"));
			guarantor2="";
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void viewDetailsSecond()
	{
		Connection conn=DataBaseConnection.JAVAConnection();

		String g2=guarantor2.substring(0,guarantor2.indexOf("/"));
		guarantoruser2=obj.userInfoByShareHolderNo(g2, conn);
		if(guarantoruser2!=null)
		{
			HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			ss.setAttribute("viewselecteduser", guarantoruser2);
			RequestContext.getCurrentInstance().execute("window.open('viewCompleteDetails.xhtml')");
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Second Guarantor User Not Valid"));
			guarantor2="";
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
   public String addRequestLoan() throws ParseException
   {
	   Connection conn=DataBaseConnection.JAVAConnection();
	   FacesContext fc=FacesContext.getCurrentInstance();
	   HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
	   //For Static Trial Period 
 		int flag=1;
	/*	Date dd= new Date();
		String string = "31/12/2019";
		DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
		Date date = format.parse(string);
		if(dd.after(date))
		{	
			flag=0;
		}
		
		// changes pending for Secure Loan
		boolean chk=obj.checkLastEntrySettingInDb("Secure Loan",conn);
		if(chk==true)
		{
			String lastDepositNo=obj.lastShareLoanDepositNo("Secure Loan");
	 		Date lastDate=obj.lastShareLoanDepositNoDate(lastDepositNo, "Secure Loan");
			if(lastDate!=null && !lastDepositNo.equals(""))
			{
				String lastDateStr=new SimpleDateFormat("dd-MMM-yyyy").format(lastDate);
				if(lastDate.after(requestDate))
				{
					flag=99;
					FacesContext fc=FacesContext.getCurrentInstance();
					fc.addMessage(null, new FacesMessage("New Personal Loan Request can't Add Before the Last Personal Loan Date. Your Last Personal Loan No. "+lastDepositNo +" Request Date is: "+lastDateStr));
				}
			}
		}
 		*/
 		
 		boolean checkDuplicate=new DataBaseAutoCompAndDuplicate().checkLoanNoDuplicacy(loanNo,"secure_loan");
 		
 		if(duration<=0)
		{
			flag=99;
		}
 		else if(loanAmount<=0)
		{
			flag=98;
		}
 		else if(checkDuplicate==true)
		{
			flag=97;
		}
 		
 		
 		if(flag==1)
 		{
 			//double remainingCompanyCapitalAmount=obj.remainingCompanyCapitalAmount();
 		    calculateEMI();
 		    if(guarantor1==null || guarantor1.equals(""))
 		    {
 		    	guarantor1="";
 		    }
 		    else
 		    {
 		    	if(guarantor1.contains("/"))
 		    	{
 		    		guarantor1=guarantor1.substring(0,guarantor1.indexOf("/"));
 		    	}
 		    }
 		    
 		    if(guarantor2==null || guarantor2.equals(""))
 		    {
 		    	guarantor2="";
 		    }
 		    else
 		    {
 		    	if(guarantor2.contains("/"))
 		    	{
 		    		guarantor2=guarantor2.substring(0,guarantor2.indexOf("/"));
 		    	}
 		    	
 		 	}
 		  
 		    if(fileCharge.trim().equals(""))
 			   {
 				   fileCharge="0";
 			   }
 			   if(insuranceFee.trim().equals(""))
 			   {
 				   insuranceFee="0";
 			   }
// 		    if(loanAmount<=200000)
// 		    {
 			   commission=0;
 		    	int i=obj.addSecureLoanRequest(branchId,shareHolderNo,guarantor1,guarantor2,loanNo,idProof,fileCharge,loanAmount,interst,duration,frequency,emiPayment,
 		    			requestDate,reason,rd_fdNo,discount,emiType, appChqNo, appAccNo, appBankName, appBankBranch, 
 		    			g1ChqNo, g1AccNo, g1BankName, g1BankBranch, g2ChqNo, g2AccNo, g2BankName, g2BankBranch,dsaCode,commission, insuranceFee, center,plan_no, emiMode
 		    			,extraAmt, securityType,billAmount,downPayment,product,dealer,imeiNoI,imeiNoII,dptCharge,cardFee,category);
 		        if(i>=1)
 		        {
 		        	if(securityType.equalsIgnoreCase("13")) {
 		        	obj.insertLoanOtherDetail(otherList, loanNo);
 		        	}
 		        	
 					fc.addMessage(null, new FacesMessage("Secure Loan Request Submit Succesfully"));
 					
 					if(paymentMode.equalsIgnoreCase("cash"))
					{   
 						System.out.println("st: " + securityType);
 						
 						String fcStatus=obj.checkSettingFromMasterSettingNewTable("File Charge", conn);
 						
 						if(!securityType.equalsIgnoreCase("14") && !securityType.equalsIgnoreCase("15")) 
 						{
	 						if(fcStatus.equalsIgnoreCase("loan_request"))
	 						{
	 							insertFileChargeInIncomeTable(conn, "active");
	 							if(Double.valueOf(fileCharge)>0)
	 							{							
	 									obj.increaseCompanyCapitalAmount(branchId,Double.valueOf(fileCharge), conn);
	 									fc.addMessage(null, new FacesMessage("File Charge "+fileCharge +" Rs. Add Sucessfully By "+paymentMode));			
	 							}
	 						}
	 						else 
	 						{
	 							if ("SILVER ROCK MICRO CARE ASSOCIATION".equalsIgnoreCase(companyName) || 
	 								"DELIGHTS MICRO CREDIT INDIA FOUNDATION".equalsIgnoreCase(companyName)) 
	 							{
	 								if(!securityType.equalsIgnoreCase("14")&& !securityType.equalsIgnoreCase("15"))
									{
	 									insertFileChargeInIncomeTable(conn, "pending");
	 									fc.addMessage(null, new FacesMessage("File Charge "+fileCharge +" Rs. Add For Pay Later."));
									}
								}
							}
 						}
 						else
 						{
 							if(!securityType.equalsIgnoreCase("14")&&!securityType.equalsIgnoreCase("15"))
							{
								insertFileChargeInIncomeTable(conn, "pending");
								fc.addMessage(null, new FacesMessage("File Charge "+fileCharge +" Rs. Add For Pay Later."));
							}
 						}
						
 						String insFeeStatus=obj.checkSettingFromMasterSettingNewTable("Insurance Fee", conn);
 						if(insFeeStatus.equalsIgnoreCase("loan_request"))
 						{
 							insertInsuranceFeeInIncomeTable(conn, "active");
 							if(Double.valueOf(insuranceFee)>0)
 							{
 								obj.increaseCompanyCapitalAmount(branchId,Double.valueOf(insuranceFee), conn);
 								fc.addMessage(null, new FacesMessage("Insurance Fee "+insuranceFee +" Rs. Add Sucessfully By "+paymentMode));
 							}
 						}
 						else
 						{
 							if(!securityType.equalsIgnoreCase("14")&&!securityType.equalsIgnoreCase("15"))
							{
 								System.out.println("if : " + insuranceFee);
								insertInsuranceFeeInIncomeTable(conn, "pending");
								fc.addMessage(null, new FacesMessage("Insurance Fee "+insuranceFee +" Rs. Add For Pay Later."));
							}
 						}
						
					}
					else
					{
						if(Double.valueOf(fileCharge)>0)
						{
							insertFileChargeInIncomeTable(conn, "active");
							fc.addMessage(null, new FacesMessage("Please Appprove File Charge Payment Rs. "+fileCharge));
						}
						if(Double.valueOf(insuranceFee)>0)
						{
							insertInsuranceFeeInIncomeTable(conn, "active");
							fc.addMessage(null, new FacesMessage("Please Appprove Insurance Fee Payment Rs. "+insuranceFee));
						}
			        	
					}
 					
 					try {
						conn.close();
					} catch (Exception e) {
						// TODO: handle exception
					}
 					selectedUser=guarantorUser1=guarantoruser2=null;
 					emiPayment=loanAmount=interst=duration=frequency=discount=0;
 					idProof=null;
 					show=false;
 					guarantor1=guarantor2=shareHolderNo=fileCharge=reason=insuranceFee="";
 					
 					return "mainDashBoard.xhtml";
 		        }
 		        else
 		        {
 		        	fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
 		        }
 		    //}
// 		    else
// 			   {
// 				   FacesContext fc=FacesContext.getCurrentInstance();
// 				   fc.addMessage(null, new FacesMessage("Sorry! Loan Amount Can't Be Greater Than Rs. 2 Lac. "));
// 			   }
 		}
 		else if(flag==99)
 		{
 			fc.addMessage(null, new FacesMessage("Please Select Valid No. of Installments Terms."));
 		}
 		else if(flag==98)
 		{
 			fc.addMessage(null, new FacesMessage("Please Enter Valid Loan Amount."));
 		}
 		else if(flag==97)
 		{
 			fc.addMessage(null, new FacesMessage("ALERT !!! SAME LOAN NO FOUND IN OTHER BRANCH, PLEASE ENTER UNIQUE LOAN NO PROPERLY !!! THANK YOU !!!"));
 		}
 		else
 		{
 			fc.addMessage(null, new FacesMessage("Some Error Occured!!!"));
 		}
	   
	    
	        return "";
	}
   
	private void insertFileChargeInIncomeTable(Connection conn, String entryStatus) 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		if(paymentMode.equalsIgnoreCase("cash"))
		{
			submittedBankName="N/A";
		}
		// Comment by Mr. Chetan Garg Due To Editable of File Charge Amount
		//if(Integer.parseInt(fileCharge)>0)
		{
			String voucherNo=obj.generateVoucherNo(branchId,"income_table",conn);
			new DataBaseIncomeExpense().addIncome(branchId,requestDate,"Other_Cr",paymentMode,String.valueOf(fileCharge),chequeNo,bankBranch,
					bankName,chequeDate,"File Charge Receive","File Charge",0,submittedBankName,
					"0",0,loanNo,"Secure Loan", voucherNo,"",0, entryStatus,""); 
		}
	}
	
	private void insertInsuranceFeeInIncomeTable(Connection conn, String entryStatus) 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		if(paymentMode.equalsIgnoreCase("cash"))
		{
			submittedBankName="N/A";
		}
		// Comment by Mr. Chetan Garg Due To Editable of File Charge Amount
		//if(Integer.parseInt(insuranceFee)>0)
		{
			String voucherNo=obj.generateVoucherNo(branchId,"income_table",conn);
			new DataBaseIncomeExpense().addIncome(branchId,requestDate,"Other_Cr",paymentMode,String.valueOf(insuranceFee),chequeNo,bankBranch,
					bankName,chequeDate,"Insurance Fee Receive","Insurance Fee",0,submittedBankName,
					"0",0,loanNo,"Secure Loan", voucherNo,"",0,entryStatus,"");
		}
	}

	public Date getRequestDate() {
		return requestDate;
	}
	public void setRequestDate(Date requestDate) {
		this.requestDate = requestDate;
	}
	public static List<String> getList() {
		return list;
	}
	public static void setList(List<String> list) {
		PersonalLoanBean.list = list;
	}
	public boolean isShow() {
		return show;
	}
	public void setShow(boolean show) {
		this.show = show;
	}
	public String getReason() {
		return reason;
	}
	public void setReason(String reason) {
		this.reason = reason;
	}
	public String getShareHolderNo() {
		return shareHolderNo;
	}
	public void setShareHolderNo(String shareHolderNo) {
		this.shareHolderNo = shareHolderNo;
	}
	public String getGuarantor1() {
		return guarantor1;
	}
	public void setGuarantor1(String guarantor1) {
		this.guarantor1 = guarantor1;
	}
	public String getGuarantor2() {
		return guarantor2;
	}
	public void setGuarantor2(String guarantor2) {
		this.guarantor2 = guarantor2;
	}
	public String getLoanNo() {
		return loanNo;
	}
	public void setLoanNo(String loanNo) {
		this.loanNo = loanNo;
	}
	public String getFileCharge() {
		return fileCharge;
	}
	public void setFileCharge(String fileCharge) {
		this.fileCharge = fileCharge;
	}
	public double getLoanAmount() {
		return loanAmount;
	}
	public boolean isShowProductLabel() {
	    return showProductI || showProductII;
	}
	public void setLoanAmount(double loanAmount) {
		this.loanAmount = loanAmount;
	}
	public double getInterst() {
		return interst;
	}
	public void setInterst(double interst) {
		this.interst = interst;
	}
	public double getDuration() {
		return duration;
	}
	public void setDuration(double duration) {
		this.duration = duration;
	}
	public int getFrequency() {
		return frequency;
	}
	public void setFrequency(int frequency) {
		this.frequency = frequency;
	}
	public double getEmiPayment() {
		return emiPayment;
	}
	public void setEmiPayment(double emiPayment) {
		this.emiPayment = emiPayment;
	}
	public String[] getIdProof() {
		return idProof;
	}
	public void setIdProof(String[] idProof) {
		this.idProof = idProof;
	}
	public ArrayList<SelectItem> getPlanList() {
		return planList;
	}
	public void setPlanList(ArrayList<SelectItem> planList) {
		this.planList = planList;
	}

	public String getEmiType() {
		return emiType;
	}

	public void setEmiType(String emiType) {
		this.emiType = emiType;
	}

	public String getPlan_no() {
		return plan_no;
	}

	public void setPlan_no(String plan_no) {
		this.plan_no = plan_no;
	}


	public UserInfo getSelectedUser() {
		return selectedUser;
	}
	public void setSelectedUser(UserInfo selectedUser) {
		this.selectedUser = selectedUser;
	}
	public UserInfo getGuarantorUser1() {
		return guarantorUser1;
	}
	public void setGuarantorUser1(UserInfo guarantorUser1) {
		this.guarantorUser1 = guarantorUser1;
	}
	public UserInfo getGuarantoruser2() {
		return guarantoruser2;
	}
	public void setGuarantoruser2(UserInfo guarantoruser2) {
		this.guarantoruser2 = guarantoruser2;
	}
	public String getSelectedScheme() {
		return selectedScheme;
	}
	public void setSelectedScheme(String selectedScheme) {
		this.selectedScheme = selectedScheme;
	}
	public String getRd_fdNo() {
		return rd_fdNo;
	}
	public void setRd_fdNo(String rd_fdNo) {
		this.rd_fdNo = rd_fdNo;
	}
	public boolean isShowField() {
		return showField;
	}
	public void setShowField(boolean showField) {
		this.showField = showField;
	}

	public int getDiscount() {
		return discount;
	}

	public void setDiscount(int discount) {
		this.discount = discount;
	}

	public String getAppChqNo() {
		return appChqNo;
	}

	public void setAppChqNo(String appChqNo) {
		this.appChqNo = appChqNo;
	}

	public String getAppAccNo() {
		return appAccNo;
	}

	public void setAppAccNo(String appAccNo) {
		this.appAccNo = appAccNo;
	}

	public String getAppBankName() {
		return appBankName;
	}

	public void setAppBankName(String appBankName) {
		this.appBankName = appBankName;
	}

	public String getAppBankBranch() {
		return appBankBranch;
	}

	public void setAppBankBranch(String appBankBranch) {
		this.appBankBranch = appBankBranch;
	}

	public String getG1ChqNo() {
		return g1ChqNo;
	}

	public void setG1ChqNo(String g1ChqNo) {
		this.g1ChqNo = g1ChqNo;
	}

	public String getG1AccNo() {
		return g1AccNo;
	}

	public void setG1AccNo(String g1AccNo) {
		this.g1AccNo = g1AccNo;
	}

	public String getG1BankName() {
		return g1BankName;
	}

	public void setG1BankName(String g1BankName) {
		this.g1BankName = g1BankName;
	}

	public String getG1BankBranch() {
		return g1BankBranch;
	}

	public void setG1BankBranch(String g1BankBranch) {
		this.g1BankBranch = g1BankBranch;
	}

	public String getG2ChqNo() {
		return g2ChqNo;
	}

	public void setG2ChqNo(String g2ChqNo) {
		this.g2ChqNo = g2ChqNo;
	}

	public String getG2AccNo() {
		return g2AccNo;
	}

	public void setG2AccNo(String g2AccNo) {
		this.g2AccNo = g2AccNo;
	}

	public String getG2BankName() {
		return g2BankName;
	}

	public void setG2BankName(String g2BankName) {
		this.g2BankName = g2BankName;
	}

	public String getG2BankBranch() {
		return g2BankBranch;
	}

	public void setG2BankBranch(String g2BankBranch) {
		this.g2BankBranch = g2BankBranch;
	}

	public ArrayList<SelectItem> getDsaList() {
		return dsaList;
	}

	public void setDsaList(ArrayList<SelectItem> dsaList) {
		this.dsaList = dsaList;
	}

	public String getDsaCode() {
		return dsaCode;
	}

	public void setDsaCode(String dsaCode) {
		this.dsaCode = dsaCode;
	}

	public double getCommission() {
		return commission;
	}

	public void setCommission(double commission) {
		this.commission = commission;
	}

	public String getInsuranceFee() {
		return insuranceFee;
	}

	public void setInsuranceFee(String insuranceFee) {
		this.insuranceFee = insuranceFee;
	}

	public String getCenter() {
		return center;
	}

	public void setCenter(String center) {
		this.center = center;
	}

	public ArrayList<SelectItem> getCenterList() {
		return centerList;
	}

	public void setCenterList(ArrayList<SelectItem> centerList) {
		this.centerList = centerList;
	}

	public DsaListInfo getDsa_info() {
		return dsa_info;
	}

	public void setDsa_info(DsaListInfo dsa_info) {
		this.dsa_info = dsa_info;
	}
	public List<String> completeText(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	     branchId = (int) ss.getAttribute("branchId");
		list=new DataBaseAutoCompAndDuplicate().shareHolderAllNo(branchId,name);
     	return list;
	}
	
	public List<String> complete_RD_FD_No(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		list=new DataBaseAutoCompAndDuplicate().rd_FD_NoOfUser(branchId,name,selectedScheme,shareHolderNo);
     	return list;
	}



	public DataBaseMethods getObj() {
		return obj;
	}



	public void setObj(DataBaseMethods obj) {
		this.obj = obj;
	}



	public ArrayList<SelectItem> getBankList() {
		return bankList;
	}



	public void setBankList(ArrayList<SelectItem> bankList) {
		this.bankList = bankList;
	}



	public ArrayList<SelectItem> getBankNameList() {
		return bankNameList;
	}



	public void setBankNameList(ArrayList<SelectItem> bankNameList) {
		this.bankNameList = bankNameList;
	}



	public String getPaymentMode() {
		return paymentMode;
	}



	public void setPaymentMode(String paymentMode) {
		this.paymentMode = paymentMode;
	}



	public String getChequeNo() {
		return chequeNo;
	}



	public void setChequeNo(String chequeNo) {
		this.chequeNo = chequeNo;
	}



	public String getBankBranch() {
		return bankBranch;
	}



	public void setBankBranch(String bankBranch) {
		this.bankBranch = bankBranch;
	}



	public String getBankName() {
		return bankName;
	}



	public void setBankName(String bankName) {
		this.bankName = bankName;
	}



	public String getSubmittedBankName() {
		return submittedBankName;
	}



	public void setSubmittedBankName(String submittedBankName) {
		this.submittedBankName = submittedBankName;
	}



	public String getLabel() {
		return label;
	}



	public void setLabel(String label) {
		this.label = label;
	}



	public String getDescription() {
		return description;
	}



	public void setDescription(String description) {
		this.description = description;
	}



	public boolean isShowCheque() {
		return showCheque;
	}



	public void setShowCheque(boolean showCheque) {
		this.showCheque = showCheque;
	}



	public boolean isShowFields() {
		return showFields;
	}



	public void setShowFields(boolean showFields) {
		this.showFields = showFields;
	}



	public boolean isShowMode() {
		return showMode;
	}



	public void setShowMode(boolean showMode) {
		this.showMode = showMode;
	}



	public Date getChequeDate() {
		return chequeDate;
	}



	public void setChequeDate(Date chequeDate) {
		this.chequeDate = chequeDate;
	}
	public String getEmiMode() {
		return emiMode;
	}
	public void setEmiMode(String emiMode) {
		this.emiMode = emiMode;
	}
	public ArrayList<UserInfo> getDocList() {
		return docList;
	}
	public void setDocList(ArrayList<UserInfo> docList) {
		this.docList = docList;
	}
	public boolean isRenderDoc() {
		return renderDoc;
	}
	public void setRenderDoc(boolean renderDoc) {
		this.renderDoc = renderDoc;
	}



	public double getExtraAmt() {
		return extraAmt;
	}



	public void setExtraAmt(double extraAmt) {
		this.extraAmt = extraAmt;
	}

	public boolean isSkip() {
		return skip;
	}

	public void setSkip(boolean skip) {
		this.skip = skip;
	}


	
	public String getSecurityType() {
		return securityType;
	}

	public void setSecurityType(String securityType) {
		this.securityType = securityType;
	}

	public ArrayList<SelectItem> getSecureTypeList() {
		return secureTypeList;
	}

	public void setSecureTypeList(ArrayList<SelectItem> secureTypeList) {
		this.secureTypeList = secureTypeList;
	}

	public boolean isReqMudraFin() {
		return reqMudraFin;
	}

	public void setReqMudraFin(boolean reqMudraFin) {
		this.reqMudraFin = reqMudraFin;
	}

	public boolean isRenAutoLoanNo() {
		return renAutoLoanNo;
	}

	public void setRenAutoLoanNo(boolean renAutoLoanNo) {
		this.renAutoLoanNo = renAutoLoanNo;
	}

	public boolean isRenManualLoanNo() {
		return renManualLoanNo;
	}

	public void setRenManualLoanNo(boolean renManualLoanNo) {
		this.renManualLoanNo = renManualLoanNo;
	}

	public ArrayList<LoanInfo> getOtherList() {
		return otherList;
	}

	public void setOtherList(ArrayList<LoanInfo> otherList) {
		this.otherList = otherList;
	}

	public double getBillAmount() {
		return billAmount;
	}

	public void setBillAmount(double billAmount) {
		this.billAmount = billAmount;
	}

	public double getDownPayment() {
		return downPayment;
	}

	public void setDownPayment(double downPayment) {
		this.downPayment = downPayment;
	}

	public boolean isShowMobile() {
		return showMobile;
	}

	public void setShowMobile(boolean showMobile) {
		this.showMobile = showMobile;
	}

	public ArrayList<SelectItem> getDealerList() {
		return dealerList;
	}

	public void setDealerList(ArrayList<SelectItem> dealerList) {
		this.dealerList = dealerList;
	}

	public ArrayList<SelectItem> getProductList() {
		return productList;
	}

	public void setProductList(ArrayList<SelectItem> productList) {
		this.productList = productList;
	}

	public String getProduct() {
		return product;
	}

	public void setProduct(String product) {
		this.product = product;
	}

	public String getDealer() {
		return dealer;
	}

	public void setDealer(String dealer) {
		this.dealer = dealer;
	}

	public String getImeiNoI() {
		return imeiNoI;
	}

	public void setImeiNoI(String imeiNoI) {
		this.imeiNoI = imeiNoI;
	}

	public String getImeiNoII() {
		return imeiNoII;
	}

	public void setImeiNoII(String imeiNoII) {
		this.imeiNoII = imeiNoII;
	}

	public boolean isShowVehicle() {
		return showVehicle;
	}

	public void setShowVehicle(boolean showVehicle) {
		this.showVehicle = showVehicle;
	}


	public double getDptCharge() {
		return dptCharge;
	}


	public void setDptCharge(double dptCharge) {
		this.dptCharge = dptCharge;
	}


	public double getCardFee() {
		return cardFee;
	}


	public void setCardFee(double cardFee) {
		this.cardFee = cardFee;
	}


	public String getLoanName() {
		return loanName;
	}


	public void setLoanName(String loanName) {
		this.loanName = loanName;
	}


	public boolean isShowProductI() {
		return showProductI;
	}


	public void setShowProductI(boolean showProductI) {
		this.showProductI = showProductI;
	}


	public boolean isShowProductII() {
		return showProductII;
	}


	public void setShowProductII(boolean showProductII) {
		this.showProductII = showProductII;
	}


	public String getCompanyName() {
		return companyName;
	}


	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}


	public boolean isGuarantorTabView() {
		return guarantorTabView;
	}


	public void setGuarantorTabView(boolean guarantorTabView) {
		this.guarantorTabView = guarantorTabView;
	}


	public boolean isShowDownPayment() {
		return showDownPayment;
	}


	public void setShowDownPayment(boolean showDownPayment) {
		this.showDownPayment = showDownPayment;
	}


	public boolean isShowBillAmount() {
		return showBillAmount;
	}


	public void setShowBillAmount(boolean showBillAmount) {
		this.showBillAmount = showBillAmount;
	}


	public boolean isShowDealer() {
		return showDealer;
	}


	public void setShowDealer(boolean showDealer) {
		this.showDealer = showDealer;
	}


	public String getCompanyNames() {
		return companyNames;
	}


	public void setCompanyNames(String companyNames) {
		this.companyNames = companyNames;
	}

	public ArrayList<SelectItem> getCategoryList() {
		return categoryList;
	}


	public void setCategoryList(ArrayList<SelectItem> categoryList) {
		this.categoryList = categoryList;
	}


	public String getCategory() {
		return category;
	}


	public void setCategory(String category) {
		this.category = category;
	}


	public ArrayList<SelectItem> getProductListByCategoryType() {
		return productListByCategoryType;
	}


	public void setProductListByCategoryType(ArrayList<SelectItem> productListByCategoryType) {
		this.productListByCategoryType = productListByCategoryType;
	}


	public ArrayList<LoanInfo> getAllLoanList() {
		return allLoanList;
	}


	public void setAllLoanList(ArrayList<LoanInfo> allLoanList) {
		this.allLoanList = allLoanList;
	}
	
}
