package main_package;

import group_head_package.DataBaseIncomeExpense;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
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;

@ManagedBean(name="groupLoanCenterWise")
@ViewScoped
public class GroupLoanCenterWiseBean implements Serializable
{
	private static final long serialVersionUID = 1L;
	String center,appType="multiple",shareHolderNo,subLoanNo,tempType="new",guarantor1,guarantor2,loanNo,fileCharge="0", insuranceFee="0",plan_no,selectedScheme,rd_fdNo,common="",emiType="flat";
	UserInfo selectedUser,guarantorUser1,guarantoruser2;
	double loanAmount,interst,duration,emiPayment;
	int frequency,discount;
	ArrayList<UserInfo> selectedUserList=new ArrayList<>();
	ArrayList<UserInfo> userList=new ArrayList<>();
	boolean show,showFirst,ShowSecond,showField,showForm,disableCom,showColumn,showType;
	ArrayList<SelectItem> centerList,planList,dsaList, loanCategoryList, repaymentFreqList;
	public static List<String> list;
	UserInfo selectedMember;
	Date requestDate;
	String[] idProof;
	String appChqNo, appAccNo, appBankName, appBankBranch, g1ChqNo, g1AccNo, g1BankName,dsaCode, g1BankBranch, g2ChqNo, g2AccNo, g2BankName, g2BankBranch;
	DsaListInfo dsa_info;
	double commission=0, extraAmount;
	String groupType="1", groupLoanNo;
	boolean showShareNo, showLoanNo,requiredCibilFiled, disGroupType=false,checkdisableForMultipleSelection=false,checkdisableForIndividualSelection=false, disDsa;
	DataBaseMethods obj=new DataBaseMethods();
	String loanCategory, loanCycle, loanPurpose, repaymentFreq;
	double processingCharge;
	
	
	
	public GroupLoanCenterWiseBean() 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		//String userId=obj.userId();
		dsaList=obj.allDsaList(branchId,"Loan",conn);
		
		if(obj.userType().equals("employee"))
		{
			//dsaCode=obj.dsaCodeByEmpUserId(userId, conn);  // comment due to DSA/Emp comese from Center Table
			disDsa=true;
		}
		loanCategoryList=obj.highMarkTableList("Loan Category", conn);
		repaymentFreqList=obj.highMarkTableList("Repayment Frequency", conn);
		
		String crifNo=obj.checkSMessageApiDetailFromTable("crif_no","", conn);
		if(crifNo!=null && !crifNo.equalsIgnoreCase(""))
		{
			requiredCibilFiled=true;
		}
		else
		{
			requiredCibilFiled=false;
		}
		 centerList=obj.allcenter(branchId,"all",conn);
		
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	
	public void memberNoListByCenter()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		
		userList=obj.centerAllotListMethod(branchId,center,conn);
		for(int i=0;i<userList.size();i++)
		{
			userList.get(i).setDisableAddLoan(obj.checkMemberListInGLTableByCenter(center, userList.get(i).getShareHolderNo()));
		}
		
		show=true;
		checkApplicationType();
		
		requestDate=new Date(); 
        planList=obj.allPlans(branchId,"Loan");
        dsaFromCenterMethod();
       
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void dsaFromCenterMethod()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		dsaCode=obj.dsaCodeFromCenterTable(center,branchId);
	}
	
	public void deleteMember()
	{
		int j=0;
		int i=0;
		for(UserInfo ls:userList)
        {
			if(ls.getShareHolderNo().equals(selectedMember.getShareHolderNo()))
       	  	{
       		  j=i;
       		  break;
       	  	}
			i++;
        }
        if(j>=0)
        {
        	userList.remove(j);
        }
	}
	
	public void viewDetails()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		
		guarantorUser1=obj.userInfoByShareHolderNo(selectedMember.getShareHolderNo(), conn);
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		ss.setAttribute("viewselecteduser", guarantorUser1);
			
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    RequestContext.getCurrentInstance().execute("window.open('viewCompleteDetails.xhtml')");
	}
	
	public void checkPlan()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		CenterInfo cf=obj.selectedPlanInfo(plan_no);
		interst=cf.getInterestRate();
		loanAmount=cf.getLoanAmount();
		emiPayment=cf.getEmi();
		emiType=cf.getEmiType();
		frequency=cf.getFrequency();
		duration=cf.getTerms();
		if(loanAmount>0)
		{
			fileCharge=String.valueOf((loanAmount*cf.getFileChargePlan())/100);
			insuranceFee=String.valueOf((loanAmount*cf.getInsuranceFeePlan())/100);
		}
		
		dsaFromCenterMethod();
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void calculateEMI()
	{
		emiPayment=discount=0;
		if(emiType.equals("reducing"))
		{
			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
		{
			emiPayment=obj.calculateLoanEmiForCalculator(loanAmount,duration, interst, frequency,"both");  	
			if(loanAmount==0)
			{
				emiPayment=0;discount=0;
			}
			
			if(emiPayment>0)
			{
				double totalPayment=emiPayment*duration;
				double falseInterest=totalPayment-loanAmount;
				double trueInterest=(loanAmount*interst*duration)/(100*frequency);
				trueInterest=Math.round(trueInterest);
				discount=(int) (falseInterest-trueInterest);
				discount=Math.round(discount);	
				
				
			}
		}
	}

	public void calculateCommission()
	{

  if(dsaCode !=null)
	{ 
		dsa_info=obj.dsaInfoByCode(dsaCode,"Loan");
		double loanAmt=loanAmount;
		String commType=dsa_info.getCommission_type();
		double commVal=dsa_info.getCommission_value();
		// System.out.println(commType);
		// System.out.println(commVal);
		if(commType.equals("flat"))
		{
			commission=commVal;
		}
		else
		{
			commission=(loanAmt*commVal)/100;
			commission=Double.parseDouble(new DecimalFormat("##.##").format(commission));
		}
		// System.out.println(commission);
	}
	}
	
	public void checkApplicationType()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		// System.out.println("hello : "+appType);
		if(groupType.equals("1"))
		{
			loanNo=obj.groupLoanNo(branchId); 	
	    }
		else
		{
			loanNo=groupLoanNo; 	
	    }
		if(loanNo.equals(""))
        {
            loanNo="1";	        	
        }
		checkdisableForIndividualSelection=false;
		showColumn=false;
		checkdisableForMultipleSelection=true;
		showForm=true;
		subLoanNo="";
	}
	
	public void openLoanForm()
	{
		boolean checkDup=new DataBaseMethodsDuplicate().checkDuplicateGroupLoan(loanNo,selectedMember.getShareHolderNo());
		if(checkDup==true)
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Loan is Already Given to This Member."));
		}
		else
		{
			int limit=obj.checkGroupLoanLimit();
			if(userList.size()<limit)
			{
				FacesContext fc=FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Minimum "+limit+" Member Are Required In Group Inculding Team Leader "));
				showForm=false;
			}
			else
			{
				tempType="old";
				if(appType.equalsIgnoreCase("common"))
				{
					subLoanNo=loanNo;
				}
				else
				{
					findLoanSubNo();
				}
				/*common="";
				loanNo=obj.groupLoanNo(); 	
		        if(loanNo.equals(""))
		        {
		            loanNo="1";	        	
		        }
		        */
		        showForm=true;
			}
		}
		
	}
	
	public void findLoanSubNo()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		//String loanType="grouploan";
		String num=obj.findSubLoanNo(branchId,loanNo);
		if(num.equalsIgnoreCase("NA"))
		{
			subLoanNo=loanNo+"S"+1;
		}
		else
		{
			String tmp[]=num.split("S");
			int x=Integer.valueOf(tmp[1]);
			x=x+1;
			subLoanNo=tmp[0]+"S"+x;
		}
	}

	public void proceed()
	{
		int limit=obj.checkGroupLoanLimit();
		if(groupType.equals("1"))
		{
			if(userList.size()<limit)
			{
				FacesContext fc=FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Minimum "+limit+" Member Are Required In Group Inculding Team Leader "));
				showType=false;
			}
			else
			{
				showType=true;
			}
		}
		else
		{
			showType=true;
		}
	}
	
	public void addTeamLeader()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		
		int i=obj.checkMemberInList(userList,shareHolderNo);
		if(i>0)
		{
			FacesContext fc=FacesContext.getCurrentInstance();
		 	fc.addMessage(null, new FacesMessage("Member Already Exist.."));
		}
		else
		{
			guarantorUser1=obj.userInfoByShareHolderNo(shareHolderNo, conn);
			if(guarantorUser1!=null)
			{
				userList.add(guarantorUser1);
			}
			else
			{
				FacesContext fc=FacesContext.getCurrentInstance();
			 	fc.addMessage(null, new FacesMessage("First Guarantor User Not Valid.."));
			}
		}
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void firstGuantorDetails()
	{
		if(appType==null)
		{
			checkdisableForIndividualSelection=true;
		}
		else if(appType.equalsIgnoreCase("multiple"))
		{
			checkdisableForIndividualSelection=false;
			checkdisableForMultipleSelection=true;
		}
		else
		{
			checkdisableForIndividualSelection=true;
			checkdisableForMultipleSelection=false;
		}
		if(guarantor1==null)
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Please Enter a Member First!"));
		}
		else
		{
			guarantor1=guarantor1.substring(0,guarantor1.indexOf("/"));
			if(groupType.equals("1"))
			{
				if(shareHolderNo.equals(guarantor1))
				{
					FacesContext fc=FacesContext.getCurrentInstance();
					fc.addMessage(null, new FacesMessage("Team Leader Already Added In List"));
				}
				else
				{
					addNewMember();
				}
			}
			else
			{
				addNewMember();
			}
		}
		guarantor1="";
	}

	
	
	private void addNewMember() 
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		
		/*HeaderBean hh=new HeaderBean();
		int i=obj.checkMemberInList(userList,guarantor1);
		if(hh.getName().equalsIgnoreCase("YASHIKA DIKSHA NIDHI LIMITED"))             // As per Client Need
		{
			i=0;
		}
		if(i>0)
		{
			FacesContext fc=FacesContext.getCurrentInstance();
		 	fc.addMessage(null, new FacesMessage("Member Already Exist.."));
		}
		else
		{
			guarantorUser1=obj.userInfoByShareHolderNo(guarantor1, conn);
			if(guarantorUser1!=null)
			{
				guarantorUser1.setDisableAddLoan(false);
				userList.add(guarantorUser1);
			}
			else
			{
				FacesContext fc=FacesContext.getCurrentInstance();
			 	fc.addMessage(null, new FacesMessage("Member Not Valid.."));
			}
		}*/
		
		guarantorUser1=obj.userInfoByShareHolderNo(guarantor1, conn);
		if(guarantorUser1!=null)
		{
			guarantorUser1.setDisableAddLoan(false);
			userList.add(guarantorUser1);
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
		 	fc.addMessage(null, new FacesMessage("Member Not Valid.."));
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void secondGuantorDetails()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		
		guarantorUser1=obj.userInfoByShareHolderNo(guarantor2, conn);
		if(guarantorUser1!=null)
		{
			RequestContext.getCurrentInstance().execute("PF('Guarantor').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 addRequestLoan() throws IOException
   {
	   HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
	   Connection conn=DataBaseConnection.JAVAConnection();

	   if(appType.equalsIgnoreCase("Multiple"))
	   {
		   
		   if(tempType.equals("new"))
		   {
			   loanNo=obj.groupLoanNo(branchId); 	
		       if(loanNo.equals(""))
		       {
		           loanNo="1";	        	
		       } 
		   }
	  int i=0;
	  int count=1;
	   for(UserInfo tt :selectedUserList)
	   {

		//String loanType="grouploan";
		   String num=obj.findSubLoanNo(branchId,loanNo);
			if(num.equalsIgnoreCase("NA"))
			{
				subLoanNo=loanNo+"S"+1;
			}
			else
			{
				String tmp[]=num.split("S");
				int x=Integer.valueOf(tmp[1]);
				x=x+1;
				subLoanNo=tmp[0]+"S"+x;
			}
		count++;
	   calculateEMI();
	   
	  //double remainingCompanyCapitalAmount=obj.remainingCompanyCapitalAmount();
	   int limit=obj.checkGroupLoanLimit();
	   if(groupType.equals("2"))
	   {
		   limit=0;
	   }
	   if(userList.size()<limit)
	   {
		   FacesContext fc=FacesContext.getCurrentInstance();
		   fc.addMessage(null, new FacesMessage("Minimum "+limit+" Member Are Required In Group Inculding Team Leader "));
	   }
	   else
	   {
//		   if(loanAmount<=200000)
//		   {
		    /*if(common.equalsIgnoreCase("common"))
			{*/
			   String tempShareNo=shareHolderNo;
			   if(appType.equalsIgnoreCase("individual"))
			   {
				   tempShareNo=selectedMember.getShareHolderNo();
			   }
			   else if(appType.equalsIgnoreCase("multiple"))
			   {
				   tempShareNo=new DataBaseMethods().shareHolderNoByRdFdNo(tt.getUser_no());
			   }
			   
			   
			   if(fileCharge.trim().equals(""))
			   {
				   fileCharge="0";
			   }
			   if(insuranceFee.trim().equals(""))
			   {
				   insuranceFee="0";
			   }
			 commission=0;  /// commission credit at Loan Approve 
		    i=obj.addGroupLoanRequest(branchId,tt.getShareHolderNo(),loanNo,idProof,fileCharge,loanAmount,interst,duration,frequency,emiPayment,requestDate,userList,center,
		    		rd_fdNo,discount,emiType,appChqNo, appAccNo, appBankName, appBankBranch, g1ChqNo, g1AccNo, g1BankName,
		    		g1BankBranch, g2ChqNo, g2AccNo, g2BankName, g2BankBranch,dsaCode,commission,appType,subLoanNo, insuranceFee, groupType, plan_no, extraAmount
		    		,loanCategory, loanCycle, loanPurpose, repaymentFreq, processingCharge);
		

		     if(i>=1)
		       {
		        	FacesContext fc=FacesContext.getCurrentInstance();
					fc.addMessage(null, new FacesMessage("Loan Request Submitted Succesfully"));
					
					String fcStatus=obj.checkSettingFromMasterSettingNewTable("File Charge", conn);
					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."));
						}
					}
					else
					{
						insertFileChargeInIncomeTable(conn, "pending");
						fc.addMessage(null, new FacesMessage("File Charge "+fileCharge +" Rs. Add For Pay Later."));
					}
					
					String pcStatus=obj.checkSettingFromMasterSettingNewTable("Processing Charge", conn);
					if(pcStatus.equalsIgnoreCase("loan_request"))
					{
						insertProcessingFeeInIncomeTable(conn, "active");
						if(Double.valueOf(processingCharge)>0)
						{
							obj.increaseCompanyCapitalAmount(branchId,Double.valueOf(processingCharge), conn);
							fc.addMessage(null, new FacesMessage("Processing Charge "+processingCharge +" Rs. Add Sucessfully."));
						}
					}
					else
					{
						insertProcessingFeeInIncomeTable(conn, "pending");
						fc.addMessage(null, new FacesMessage("Processing Charge "+processingCharge +" 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."));
						}
					}
					else
					{
						insertInsuranceFeeInIncomeTable(conn, "pending");
						fc.addMessage(null, new FacesMessage("Insurance Fee "+insuranceFee +" Rs. Add For Pay Later."));
					}
						
				//	guarantorUser1=guarantoruser2=null;
					if(common.equalsIgnoreCase("common"))
					{
						disableCom=true;
					}
					else
					{
						disableCom=false;
					}
				/*	appChqNo=appAccNo=appBankName=appBankBranch=g1ChqNo=g1AccNo=g1BankName=g1BankBranch=g2ChqNo=g2AccNo=g2BankName=g2BankBranch="";
					emiPayment=loanAmount=interst=duration=discount=0;
					commission=0;
					frequency=365;
					idProof=null;
					requestDate=null;
					emiType="flat";
					selectedScheme=rd_fdNo=plan_no=fileCharge=center=dsaCode="";
					showForm=false;*/
					
					if(appType.equalsIgnoreCase("common"))
					{
						FacesContext.getCurrentInstance().getExternalContext().redirect("mainDashBoard.xhtml");
					}
					else
					{
						if(!appType.equalsIgnoreCase("multiple"))
						{
						for(UserInfo ui : userList)
						{
							if(ui.getShareHolderNo().equals(selectedMember.getShareHolderNo()))
							{
								ui.setDisableAddLoan(true);
							}
						}
					}
					}
					//loanNo="";
					//userList=new ArrayList<>();
					//return "groupLoanDashboard.xhtml";
		        }
		        else
		        {
		        	FacesContext fc=FacesContext.getCurrentInstance();
		        	fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
		        } 
	   }
	   }
	   if(selectedUserList.size() ==0)
	   {
		   FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please Select Atleast one loan No."));
		  
	   }
	   else
	   {
	   appChqNo=appAccNo=appBankName=appBankBranch=g1ChqNo=g1AccNo=g1BankName=g1BankBranch=g2ChqNo=g2AccNo=g2BankName=g2BankBranch="";
		emiPayment=loanAmount=interst=duration=discount=0;
		commission=0;
		frequency=365;
		idProof=null;
		requestDate=null;
		emiType="flat";
		selectedScheme=rd_fdNo=plan_no=fileCharge=center=dsaCode="";
		showForm=false;
		showType=false;
		checkdisableForMultipleSelection=false;
		userList.clear();
	   }
	   }
	   else
	   {

			  
		   int i=0;
		   if(tempType.equals("new"))
		   {
			   loanNo=obj.groupLoanNo(branchId); 	
		       if(loanNo.equals(""))
		       {
		           loanNo="1";	        	
		       } 
		   }
	       
	       if(appType.equalsIgnoreCase("common"))
	       {
	    	   subLoanNo=loanNo;
	       }
	       else
	       {
	    	   findLoanSubNo();
	       }
	       
		   calculateEMI();
		   
		  //double remainingCompanyCapitalAmount=obj.remainingCompanyCapitalAmount();
		   int limit=obj.checkGroupLoanLimit();
		   if(groupType.equals("2"))
		   {
			   limit=0;
		   }
		   if(userList.size()<limit)
		   {
			   FacesContext fc=FacesContext.getCurrentInstance();
			   fc.addMessage(null, new FacesMessage("Minimum "+limit+" Member Are Required In Group Inculding Team Leader "));
		   }
		   else
		   {
//			   if(loanAmount<=200000)
//			   {
			    /*if(common.equalsIgnoreCase("common"))
				{*/
				   String tempShareNo=shareHolderNo;
				   if(!appType.equalsIgnoreCase("common"))
				   {
					   tempShareNo=selectedMember.getShareHolderNo();
				   }
				   
				   
				   if(fileCharge.trim().equals(""))
				   {
					   fileCharge="0";
				   }
				   if(insuranceFee.trim().equals(""))
				   {
					   insuranceFee="0";
				   }
				 commission=0;  /// commission credit at Loan Approve 
			    i=obj.addGroupLoanRequest(branchId,tempShareNo,loanNo,idProof,fileCharge,loanAmount,interst,duration,frequency,emiPayment,requestDate,userList,center,
			    		rd_fdNo,discount,emiType,appChqNo, appAccNo, appBankName, appBankBranch, g1ChqNo, g1AccNo, g1BankName,
			    		g1BankBranch, g2ChqNo, g2AccNo, g2BankName, g2BankBranch,dsaCode,commission,appType,subLoanNo, insuranceFee, groupType, plan_no, extraAmount
			    		,loanCategory, loanCycle, loanPurpose, repaymentFreq, 0);
				/*}
				else
				{
					i=obj.addGroupLoanRequest(selectedMember.getShareHolderNo(),loanNo,idProof,fileCharge,loanAmount,interst,duration,frequency,emiPayment,requestDate,userList,center,rd_fdNo,discount);
				}*/
				   
			       if(i>=1)
			       {
			        	FacesContext fc=FacesContext.getCurrentInstance();
						fc.addMessage(null, new FacesMessage("Loan Request Submitted Succesfully"));
						
						String fcStatus=obj.checkSettingFromMasterSettingNewTable("File Charge", conn);
						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."));
							}
						}
						else
						{
							insertFileChargeInIncomeTable(conn, "pending");
							fc.addMessage(null, new FacesMessage("File Charge "+fileCharge +" Rs. Add For Pay Later."));
						}
					
						String insFeeStatus=obj.checkSettingFromMasterSettingNewTable("File Charge", 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."));
							}
						}
						else
						{
							insertInsuranceFeeInIncomeTable(conn, "pending");
							fc.addMessage(null, new FacesMessage("Insurance Fee "+insuranceFee +" Rs. Add For Pay Later."));
						}
							
						guarantorUser1=guarantoruser2=null;
						if(common.equalsIgnoreCase("common"))
						{
							disableCom=true;
						}
						else
						{
							disableCom=false;
						}
						appChqNo=appAccNo=appBankName=appBankBranch=g1ChqNo=g1AccNo=g1BankName=g1BankBranch=g2ChqNo=g2AccNo=g2BankName=g2BankBranch="";
						emiPayment=loanAmount=interst=duration=discount=0;
						commission=0;
						frequency=365;
						idProof=null;
						requestDate=null;
						emiType="flat";
						selectedScheme=rd_fdNo=plan_no=fileCharge=center=dsaCode="";
						showForm=false;
						
						if(appType.equalsIgnoreCase("common"))
						{
							FacesContext.getCurrentInstance().getExternalContext().redirect("mainDashBoard.xhtml");
						}
						else
						{
							for(UserInfo ui : userList)
							{
								if(ui.getShareHolderNo().equals(selectedMember.getShareHolderNo()))
								{
									ui.setDisableAddLoan(true);
								}
							}
						}
						//loanNo="";
						//userList=new ArrayList<>();
						//return "groupLoanDashboard.xhtml";
			        }
			        else
			        {
			        	FacesContext fc=FacesContext.getCurrentInstance();
			        	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. "));
//			   }
		    
		   }
		   
	   }
	   try {
		conn.close();
	} catch (Exception e) {
		// TODO: handle exception
	}
	   //return "";
	}
   
   private void insertInsuranceFeeInIncomeTable(Connection conn, String string) 
   {
	   HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		
	   // 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","cash",String.valueOf(insuranceFee),"","",
					"",null,"Insurance Fee Receive","Insurance Fee",0,"N/A",
					"0",0,subLoanNo,"Group Loan", voucherNo,"",0,string,"");
		}
	}
   
   private void insertProcessingFeeInIncomeTable(Connection conn, String entryStatus) 
   {
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		
		String voucherNo = obj.generateVoucherNo(branchId, "income_table", conn);
		new DataBaseIncomeExpense().addIncome(branchId, requestDate, "Other_Cr", "cash", String.valueOf(processingCharge), 
				"", "", "", null, "Processing Charge Receive", "Processing Charge", 0, "N/A", "0", 0, subLoanNo,
				"Group Loan", voucherNo, "", 0, entryStatus, "");
	}
	
	private void insertFileChargeInIncomeTable(Connection conn, String string) 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		// 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","cash",String.valueOf(fileCharge),"","",
					"",null,"File Charge Receive","File Charge",0,"N/A",
					"0",0,subLoanNo,"Group Loan", voucherNo,"",0,string,""); 
		}
	}

   
	public String getCenter() {
		return center;
	}
	public void setCenter(String center) {
		this.center = center;
	}
	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 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 double getLoanAmount() {
		return loanAmount;
	}
	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 ArrayList<UserInfo> getUserList() {
		return userList;
	}
	public void setUserList(ArrayList<UserInfo> userList) {
		this.userList = userList;
	}
	public boolean isShow() {
		return show;
	}
	public void setShow(boolean show) {
		this.show = show;
	}
	public boolean isShowFirst() {
		return showFirst;
	}
	public void setShowFirst(boolean showFirst) {
		this.showFirst = showFirst;
	}
	public boolean isShowSecond() {
		return ShowSecond;
	}
	public void setShowSecond(boolean showSecond) {
		ShowSecond = showSecond;
	}
	public ArrayList<SelectItem> getCenterList() {
		return centerList;
	}
	public void setCenterList(ArrayList<SelectItem> centerList) {
		this.centerList = centerList;
	}
	public static List<String> getList() {
		return list;
	}
	public static void setList(List<String> list) {
		GroupLoanCenterWiseBean.list = list;
	}
	public UserInfo getSelectedMember() {
		return selectedMember;
	}
	public void setSelectedMember(UserInfo selectedMember) {
		this.selectedMember = selectedMember;
	}
	public Date getRequestDate() {
		return requestDate;
	}
	public void setRequestDate(Date requestDate) {
		this.requestDate = requestDate;
	}
	public String[] getIdProof() {
		return idProof;
	}
	public void setIdProof(String[] idProof) {
		this.idProof = idProof;
	}

	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 String getEmiType() {
		return emiType;
	}

	public void setEmiType(String emiType) {
		this.emiType = emiType;
	}

	public void setDiscount(int discount) {
		this.discount = discount;
	}

	public String getPlan_no() {
		return plan_no;
	}

	public void setPlan_no(String plan_no) {
		this.plan_no = plan_no;
	}

	public ArrayList<SelectItem> getPlanList() {
		return planList;
	}

	public void setPlanList(ArrayList<SelectItem> planList) {
		this.planList = planList;
	}

	public boolean isShowForm() {
		return showForm;
	}

	public void setShowForm(boolean showForm) {
		this.showForm = showForm;
	}

	public boolean isDisableCom() {
		return disableCom;
	}

	public void setDisableCom(boolean disableCom) {
		this.disableCom = disableCom;
	}

	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 getCommon() {
		return common;
	}

	public void setCommon(String common) {
		this.common = common;
	}

	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 boolean isShowColumn() {
		return showColumn;
	}

	public void setShowColumn(boolean showColumn) {
		this.showColumn = showColumn;
	}

	public String getAppType() {
		return appType;
	}

	public void setAppType(String appType) {
		this.appType = appType;
	}

	public String getSubLoanNo() {
		return subLoanNo;
	}

	public void setSubLoanNo(String subLoanNo) {
		this.subLoanNo = subLoanNo;
	}

	public boolean isShowType() {
		return showType;
	}

	public void setShowType(boolean showType) {
		this.showType = showType;
	}

	public String getTempType() {
		return tempType;
	}

	public void setTempType(String tempType) {
		this.tempType = tempType;
	}

	public String getInsuranceFee() {
		return insuranceFee;
	}

	public void setInsuranceFee(String insuranceFee) {
		this.insuranceFee = insuranceFee;
	}

	public DsaListInfo getDsa_info() {
		return dsa_info;
	}

	public void setDsa_info(DsaListInfo dsa_info) {
		this.dsa_info = dsa_info;
	}

	public String getGroupType() {
		return groupType;
	}

	public void setGroupType(String groupType) {
		this.groupType = groupType;
	}

	public boolean isShowShareNo() {
		return showShareNo;
	}

	public void setShowShareNo(boolean showShareNo) {
		this.showShareNo = showShareNo;
	}

	public boolean isShowLoanNo() {
		return showLoanNo;
	}

	public void setShowLoanNo(boolean showLoanNo) {
		this.showLoanNo = showLoanNo;
	}

	public boolean isDisGroupType() {
		return disGroupType;
	}

	public void setDisGroupType(boolean disGroupType) {
		this.disGroupType = disGroupType;
	}

	public String getGroupLoanNo() {
		return groupLoanNo;
	}

	public void setGroupLoanNo(String groupLoanNo) {
		this.groupLoanNo = groupLoanNo;
	}

	public ArrayList<UserInfo> getSelectedUserList() {
		return selectedUserList;
	}

	public void setSelectedUserList(ArrayList<UserInfo> selectedUserList) {
		this.selectedUserList = selectedUserList;
	}

	public boolean isCheckdisableForMultipleSelection() {
		return checkdisableForMultipleSelection;
	}

	public void setCheckdisableForMultipleSelection(
			boolean checkdisableForMultipleSelection) {
		this.checkdisableForMultipleSelection = checkdisableForMultipleSelection;
	}

	public boolean isCheckdisableForIndividualSelection() {
		return checkdisableForIndividualSelection;
	}

	public void setCheckdisableForIndividualSelection(
			boolean checkdisableForIndividualSelection) {
		this.checkdisableForIndividualSelection = checkdisableForIndividualSelection;
	}

	public double getExtraAmount() {
		return extraAmount;
	}

	public void setExtraAmount(double extraAmount) {
		this.extraAmount = extraAmount;
	}

	public ArrayList<SelectItem> getLoanCategoryList() {
		return loanCategoryList;
	}

	public void setLoanCategoryList(ArrayList<SelectItem> loanCategoryList) {
		this.loanCategoryList = loanCategoryList;
	}

	public ArrayList<SelectItem> getRepaymentFreqList() {
		return repaymentFreqList;
	}

	public void setRepaymentFreqList(ArrayList<SelectItem> repaymentFreqList) {
		this.repaymentFreqList = repaymentFreqList;
	}

	public String getLoanCategory() {
		return loanCategory;
	}

	public void setLoanCategory(String loanCategory) {
		this.loanCategory = loanCategory;
	}

	public String getLoanCycle() {
		return loanCycle;
	}

	public void setLoanCycle(String loanCycle) {
		this.loanCycle = loanCycle;
	}

	public String getLoanPurpose() {
		return loanPurpose;
	}

	public void setLoanPurpose(String loanPurpose) {
		this.loanPurpose = loanPurpose;
	}

	public String getRepaymentFreq() {
		return repaymentFreq;
	}

	public void setRepaymentFreq(String repaymentFreq) {
		this.repaymentFreq = repaymentFreq;
	}


	public boolean isDisDsa() {
		return disDsa;
	}


	public void setDisDsa(boolean disDsa) {
		this.disDsa = disDsa;
	}


	public boolean isRequiredCibilFiled() {
		return requiredCibilFiled;
	}


	public void setRequiredCibilFiled(boolean requiredCibilFiled) {
		this.requiredCibilFiled = requiredCibilFiled;
	}

	public double getProcessingCharge() {
		return processingCharge;
	}

	public void setProcessingCharge(double processingCharge) {
		this.processingCharge = processingCharge;
	}
}
