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.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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 = "personalLoan")
@ViewScoped


public class PersonalLoanBean implements Serializable 
{
	private static final long serialVersionUID = 1L;
	Date requestDate, chequeDate;
	public static List<String> list;
	ArrayList<SelectItem> planList, centerList;
	ArrayList<nomineeGuarantorBankInfo> nGList; // RR 15/7
	DataBaseMethodRahul dbr = new DataBaseMethodRahul();
	ArrayList<UserInfo> docList, appBankDetList;
	boolean showAuto, show, showField, renderDoc = false, skip, disDsa, reqMudraFin, renAutoLoanNo, renManualLoanNo;
	String shareHolderNo, guarantor1, guarantor2, loanNo, plan_no, reason, selectedScheme, rd_fdNo, emiType = "flat",
			center;
	double loanAmount, interst, duration, emiPayment, extraAmt, fileCharge, insuranceFee, processingCharge;
	int frequency, discount;
	String[] idProof;
	UserInfo selectedUser, guarantorUser1, guarantoruser2;
	String appChqNo, appAccNo, appBankName, appBankBranch, g1ChqNo, g1AccNo, g1BankName, g1BankBranch, g2ChqNo, g2AccNo,
			g2BankName, g2BankBranch, emiMode = "both";
	ArrayList<SelectItem> dsaList;
	String dsaCode;
	DsaListInfo dsa_info;
	double commission = 0;
	DataBaseMethods obj = new DataBaseMethods();
	DbYashwant dby = new DbYashwant();
	ArrayList<LoanInfo> allLoanList;
	ArrayList<String> memberGuarantorLoanDetailList;
	String companyName, nomChqNo, nomAccNo, nomBankName, nomBankBranch, nomBankIfsc, appBankIfsc, g1BankIfsc,
			g2BankIfsc;
	int branchId = 0;
	ArrayList<SelectItem> bankList, bankNameList;
	String paymentMode = "Cash", chequeNo, bankBranch, bankName, submittedBankName, label, description, userType;
	boolean showCheque, showFields, showMode, rateren;
	int rating;
	int advanceTerm;
	double stamp, advanceEMI, totalAdvanceEMIAmount;
	DataBaseMethodsRaviK dbrk =new DataBaseMethodsRaviK();
	
	

	public PersonalLoanBean() {
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		userType = (String) ss.getAttribute("type");
		UserInfo selected = (UserInfo) ss.getAttribute("selectedDataForHeaderBean");
		companyName = selected.getFirm_name();

		if (!companyName.equalsIgnoreCase("SUNLOG CREDITS PRIVATE LIMITED")) {
			showAuto = true;
		}
        
		Connection conn = DataBaseConnection.JAVAConnection();
		dsaList = obj.allDsaList(branchId, "Loan", conn);
		String userId = obj.userId();
		String empDataStatus = obj.checkSMessageApiDetailFromTable("employee_wise_data", "", conn);
		if (obj.userType().equals("employee") && empDataStatus.equalsIgnoreCase("active")) {
			dsaCode = obj.dsaCodeByEmpUserId(userId, conn);
			disDsa = true;
		}
		bankNameList = obj.bankNameSelectItemList(conn);
		bankList = new DataBaseIncomeExpense().allBankList(conn);
		centerList = obj.allcenter(branchId, "all", conn);
		
		try
		{
			conn.close();
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}
        
		loanNo = obj.personalLoanNo(branchId);

	}
    
	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 shareHolderDetails() 
	{
	    
		

		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		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;
				}
		
		
		appBankDetList = new ArrayList<>();

		appBankDetList = dbr.shareHolderAppBankDetails(shareHolderNo, branchId, appBankDetList);

		for (UserInfo ff : appBankDetList) {

			appChqNo = ff.getChequeNo();
			appAccNo = ff.getAccountNo();
			appBankName = ff.getBank_name();
			appBankBranch = ff.getBranch();
			appBankIfsc = ff.getBankIfsc();

		}

		applicantPersonalloanDetail();
		show = true;
		memberGuarantorLoanDetailList = obj.memberGuarantorLoanDetailListMethod(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"));
			rating = dby.checkRating(ll.getLoanNo());

			if (rating != 0) {

				rateren = true;

			}

			if (!userType.equalsIgnoreCase("masterAdmin")) {

				if (rating <= 3 && rating != 0) {
					show = false;

					FacesContext.getCurrentInstance().addMessage(null,
							new FacesMessage("Previous Loan rating is low! Only Master Admin can add this loan."));

				}

			}

		}

		selectedUser = obj.userInfoByShareHolderNo(shareHolderNo, conn);
		if (selectedUser != null)

		{

			{

				{

					loanNo = obj.personalLoanNo(branchId);
					requestDate = new Date();
					planList = obj.allPlans(branchId, "Loan");

					if (loanNo.equalsIgnoreCase("")) {
						renManualLoanNo = true;
						renAutoLoanNo = false;
					} else {
						renManualLoanNo = false;
						renAutoLoanNo = true;
					}

					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")
				|| hh.getName().equalsIgnoreCase("SUNLOG CREDITS PRIVATE LIMITED")) {
			reqMudraFin = true;
			emiType = "reducing";
		} else

		{
			reqMudraFin = false;
		}

		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void applicantPersonalloanDetail() {

		nGList = new ArrayList<>();

		if (shareHolderNo.contains("/")) {
			shareHolderNo = shareHolderNo.substring(0, shareHolderNo.indexOf("/"));
		}

		nGList = dbr.applicantPersonalloanDetailByShareHolderNo("personalloan", shareHolderNo, nGList, branchId);

		for (nomineeGuarantorBankInfo nn : nGList) {

			nomChqNo = nn.getNom_chq_no();
			nomAccNo = nn.getNom_acc_no();
			nomBankName = nn.getNom_bank_name();
			nomBankBranch = nn.getNom_bank_branch();
			nomBankIfsc = nn.getNom_bank_ifsc();
			g1ChqNo = nn.getG1_chq_no();
			g1AccNo = nn.getG1_acc_no();
			g1BankName = nn.getG1_bank_name();
			g1BankBranch = nn.getG1_bank_branch();
			g1BankIfsc = nn.getG1_bank_ifsc();
			g2ChqNo = nn.getG2_chq_no();
			g2AccNo = nn.getG2_acc_no();
			g2BankName = nn.getG2_bank_name();
			g2BankBranch = nn.getG2_bank_branch();
			g2BankIfsc = nn.getG2_bank_ifsc();

		}

	}

	public void checkPlan() {
//		interst=obj.interestByPlanNo(plan_no);

		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 = ((loanAmount * cf.getFileChargePlan()) / 100);
			insuranceFee = ((loanAmount * cf.getInsuranceFeePlan()) / 100);
		}

	}

	public void checkScheme() {
		if (!selectedScheme.equals("")) {
			showField = true;
		} else {
			showField = false;
		}
	}

	public void checkFileInsPer() {
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		Connection conn = DataBaseConnection.JAVAConnection();
		fileCharge = (loanAmount * obj.fileChargeAndInsFeeFromPlanTable(branchId, "file_charge_plan", plan_no, conn))
				/ 100;
		insuranceFee = (loanAmount
				* obj.fileChargeAndInsFeeFromPlanTable(branchId, "insurance_fee_plan", plan_no, conn)) / 100;
		processingCharge = (loanAmount
				* obj.fileChargeAndInsFeeFromPlanTable(branchId, "processing_charge_plan", plan_no, conn)) / 100;

		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void calculateEMI() {
		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);
			}
		}
		
		calculateAdvanceEMIAMount();
	}

	public List<String> completeFirstGuarantorText(String name) {
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int 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()");
			g1BankName = guarantorUser1.getBank_name();
			g1BankBranch = guarantorUser1.getBranch();
			g1BankIfsc = guarantorUser1.getBankIfsc();
			g1AccNo = guarantorUser1.getBank_accountNo();
			g1ChqNo = guarantorUser1.getG1C();
			System.out.println("g1chqNo :" + g1ChqNo);
		} 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(false);
		int 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("/"));
		guarantorUser1 = obj.userInfoByShareHolderNo(g2, conn);
		if (guarantorUser1 != null) {
			RequestContext.getCurrentInstance().execute("PF('detailDialog').show()");
			g2BankName = guarantorUser1.getBank_name();
			g2BankBranch = guarantorUser1.getBranch();
			g2BankIfsc = guarantorUser1.getBankIfsc();
			g2AccNo = guarantorUser1.getBank_accountNo();
			g2ChqNo = guarantorUser1.getG1C();
			System.out.println("g2chqNo :" + g2ChqNo);
		} 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("/"));
		guarantorUser1 = obj.userInfoByShareHolderNo(g2, 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("Second Guarantor User Not Valid"));
			guarantor2 = "";
		}

		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String addRequestLoan() throws ParseException {

		String ll = loanNo;
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		Connection conn = DataBaseConnection.JAVAConnection();

		// For Static Trial Period
		int flag = 1;
		Date dd = new Date();
		String string = "31/12/2026";
		DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
		Date date = format.parse(string);
		if (dd.after(date)) {
			flag = 0;
		} else if (duration <= 0) {
			flag = 99;
		} else if (loanAmount <= 0) {
			flag = 98;
		} else if (selectedUser.getOffice_date().after(requestDate)) {
			flag = 97;
		}

		else if (obj.personalLoanNoDuplicacy(loanNo, conn) == true) {
			flag = 96;
		}

		boolean chk = obj.checkLastEntrySettingInDb(branchId, "Personal Loan", conn);
		if (chk == true) {
			String lastDepositNo = obj.lastShareLoanDepositNo("Personal Loan");
			Date lastDate = obj.lastShareLoanDepositNoDate(lastDepositNo, "Personal 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));
				}
			}
		}

		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(loanAmount<=200000)
// 		    {
			commission = 0;
			if (renAutoLoanNo == true) 
			{
				loanNo = obj.personalLoanNo(branchId);
			}

			loanNo = obj.personalLoanNo(branchId);
			int i = obj.addLoanRequest(branchId, shareHolderNo, guarantor1, guarantor2, ll, 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, nomChqNo, nomAccNo, nomBankName, nomBankBranch, nomBankIfsc, 
					   				   appBankIfsc, g1BankIfsc, g2BankIfsc, processingCharge, stamp, advanceTerm, 
					   				   totalAdvanceEMIAmount);

				if (i >= 1) 
				{
					FacesContext fc = FacesContext.getCurrentInstance();
					fc.addMessage(null, new FacesMessage("Loan Request Submit Succesfully"));
					
					if (paymentMode.equalsIgnoreCase("cash")) 
					{
						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 By " + paymentMode));
							}
						} 
						else 
						{
							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 
						{
							insertInsuranceFeeInIncomeTable(conn, "pending");
							fc.addMessage(null,
									new FacesMessage("Insurance Fee " + insuranceFee + " 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 By " + paymentMode));
							}
						} 
						else
						{
							insertProcessingFeeInIncomeTable(conn, "pending");
							fc.addMessage(null, new FacesMessage("Processing Charge " + processingCharge + " Rs. Add For Pay Later."));
						}
						
						String sfStatus = obj.checkSettingFromMasterSettingNewTable("Stamp Fee", conn);
						
						if (sfStatus.equalsIgnoreCase("loan_request"))
						{
							insertStampFeeInIncomeTable(conn, "active");
							if (Double.valueOf(stamp) > 0)
							{
								obj.increaseCompanyCapitalAmount(branchId, Double.valueOf(stamp), conn);
								fc.addMessage(null, new FacesMessage("Stamp Fee " + stamp
																   + " Rs. Add Sucessfully By " + paymentMode));
							}
						}
						else
						{
							if (Double.valueOf(stamp) > 0)
							{
								insertStampFeeInIncomeTable(conn, "pending");
								fc.addMessage(null, new FacesMessage("Stamp Fee " + stamp + " 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));
						}
						
						if (Double.valueOf(processingCharge) > 0) 
						{
							insertProcessingFeeInIncomeTable(conn, "active");
							fc.addMessage(null, new FacesMessage("Please Appprove Processing Charge Payment Rs. " + processingCharge++));
						}
					}

				try 
				{
					conn.close();
				}
				catch (Exception e) 
				{
					e.printStackTrace();
				}
				selectedUser = guarantorUser1 = guarantoruser2 = null;
				emiPayment = loanAmount = interst = duration = frequency = discount = 0;
				fileCharge = insuranceFee = 0;
				idProof = null;
				show = false;
				guarantor1 = guarantor2 = shareHolderNo = reason = "";

				return "mainDashBoard.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. "));
// 			   }
			} 
			else if (flag == 99) 
			{
				FacesContext fc = FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Please Select Valid No. of Installments Terms."));
			}
			else if (flag == 98) 
			{
				FacesContext fc = FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Please Enter Valid Loan Amount."));
			} 
			else if (flag == 97) 
			{
				FacesContext fc = FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage(
						"Loan Request Date can't be Before Member Registration Date: " + selectedUser.getStrOffcDate()));
			} 
			else if (flag == 96) 
			{
				FacesContext fc = FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Loan No Can't Duplicate, Please Enter Valid Loan No. "));
			} 
			else
			{
				FacesContext fc = FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Some Error Occured!!!"));
			}
	
			return "";
		}

	private void insertFileChargeInIncomeTable(Connection conn, String entryStatus) {
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int 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(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, "Personal Loan", voucherNo, "", 0, entryStatus,
					"");
		}
	}

	private void insertInsuranceFeeInIncomeTable(Connection conn, String entryStatus) {
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int 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(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, "Personal Loan", voucherNo, "", 0,
					entryStatus, "");
		}
	}

	private void insertProcessingFeeInIncomeTable(Connection conn, String entryStatus) {

		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int 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(insuranceFee>0)
		{
			String voucherNo = obj.generateVoucherNo(branchId, "income_table", conn);
			new DataBaseIncomeExpense().addIncome(branchId, requestDate, "Other_Cr", paymentMode,
					String.valueOf(processingCharge), chequeNo, bankBranch, bankName, chequeDate,
					"Processing Charge Receive", "Processing Charge", 0, submittedBankName, "0", 0, loanNo,
					"Personal Loan", voucherNo, "", 0, entryStatus, "");
		}

	}
	
	
	
	private void insertStampFeeInIncomeTable(Connection conn, String entryStatus) 
	{
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		
		if (paymentMode.equalsIgnoreCase("cash")) 
		{
			submittedBankName = "N/A";
		}
		
		String voucherNo = obj.generateVoucherNo(branchId, "income_table", conn);
		new DataBaseIncomeExpense().addIncome(branchId, requestDate, "Other_Cr", paymentMode, String.valueOf(stamp), 
											  chequeNo, bankBranch, bankName, chequeDate, "Stamp Fee Receive", 
											  "Stamp Fee", 0, submittedBankName, "0", 0, loanNo, "Personal Loan", 
											  voucherNo, "", 0, entryStatus, "");
	}
	
	
	
	public void calculateAdvanceEMIAMount()
	{
		totalAdvanceEMIAmount = emiPayment * advanceTerm;
	}
	
	
	
	public List<Integer> getAdvanceEmiTerms()
	{
	    List<Integer> list = new ArrayList<>();

	    int maxValue = (int) (duration >= 20 ? 20 : duration / 2);

	    for(int i = 1; i <= maxValue; i++)
	    {
	        list.add(i);
	    }

	    return list;
	}
	
	

	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 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 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 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(false);
		int 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(false);
		int 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 double getFileCharge() {
		return fileCharge;
	}

	public void setFileCharge(double fileCharge) {
		this.fileCharge = fileCharge;
	}

	public double getInsuranceFee() {
		return insuranceFee;
	}

	public void setInsuranceFee(double insuranceFee) {
		this.insuranceFee = insuranceFee;
	}

	public boolean isDisDsa() {
		return disDsa;
	}

	public void setDisDsa(boolean disDsa) {
		this.disDsa = disDsa;
	}

	public ArrayList<LoanInfo> getAllLoanList() {
		return allLoanList;
	}

	public void setAllLoanList(ArrayList<LoanInfo> allLoanList) {
		this.allLoanList = allLoanList;
	}

	public ArrayList<String> getMemberGuarantorLoanDetailList() {
		return memberGuarantorLoanDetailList;
	}

	public void setMemberGuarantorLoanDetailList(ArrayList<String> memberGuarantorLoanDetailList) {
		this.memberGuarantorLoanDetailList = memberGuarantorLoanDetailList;
	}

	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 String getNomChqNo() {
		return nomChqNo;
	}

	public void setNomChqNo(String nomChqNo) {
		this.nomChqNo = nomChqNo;
	}

	public String getNomAccNo() {
		return nomAccNo;
	}

	public void setNomAccNo(String nomAccNo) {
		this.nomAccNo = nomAccNo;
	}

	public String getNomBankName() {
		return nomBankName;
	}

	public void setNomBankName(String nomBankName) {
		this.nomBankName = nomBankName;
	}

	public String getNomBankBranch() {
		return nomBankBranch;
	}

	public void setNomBankBranch(String nomBankBranch) {
		this.nomBankBranch = nomBankBranch;
	}

	public String getNomBankIfsc() {
		return nomBankIfsc;
	}

	public void setNomBankIfsc(String nomBankIfsc) {
		this.nomBankIfsc = nomBankIfsc;
	}

	public String getAppBankIfsc() {
		return appBankIfsc;
	}

	public void setAppBankIfsc(String appBankIfsc) {
		this.appBankIfsc = appBankIfsc;
	}

	public String getG1BankIfsc() {
		return g1BankIfsc;
	}

	public void setG1BankIfsc(String g1BankIfsc) {
		this.g1BankIfsc = g1BankIfsc;
	}

	public String getG2BankIfsc() {
		return g2BankIfsc;
	}

	public void setG2BankIfsc(String g2BankIfsc) {
		this.g2BankIfsc = g2BankIfsc;
	}

	public double getProcessingCharge() {
		return processingCharge;
	}

	public void setProcessingCharge(double processingCharge) {
		this.processingCharge = processingCharge;
	}

	public boolean isShowAuto() {
		return showAuto;
	}

	public void setShowAuto(boolean showAuto) {
		this.showAuto = showAuto;
	}

	public boolean isRateren() {
		return rateren;
	}

	public void setRateren(boolean rateren) {
		this.rateren = rateren;
	}

	public String getUserType() {
		return userType;
	}

	public void setUserType(String userType) {
		this.userType = userType;
	}

	public int getRating() {
		return rating;
	}

	public void setRating(int rating) {
		this.rating = rating;
	}

	public double getStamp() {
		return stamp;
	}

	public void setStamp(double stamp) {
		this.stamp = stamp;
	}

	public double getAdvanceEMI() {
		return advanceEMI;
	}

	public void setAdvanceEMI(double advanceEMI) {
		this.advanceEMI = advanceEMI;
	}

	public double getTotalAdvanceEMIAmount() {
		return totalAdvanceEMIAmount;
	}

	public void setTotalAdvanceEMIAmount(double totalAdvanceEMIAmount) {
		this.totalAdvanceEMIAmount = totalAdvanceEMIAmount;
	}

	public int getAdvanceTerm() {
		return advanceTerm;
	}

	public void setAdvanceTerm(int advanceTerm) {
		this.advanceTerm = advanceTerm;
	}

}
