package main_package;

import group_head_package.DataBaseIncomeExpense;
import other_package.DataBaseMethodsOther;
import other_package.ReportInfo;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

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;

@ViewScoped
@ManagedBean(name="loanCloser")

public class LoanCloserBean implements Serializable
{	
	String loanNo, loanType, printDt ,companyName;
	String loanAmount;
	ArrayList<LoanInfo> loanEMIList;
	LoanInfo loan_info,selectedLoan;
	ArrayList<SelectItem> bankList, loanTypeList;
	UserInfo user_info;
	List<String> nameList;
	double totalPenaltyDue, totalPenaltyPaid, totalIntrest,afterTodayTotalInterest, totalEmi, totalInterestRemainLocal,totalChqChrgRemainLocal,totalPrincipalRemainLocal,totalPrincipal, totalDue, totalPaid, totalRemaining, totalIntrestRemain, totalPrincipalRemain, amount,grossTotal, 
	totalPenaltyRemain, totalChqChargeRemain, discount, foreClosureInterest, foreClosureTotalRemaining;
	double totalChqCharge, paidChqcharge,totalPenaltyRemainLocal, savingAmount,tilldateInterest,totalForCloser, advanceInterest;
	boolean show, showDsaField,renderTableField, chkLoanSettlement=false,renderPayMode=true;
	boolean value, value1, value2,showTransfer, showTransferSelect=true, ecsDdNo;
	String chequeNo, bankName, paymentMode="Cash",transfer="No",submittedBankName, payType, label, receipt_no, voucherNo, dsaName,rdNumber;
	Date chequeDate, paidDate=new Date();
	
	double storeRDAmount;
	boolean deductRDAmount=false;
	boolean showRdDetailsOnLoanCloser=false;
	double rdInstallmentAmount,paidInstallments;

	private Double foreCloseChargeinper = 0.0;   // percentage
	private Double foreclosureCharges; 
	double totalInterestAmountRemaining;
	String interestType = "date";
	boolean showInterestType = false;
	
	double totalChqCharge1, totalChqCharge2;
	Boolean longOverdueClosure = false;
	
	double calculatedIntAmtAfterTenureTillDate = 0.0;
	double disIntAmtAfterTenureTillDate, calculatedIntAmtAfterTenureTillDateLocal;

	DataBaseMethodsHemant dbmt= new DataBaseMethodsHemant();
	DataBaseMethodTaheer dbt = new DataBaseMethodTaheer();
	DataBaseMethodsRaviK dbrk = new DataBaseMethodsRaviK();
	
	boolean bothMode, renCashAmount, renUPIAmount, disCashAmount, disUPIAmount, disPayMode;
	double gst, gstAmount, cashAmount, upiAmount, chargeAmount;
	double afterTenureInterest;
	
	private enum EditSource {
	    AMOUNT, PERCENT
	}
    
	private EditSource lastEdited;

	
	boolean disableForeclosureCharges;

	int MyId,branchId,rdvalue,period;


	double sA=0.0, finalAmount;
	double discountPenalty, discountChequeBounce, discountIntrest, commission, loanSettlementAmount;
	DsaListInfo commissionInfo;
	ArrayList<ReportInfo> dailyPayList;
	DataBaseMethods obj=new DataBaseMethods();
	DataBaseMethodRahul dbr = new DataBaseMethodRahul();
	DecimalFormat dc=new DecimalFormat("##.##");
	String rating,remark;
	
	SimpleDateFormat sf=new SimpleDateFormat("dd/MM/yyyy");
	HeaderBean hb = new HeaderBean();
	
	
	
	public LoanCloserBean() throws ParseException 
	{	
		HeaderBean hb= new HeaderBean(); 
		Connection con=DataBaseConnection.JAVAConnection();
		bankList=new DataBaseIncomeExpense().allBankList(con);
		receipt_no=String.valueOf(obj.loanPayReceiptNo());
//		showRdDetailsOnLoanCloser=new DataBaseMethodsNaman().getShowDepositStatus(con);
//		System.out.println("showRdDetailsOnLoanCloser"+showRdDetailsOnLoanCloser);
		
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		companyName  = (String) ss.getAttribute("companyName");
		String type = (String) ss.getAttribute("type");
		
		if ("SUDERSHANA FINANCE".equalsIgnoreCase(companyName)) 
		{
			if ("masterAdmin".equalsIgnoreCase("admin")) 
			{
				disableForeclosureCharges = false;
			}
			else
			{
				disableForeclosureCharges = true;
			}
		}
		else 
		{
			disableForeclosureCharges = false;
		}
		
		String pageName=(String) ss.getAttribute("pageName");
		if(pageName!=null && pageName.equals("payLoanEMI.xhtml"))
		{
			loanNo=((LoanInfo) ss.getAttribute("selectedLoan")).getLoanNo();
			System.out.println("loan closure loan no is:"+loanNo);
			loanType=((LoanInfo) ss.getAttribute("selectedLoan")).getLoanType();
			
			loanAmount=((LoanInfo) ss.getAttribute("selectedLoan")).getLoanType();
			System.out.println("loan amount in loan closure is:"+loanAmount);
			
			if(loanType.equals("Personal Loan"))
			{
				loanType="personalloan";
			}
			else if(loanType.equals("Vehicle Loan"))
			{
				loanType="vechicleloan";
			}
			else if(loanType.equals("Property Loan"))
			{
				loanType="propertyloan";
			}
			else if(loanType.equals("Group Loan"))
			{
				loanType="grouploan";
			}
			else if(loanType.equals("Secure Loan"))
			{
				loanType="secure_loan";
			}
			else if(loanType.equals("Business Loan"))
			{
				loanType="business_loan";
			}
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				loanNo=((LoanInfo) ss.getAttribute("selectedLoan")).getSubLoanNo();
			}
			
			boolean loanClosed = dbt.checkLoanClosed(loanNo, loanType);
			System.out.println("loan closed : " + loanClosed);
			if (!loanClosed) 
			{
				userInfo();
			}
			else 
			{
				loanNo = "";
			}
			
			ss.removeAttribute("selectedLoan");
			ss.removeAttribute("pageName");
		}
		
		try {
			con.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		if (hb != null && hb.getCompanyName() != null && hb.getCompanyName().equalsIgnoreCase("SUDERSHANA FINANCE")) 
		{
			foreCloseChargeinper = 5.0;
		}
		onPercentEntered();
	}
	
	public List<String> completeLoanNo(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		if(loanType!=null)
		{
			nameList=new DataBaseAutoCompAndDuplicate().showLoanNoByLoanTypeActiveLoan(branchId,name,loanType);
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null,new FacesMessage("Please Select Loan Type First"));
		}
		return nameList;
	} 
	
	public double rdvalueTillDate() {

	    DataBaseMethodsNaman dbn = new DataBaseMethodsNaman();

	    try (Connection conn = DataBaseConnection.JAVAConnection()) {

	        String shareHolderNo = user_info.getShareHolderNo();
	        String rdNumber = dbn.rdFdNoByShareHolderNo(shareHolderNo, conn);

	        if (rdNumber == null || rdNumber.isEmpty()) {
	            return 0.0;
	        }
	        
	        this.rdNumber=rdNumber;

	        double rdInterestRate = dbn.getInterestRateOfRD(shareHolderNo);
	        double rdInstallmentAmount = dbn.getRdInstallmentAmount(rdNumber, conn);
	        int paidInstallments = (int) dbn.getPaidRDInstallmentCount(rdNumber, conn);
	        this.rdInstallmentAmount=rdInstallmentAmount;
	        this.paidInstallments=paidInstallments;
	        LocalDate rdStartDate = dbn.getRDStartDate(rdNumber, conn);
	        if (rdStartDate == null) {
	            return 0.0;
	        }

	        Period period = Period.between(rdStartDate, LocalDate.now());
	        int monthsCompleted = Math.max(0,
	                period.getYears() * 12 + period.getMonths());
	        
	        this.period=monthsCompleted;

	        int monthsUsed = Math.min(monthsCompleted, paidInstallments);
	        if (monthsUsed <= 0) {
	            return 0.0;
	        }
            
	        double interest =
	                rdInstallmentAmount *
	                (monthsUsed * (monthsUsed + 1) / 2.0) *
	                (rdInterestRate / (12 * 100));

	        System.out.println(
	        	    "RD Value Till Date " + ((rdInstallmentAmount * monthsUsed) + interest)
	        	);
	        
	        return (rdInstallmentAmount * monthsUsed) + interest;

	    } catch (Exception e) {
	        // Replace with logger in production
	        e.printStackTrace();
	        return 0.0;
	    }
	}
	
	
	
	public void userInfo() throws ParseException 
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		
		/*HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		pageName=(String) ss1.getAttribute("pageName");
		if(pageName!=null && pageName.equals("particularLoan"))
		{
			// System.out.println("if");
			loanNo=((LoanInfo) ss1.getAttribute("selectedLoan")).getLoanNo();
		}
		else
		{
			// System.out.println("else");
			loanNo=loanNo.substring(0,loanNo.indexOf("/"));
		}*/
		
		show=true;
		if(loanNo.contains("/"))
		{
			loanNo=loanNo.substring(0,loanNo.indexOf("/"));
		}
		
		user_info=obj.userInfoByLoanNoLoanType(loanNo,loanType, conn);
		loan_info=obj.loanInfoByLoanNoLoanType(loanNo,loanType, conn);
	//	System.out.println("ShareHolderFor RD maturity :"+user_info.getShareHolderNo());
	//	rdvalue = (int) rdvalueTillDate();
	//	System.out.println("naman maturity NNN "+rdvalue);
		System.out.println("ShareHolderFor RD maturity :"+user_info.getShareHolderNo());
		// rdvalue = (int) rdvalueTillDate();
		//amount=loan_info.getInstallAmount();
		//// System.out.println(loan_info.getEmiMode());
		if(loan_info.getDsacode()==null || loan_info.getDsacode().equals(""))
		{
			//System.out.println("ifffffffffffff");
			commission=0;
			showDsaField=false;
		}
		else
		{
			dsaName=obj.dsaNameById(loan_info.getDsacode(),conn); 
			showDsaField=true;
			calculateCommission(conn);
			
		}
		
		if(loan_info.getEmiMode().equals("both"))
		{
			renderTableField=true;
		}
		
		loanEMIList=obj.loanInstallment(loanType,loanNo, conn);
	    
		foreClosureInterest=foreClosureTotalRemaining=0;
		for(int l=0;l<loanEMIList.size();l++)
		{
			Date dt=new Date();
			if(loanEMIList.get(l).getStatus().equals("Paid"))
			{
				loanEMIList.get(l).setColorStatus("paid");
			//	System.out.println("value of the forClosureInterest :::::::"+foreClosureInterest);
			}
			else
			{
				if(loanEMIList.get(l).getInstallDate().before(dt))
				{
					loanEMIList.get(l).setColorStatus("due");
					foreClosureInterest+=Double.parseDouble(dc.format(Double.parseDouble(loanEMIList.get(l).getInterestAmount())));
				    
				}
				else
				{
					loanEMIList.get(l).setColorStatus("upcoming");
				}
			}
		}
		loanEMIList=obj.penaltyCalculationMethod(loanType, loanNo, loanEMIList, conn);
		
		double totPaid=obj.totalPaidPenaltyAndChequeBounceCharges(loanNo, "Penalty", conn);
		if(totPaid>0)
		{
			for(int i=0; i<loanEMIList.size(); i++)
			{
				if(totPaid>loanEMIList.get(i).getPenaltyDue())
				{
					loanEMIList.get(i).setPenaltyPaid(loanEMIList.get(i).getPenaltyDue());
				}
				else
				{
					loanEMIList.get(i).setPenaltyPaid(totPaid);
					break;
				}
				totPaid=totPaid-loanEMIList.get(i).getPenaltyDue();
			}
			
		}
	
		
		totalPenaltyDue=totalPenaltyPaid=totalIntrest=totalEmi=totalPrincipal=totalDue=totalPaid=totalIntrestRemain=totalPrincipalRemain=totalChqCharge=0;
		for(LoanInfo ll: loanEMIList)
		{   // System.out.println("value of the one day interest :"+totalInterestRemainLocal);
		  //  System.out.println("l");
			totalEmi+=ll.getInstallAmount();
			totalIntrest+=Double.parseDouble(ll.getInterestAmount());
			totalPrincipal+=Double.parseDouble(ll.getPrincipalAmount());
			totalPaid+=ll.getPaidAmount();
			totalDue+=ll.getDueAmount();
			totalPenaltyDue+=ll.getPenaltyDue();
			totalPenaltyPaid+=ll.getPenaltyPaid();
			
			/*if(ll.getStatus().equals("Due"))
			{
				totalIntrestRemain+=Double.parseDouble(ll.getInterestAmount());
				totalPrincipalRemain+=Double.parseDouble(ll.getPrincipalAmount());
			}*/
		}
		
		double totPrPaid=obj.totalPrincipalPaidByLoanNo(loanNo);
		double totIrPaid=obj.totalIntrestPaidByLoanNo(loanNo);
		System.out.println("total interest for loan : " + totalIntrest);
		System.out.println("totalInterestPaid in loanclosure is:"+totIrPaid);
		if(loan_info.getEmiMode().equals("interest"))
		{
			totalPrincipalRemain=Double.parseDouble(loan_info.getLoanAmount());
		}
		else
		{
			totalPrincipalRemain=Double.parseDouble(loan_info.getLoanAmount())-totPrPaid;
		}
		
		//totalPrincipalRemain=Double.parseDouble(loan_info.getLoanAmount())-totPrPaid;
		totalIntrestRemain=totalIntrest-totIrPaid;
		System.out.println("total int befre:"+totalIntrestRemain);
		System.out.println("totaol interst reamn is:"+totalIntrestRemain);
		System.out.println("loan info discount is:"+loan_info.getDiscount());
		totalIntrestRemain=totalIntrestRemain-loan_info.getDiscount();  // Discount adjust in Loan Interest Amount
		System.out.println("total int after dis:"+totalIntrestRemain);
		// System.out.println(totalPrincipal+"====="+totPrPaid);
		// System.out.println(totalIntrest+"====="+totIrPaid);
		
		
	    //totalChqCharge=obj.calculatePenaltyAndChequeBounceCharges(loanNo, "Cheque Bounce",loanType, conn); 
		totalChqCharge1=dbrk.chequeBouncechargesforDueEmi(loanNo, loanType, conn, loanEMIList);
	    totalChqCharge2=obj.calculatePenaltyAndChequeBounceCharges(loanNo, "Cheque Bounce",loanType, conn);
	    totalChqCharge = totalChqCharge1+totalChqCharge2;
		paidChqcharge=obj.totalPaidPenaltyAndChequeBounceCharges(loanNo, "Cheque Bounce", conn);
		totalChqChargeRemain=Double.parseDouble(dc.format(totalChqCharge-paidChqcharge));
		
		if (totalChqChargeRemain < 0) 
		{
			totalChqChargeRemain = 0;
		}
		
		totalEmi=Double.parseDouble(dc.format(totalEmi));
		//net total Interest in loan closure.
		totalIntrest=Math.round(totalIntrest);
		//net total Interest in loan closure.
		System.out.println("totalINterest in loan closre"+totalIntrest);
		
		totalPrincipal=Math.round(totalPrincipal);
		totalPaid=Double.parseDouble(dc.format(totalPaid));
		totalDue=Double.parseDouble(dc.format(totalDue));
		totalPenaltyDue=Double.parseDouble(dc.format(totalPenaltyDue));
		totalPenaltyPaid=Double.parseDouble(dc.format(totalPenaltyPaid));
		totalPenaltyRemain=Double.parseDouble(dc.format(totalPenaltyDue-totalPenaltyPaid));
		totalIntrestRemain=Double.parseDouble(dc.format(totalIntrestRemain));
		System.out.println("totalIntrest reamin is "+totalIntrestRemain);
		
		// till closure date total interest aage ka aaj tak ka chodkar.
		//afterTodayTotalInterest= totalIntrest-totlIrPaid;
		
		if(totalIntrestRemain<0)
		{
			totalIntrestRemain=0;
		}
		
		totalPrincipalRemain=Double.parseDouble(dc.format(totalPrincipalRemain));
		if(totalPrincipalRemain<0)
		{
			totalPrincipalRemain=0;
		}
		if (totalPrincipalRemain == 0) 
		{ 
			totalChqChargeRemain = 0;
			totalPenaltyRemain = 0;
		}
		
	  String lastPaidEmiNo= dbt.checkLastPaidEmiNoByLoanNo(loanNo);
	  double lastEmiNo = 0;
	   
	  if (lastPaidEmiNo != null) 
	  {
		  lastEmiNo= Double.parseDouble(lastPaidEmiNo);
	  }   
		
	  String loanTerms = loan_info.getLoanTerm();
	   
	  double loanTermsDouble = Double.parseDouble(loanTerms);

	  System.out.println("last emi no : " + lastEmiNo + " last term : " + loanTermsDouble);
	  
	  if(loanTermsDouble==lastEmiNo)
	  {
		  System.out.println("lastPaid emi no "+lastEmiNo);
			
		  System.out.println(" loan term of loan"+loanTermsDouble);
		  totalChqChargeRemain = 0;
		  totalPenaltyRemain = 0;
		  tilldateInterest=0;
	  }
		
	  
		
	  totalRemaining = Double.parseDouble(dc.format(
		        totalIntrestRemain
		        + totalPrincipalRemain
		        + totalChqChargeRemain
		        + totalPenaltyRemain
		        + savingAmount
		));

		
		amount=totalRemaining;
		amount = Math.ceil(amount);
		System.out.println("amount isL:"+amount);
		
		foreClosureInterest=Double.parseDouble(dc.format(foreClosureInterest));
		foreClosureTotalRemaining=totalPrincipalRemain+totalPenaltyRemain+totalChqChargeRemain+foreClosureInterest;//
		foreClosureTotalRemaining=Double.parseDouble(dc.format(foreClosureTotalRemaining));
		
		printDt=new SimpleDateFormat("dd/MM/yyyy").format(paidDate);
		
		try 
		{
			conn.close();
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}



//		Set<String> skipCompanies = Set.of(
//			    "FINAZONE MICRO SERVICES FOUNDATION",
//			    "JANTAMANNA DREAM CARE FOUNDATION"
//			);
//
//			if (!skipCompanies.contains(companyName.toUpperCase())) {
//			    checkDetailRR();
//			}
             {
			System.out.println("ffffff :"+totalIntrestRemain);
			tilldateInterest=totalIntrestRemain;
			System.out.println("till date interest is :"+tilldateInterest);
		   
		}

//           
//
//			if ( !"FINAZONE MICRO SERVICES FOUNDATION".equals(companyName.toUpperCase()) || !"JANTAMANNA DREAM CARE FOUNDATION".equals(companyName.toUpperCase())) {
//			    checkDetailRR();
//			} else {
//			    System.out.println("ffffff :" + totalIntrestRemain);
//			    tilldateInterest = totalIntrestRemain;
//			}
//
//		

		if ("FINAZONE MICRO SERVICES FOUNDATION".equalsIgnoreCase(companyName)
			    || "JANTAMANNA DREAM CARE FOUNDATION".equalsIgnoreCase(companyName)
			    || "MAHAVIR KRIPA MICRO FINANCE".equalsIgnoreCase(companyName)
			    || "ROYAL MICROFINANCE".equalsIgnoreCase(companyName)
				|| "GKFC MICROSERVICES FOUNDATION".equalsIgnoreCase(companyName))
		{
			    
			    // Skip checkDetailRR
			    System.out.println("ffffff :" + totalIntrestRemain);
			    tilldateInterest = totalIntrestRemain;
			    totalForCloser=Math.round(Double.parseDouble(dc.format(tilldateInterest+totalPrincipalRemain+totalChqChargeRemain+totalPenaltyRemain+savingAmount)));
			    
			    totalRemaining = Double.parseDouble(dc.format(
			            totalIntrestRemain
			            + totalPrincipalRemain
			            + totalChqChargeRemain
			            + totalPenaltyRemain
			            + savingAmount
			    ));    

			} else {
			    // Run the method for all other companies
			    checkDetailRR();
			}
		
		
		if("SHREEHANUMAT MICROCARE FOUNDATION".equalsIgnoreCase(companyName))
		{
			System.out.println("negative : " + tilldateInterest);
			    totalForCloser=Math.round(Double.parseDouble(dc.format(tilldateInterest+totalPrincipalRemain+totalChqChargeRemain+totalPenaltyRemain+savingAmount)));
			    tilldateInterest = totalIntrestRemain;
			    totalRemaining = Double.parseDouble(dc.format(
			            totalIntrestRemain
			            + totalPrincipalRemain
			            + totalChqChargeRemain
			            + totalPenaltyRemain
			            + savingAmount
			    ));
			    
			    totalRemaining= Math.ceil(totalRemaining); 
		}
        
		double tia = 0;
		
		for (LoanInfo li : loanEMIList)
		{
			if (li.getStatus().equalsIgnoreCase("due")) 
			{
				tia += Double.parseDouble(li.getInterestAmount());
			}
		}
		System.out.println("total inrest remain is tia :+"+tia);
		
		String tiar = dc.format(tia);
		totalInterestAmountRemaining = Double.parseDouble(tiar);
		System.out.println("tilldateInterest is: " + tilldateInterest);
		
		if(tilldateInterest > 0)
		{
			totalInterestAmountRemaining = totalInterestAmountRemaining - tilldateInterest;
			System.out.println("total amount interest remainning" + totalInterestAmountRemaining);
		}		
		else 
		{
			advanceInterest = - tilldateInterest;
			tilldateInterest = 0;
		}

		if (interestType.equalsIgnoreCase("end")) 
		{
			System.out.println("working");
			tilldateInterest = totalInterestAmountRemaining + tilldateInterest;
			totalRemaining = totalRemaining + totalInterestAmountRemaining;
			totalInterestAmountRemaining = 0;
		}
	}
	
	
	
	public void checkDetailRR() throws ParseException 
	{
		LoanInfo lastPaidEmi = null;
		LoanInfo nextEmi = null;
		LoanInfo lastDueEmi=null;
		Double lateInterest = 0.0;
		boolean Duecase = false;

		for (int i = 0; i < loanEMIList.size(); i++) 
		{	
			LoanInfo current = loanEMIList.get(i); 
			String dateString = current.getStrInstlmntDate();
			
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
			Date Ldate = sdf.parse(dateString);
			Date todayDate = new Date(); 
			boolean lastPaidGet = false;
			
			if (current.getStatus().equalsIgnoreCase("Due")) 
			{
			    lastPaidGet = true;		     
			}
		
			if(loanEMIList.size()-1 == i) 
			{	
				nextEmi = current;	
			}
            
		    if (current.getStatus().equalsIgnoreCase("Paid")) 
		    {
		        lastPaidEmi = current;
		    } 
		    
		    else if(Ldate.before(todayDate)&& lastPaidGet==true)
		    {
		    	
		    	lateInterest += current.getInterest(); 
		    	 lastDueEmi = current ; 
		    	 Duecase = true;
		    } 
		   
		    
		    else if (Ldate.after(todayDate)&& lastPaidGet==true) {
		    	// First unpaid EMI after the last paid one
		    	nextEmi = current;
		    	lastPaidGet=false;
		    	
		    	Connection conn = DataBaseConnection.JAVAConnection();
		    	String emiPaidDate = dbt.EMIDateByLoanNo(conn, loanNo);
		    	
		    	if (emiPaidDate.equalsIgnoreCase("")) 
		    	{
		    		lateInterest += current.getInterest(); 
		    		lastDueEmi = current;
					Duecase = true;
				}
		    	
		    	try 
		    	{
		    		conn.close();
				} 
		    	catch (Exception e) 
		    	{
					e.printStackTrace();
				}
		    	
		    	break;
		    }
		    
		 //   System.out.println("Total Due Late Interest :"+lateInterest);
	
	}
       
//		
//		// Print both rows
//		if (lastPaidEmi != null) {
//		    System.out.println("🔹 Last Paid EMI (Row " + lastPaidEmi.getEmiNo() + ")");
//		    System.out.println("Date     : " + lastPaidEmi.getStrInstlmntDate());
//		    System.out.println("Amount   : ₹" + lastPaidEmi.getEmiAmount());
//		    System.out.println("Interest : ₹" + lastPaidEmi.getInterest());
//		    System.out.println("Principal: ₹" + lastPaidEmi.getPrincipal());
//		}
//      
//		if (nextEmi != null) {
//		    System.out.println("\n🔸 Next EMI (Upcoming - Row " + nextEmi.getEmiNo() + ")");
//		    System.out.println("Date     : " + nextEmi.getStrInstlmntDate());
//		    System.out.println("Amount   : ₹" + nextEmi.getEmiAmount());
//		    System.out.println("Interest : ₹" + nextEmi.getInterest());
//		    System.out.println("Principal: ₹" + nextEmi.getPrincipal());
//		}
//		
//		if (lastDueEmi != null) {
//		    System.out.println("\n🔸 Last Due EMI (Last Due - Row " + lastDueEmi.getEmiNo() + ")");
//		    System.out.println("Date     : " + lastDueEmi.getStrInstlmntDate());
//		    System.out.println("Amount   : ₹" + lastDueEmi.getEmiAmount());
//		    System.out.println("Interest : ₹" + lastDueEmi.getInterest());
//		    System.out.println("Principal: ₹" + lastDueEmi.getPrincipal());
//		}
//		
  
		 DataBaseMethods dr = new DataBaseMethods();
		
		Date date=null;
		double tinterest = 0.0;
		int tDay =0;
		String dateString ;
		double interestBtwEmi =0.0;
	
//			if(Duecase==false)
//			{
//			 dateString = lastPaidEmi.getStrInstlmntDate();
//			}else {
//		     dateString = lastDueEmi.getStrInstlmntDate();
//			}
//			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
//			 date = sdf.parse(dateString);
//			 
		if (Duecase == false)
		{
		    if (lastPaidEmi != null) {
		        dateString = lastPaidEmi.getStrInstlmntDate();
		    } else {
		        System.out.println("lastPaidEmi is NULL");
		        return;
		    }
		}
		else
		{
		    if (lastDueEmi != null) {
		        dateString = lastDueEmi.getStrInstlmntDate();
		    } else {
		        System.out.println("lastDueEmi is NULL");
		        return;
		    }
		}

		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		date = sdf.parse(dateString);
			// System.out.println("Date calcualtion from :"+date);
			
			 String[] parts = dateString.split("/");
             
			 int day = Integer.parseInt(parts[0]);
			 int month = Integer.parseInt(parts[1]);
			 int year = Integer.parseInt(parts[2]);
			  
			 tDay = dr.daysInMonth(month, year);  
			 
		  
			 if( loan_info.getFrequency().equalsIgnoreCase("2 week") ) {
				
				System.out.println("frequency came :"+loan_info.frequency);
				tDay=14;
				
			}else if(loan_info.getFrequency().equalsIgnoreCase("4 week")) {
				
				System.out.println("frequency came :"+loan_info.frequency);
				tDay=28;
				
			}
            else if(loan_info.getFrequency().equalsIgnoreCase("1 Week")) {
				
				System.out.println("frequency came :"+loan_info.frequency);
				tDay=7;				
			}
						 
		//System.out.println("Total Days in month :"+tDay);

		Date today = new Date();  // current date
		
		if (!longOverdueClosure) 
		{
			if("SHREEHANUMAT MICROCARE FOUNDATION".equalsIgnoreCase(companyName))
			{
				today = paidDate; // current date
			}
		}
		else 
		{
			Calendar cal = Calendar.getInstance();

			today = loan_info.getEmiDate();

			cal.setTime(today);

			int terms = loan_info.getTerms();

			cal.add(Calendar.MONTH, terms - 1);

			today = cal.getTime();
		}
		
		System.out.println("today date is :" + today);
		
		long diffInMillies = today.getTime() - date.getTime();
		int numberOfDays = (int) TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
		System.out.println("Number of days: " + numberOfDays);
		
		if(Duecase==false)
		{
		// interestBtwEmi = lastPaidEmi.getInterest() -  nextEmi.getInterest(); 6-8
			interestBtwEmi =  nextEmi.getInterest();
		}else {
	  //   interestBtwEmi = lastDueEmi.getInterest() -  nextEmi.getInterest();  6-8
			interestBtwEmi =  nextEmi.getInterest();
        }
		
		 System.out.println("Total interset between :"+interestBtwEmi);
		 tinterest = Math.round(interestBtwEmi / tDay) ;
		 System.out.println("One Day Interest :"+tinterest);
		 System.out.println("n o d :"+numberOfDays);
		 if(Duecase==false) 
		 { 	 
			 tilldateInterest = Math.round(numberOfDays*tinterest);
			 System.out.println("duecase tilldateInteset:"+tilldateInterest);
		 } 
		 else
		 {
			 	 sA = Math.round(numberOfDays*tinterest);
			 	 tilldateInterest =Math.round(sA + lateInterest);
			 	 System.out.println("tilldateInteset:"+tilldateInterest);
			 	 System.out.println("sA :"+numberOfDays);		 
		 } 
		 
		 if(totalPrincipalRemain==0)
		 {
			 tilldateInterest=0;
		 }
		 String lastPaidEmiNo= dbmt.checkLastPaidEmiNoByLoanNo(loanNo);
		    
		 double lastEmiNo = 0;
		   
		  if (lastPaidEmiNo != null) 
		   {
			   lastEmiNo= Double.parseDouble(lastPaidEmiNo);
		   }
		   
		
	  String loanTerms = loan_info.getLoanTerm();
	 
	  double loanTermsDouble = Double.parseDouble(loanTerms);

	  
	  if(loanTermsDouble==(lastEmiNo))
	  {
		  System.out.println("lastPaid emi no "+lastEmiNo);
			
		  System.out.println(" loan term of loan"+loanTermsDouble);
		  totalChqChargeRemain = 0;
		  totalPenaltyRemain = 0;
		  tilldateInterest=0;
	  }
	  
	  if (tilldateInterest < 0)
	  {
		  tilldateInterest = 0;
	  }
      
	  if (tilldateInterest < 0) 
	  {
		  tilldateInterest = 0;
	  }
	  
       System.out.println("Till Date intereset neg :"+tilldateInterest);
		
		totalForCloser=Math.round(Double.parseDouble(dc.format(tilldateInterest+totalPrincipalRemain+totalChqChargeRemain+totalPenaltyRemain+savingAmount)));
		totalRemaining=Double.parseDouble(dc.format(tilldateInterest+totalPrincipalRemain+totalChqChargeRemain+totalPenaltyRemain+savingAmount + calculatedIntAmtAfterTenureTillDate));
        
        
        if("DELIGHTS MICRO CREDIT INDIA FOUNDATION".equalsIgnoreCase(companyName)) {
        	
        	
        }

        storeRDAmount=totalRemaining;
       
        
        if (deductRDAmount) {
            totalRemaining -= rdvalue;
            grossTotal = totalRemaining + rdvalue;
        } else {
            grossTotal = totalRemaining;
        }
        
        
        
       
	//	 System.out.println("totalRemaininggggg :"+totalRemaining);
	//	 System.out.println("amountttttt :"+amount);
		
		//		System.out.println("sA = " + sA);
//		System.out.println("totalPrincipalRemain = " + totalPrincipalRemain);
//		System.out.println("totalChqChargeRemain = " + totalChqChargeRemain);
//		System.out.println("totalPenaltyRemain = " + totalPenaltyRemain);
//		System.out.println("savingAmount = " + savingAmount);

		// Full expression
		System.out.println("Final Result = " + (tilldateInterest+ totalPrincipalRemain + totalChqChargeRemain + totalPenaltyRemain + savingAmount));
         
//		if ("FINAZONE MICRO SERVICES FOUNDATION".equalsIgnoreCase(companyName)
//			    || "JANTAMANNA DREAM CARE FOUNDATION".equalsIgnoreCase(companyName)
//			    || "MAHAVIR KRIPA MICRO FINANCE".equalsIgnoreCase(companyName)
//			    || "ROYAL MICROFINANCE".equalsIgnoreCase(companyName)) {
//			    
//			    // Skip checkDetailRR
//			    System.out.println("ffffff :" + totalIntrestRemain);
//			    tilldateInterest = totalIntrestRemain;
//			    
//			    
//
//			}
//		if(lastPaidEmi.equals(null)&&lastPaidEmi!=) {
//			tilldateInterest=0.0;
//		}
	  
	}
	
	public void upAmount() throws ParseException {
		amount = totalRemaining;
		
		if (hb != null && hb.getCompanyName() != null
	            && hb.getCompanyName().equalsIgnoreCase("SUDERSHANA FINANCE")) {

	        foreCloseChargeinper = 5.0; // 🔥 force 5%
	    }
		checkPaid();
	//	System.out.println("val of am :"+amount);
	}
	
	
	public void printDailyPay()
	{
		dailyPayList= new ArrayList<>();
		if(loanType.equalsIgnoreCase("grouploan"))
		{
			dailyPayList= new DataBaseMethodsOther().dailyloanReport(loan_info.getSubLoanNo());
		}
		else
		{
			dailyPayList= new DataBaseMethodsOther().dailyloanReport(loan_info.getLoanNo());
		}
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		ss.setAttribute("penaltyAmount", totalPenaltyDue);
		ss.setAttribute("penaltyPaid", totalPenaltyPaid);
		ss.setAttribute("penaltyDue", totalPenaltyRemain);
		ss.setAttribute("totalChqCharge", totalChqCharge);
		ss.setAttribute("paidChqCharge", totalChqCharge);
		ss.setAttribute("dailyPayList", dailyPayList);
		ss.setAttribute("selectedVal",loan_info);
		ss.setAttribute("operationVal", "loan");
		ss.setAttribute("reportClosingBalance", totalDue);
		ss.setAttribute("disOnLoanClose",0.0);
		ss.setAttribute("printOverallEmi",loanEMIList );               //RR 14/5 
		ss.setAttribute("totalEmi", totalEmi);                         //RR 14/5
		ss.setAttribute("totalIntrest",totalIntrest);                  // RR 14/5
		ss.setAttribute("totalPrincipal", totalPrincipal);             // RR 14/5
		ss.setAttribute("totalPaid", totalPaid);                       // RR 14/5
		RequestContext.getCurrentInstance().execute("window.open('printPerticularDatePayment.xhtml')");
		
	}
	
	public void checkLoanSettlementMethod()
	{
		totalChqChargeRemain=0;
		totalPenaltyRemain=0;
		paymentMode="Transfer";
		renderPayMode=false;
		if(chkLoanSettlement==true)
		{
			RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_INFO, "Loan Settlement Message", "if You Select Loan Settlement, "
					+ "this means total amount booked as a Expense With the Ledger of Loan settlement Amount and Loan Settlement Entry can't Reverse, "
					+ "if you have any query Please contact to Admininstrator. Thank You!!!"));
		}
		else
		{
			renderPayMode=true;
			paymentMode="";
		}
		RequestContext.getCurrentInstance().update("form3:pnl111");
	}
	
	public void calculateCommission(Connection conn)
	{
		if(loan_info.getPlanNo()==null || loan_info.equals(""))
		{
			System.out.println("1");
			commission=0;
		}
		else
		{
			commissionInfo=obj.checkPlanCommissionDetail(loan_info.getPlanNo(), conn);
			if(commissionInfo==null || commissionInfo.getStatusNullCheck().equals("0"))
			{
				System.out.println("5");
				commission=0;
			}
			else
			{
				double val=0;
				val=Double.parseDouble(loan_info.getLoanAmount());
			   if(commissionInfo.getCommissionBase().equalsIgnoreCase("closure"))
			   {
				   if(commissionInfo.getCommission_type().equalsIgnoreCase("percent"))
				   {
					   commission=(val/100)*commissionInfo.getCommission_value();
				   }
				   else
				   {
					   commission=commissionInfo.getCommission_value();
				   }
			   }
			   else
			   {
				   commission=0;
			   }
			   commission=Double.parseDouble(dc.format(commission));
			}
		}
	}
	
	
	
//	public void onAmountEntered() throws ParseException 
//	{
////		lastEdited = EditSource.AMOUNT;
////		checkPaid();
//				 
//		amount = totalRemaining - discount+ foreclosureCharges;
//		amount = Math.round(amount);
//		System.out.println("amount is"+amount);
//
//		foreCloseChargeinper =  (foreclosureCharges * 100) / totalPrincipalRemain;
//		System.out.println("forclousr charge is:"+foreCloseChargeinper);
//		System.out.println("amount");
//		System.out.println("fc: " + foreclosureCharges);
//		System.out.println("amt: " + finalAmount);
//	}
	
	
	
	public void onAmountEntered() throws ParseException {
		calculateTotalDiscount();
	    double fc = (foreclosureCharges == null)
	            ? 0.0
	            : foreclosureCharges;

	    if (longOverdueClosure)
	    {
	        amount = totalRemaining
	               + calculatedIntAmtAfterTenureTillDate
	               - discount
	               + fc;
	    }
	    else
	    {
	        amount = totalRemaining
	               - discount
	               + fc;
	    }

	    amount = Math.round(amount);

	}
	
	
	
//	public void onPercentEntered() throws ParseException 
//	{
//
////		lastEdited = EditSource.PERCENT;
////	    checkPaid();
//		
//		System.out.println("percent");
//		
//		foreclosureCharges = (totalPrincipalRemain * foreCloseChargeinper) / 100; 
//		amount = totalRemaining - discount + foreclosureCharges;		
//		amount = Math.round(amount);
//		System.out.println("fc: " + foreclosureCharges);
//		System.out.println("amt: " + finalAmount);
//	}

	
		
	public void onPercentEntered() throws ParseException 
	{
//		lastEdited = EditSource.PERCENT;
//	    checkPaid();
		
		System.out.println("percent");
		calculateTotalDiscount();
		foreclosureCharges = (totalPrincipalRemain * foreCloseChargeinper) / 100; 
		amount = totalRemaining - discount + foreclosureCharges;		
		amount = Math.round(amount);
		System.out.println("fc: " + foreclosureCharges);
		System.out.println("amt: " + finalAmount);
	}
	
	
	
	public void checkPaid() throws ParseException
	{  


		userInfo();
		discount=0;
		
		// normalize
//		 if (foreCloseChargeinper == null) foreCloseChargeinper = 0.0;
//		    if (foreclosureCharges == null) foreclosureCharges = 0.0;
//
//
//		    if (lastEdited == EditSource.AMOUNT) {
//
//		        // amount → percent
//		        foreCloseChargeinper =
//		            (foreclosureCharges * 100) / totalPrincipalRemain;
//
//		    } else if (lastEdited == EditSource.PERCENT) {
//
//		        // percent → amount
//		        foreclosureCharges =
//		            (totalPrincipalRemain * foreCloseChargeinper) / 100;
//		    }

		// single source of truth: percent
//		foreclosureCharges =
//		    (totalPrincipalRemain * foreCloseChargeinper) / 100;

//		System.out.println(foreclosureCharges+" "+foreCloseChargeinper);
		totalChqChrgRemainLocal=totalChqChargeRemain;
		totalInterestRemainLocal=totalIntrestRemain;
		totalPenaltyRemainLocal=totalPenaltyRemain;
		calculatedIntAmtAfterTenureTillDateLocal = calculatedIntAmtAfterTenureTillDate;
		System.out.println(""+totalIntrestRemain+"total cheq charge remain"+totalChqChargeRemain+"total penalty remain is:"+totalPenaltyRemain);
		double maxDis=totalIntrestRemain+totalChqChargeRemain+totalPenaltyRemain+calculatedIntAmtAfterTenureTillDate;
		
		System.out.println("discount interest is:"+discountIntrest);
		discount=discountChequeBounce+discountIntrest+discountPenalty;
		System.out.println("total discount is:"+discount);
		System.out.println("max discount is: "+maxDis);
	
		if(discount<=maxDis)
		{	
			
			if(totalChqChargeRemain>=discountChequeBounce)
			{
				totalChqChargeRemain-=discountChequeBounce;
			}
			else
			{
				discountChequeBounce=totalChqChargeRemain;
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Cheque Bounce Discount Can't be greater than Rs. "+discountChequeBounce));
			}
			
			if(tilldateInterest>=discountIntrest)
			{
				totalIntrestRemain-=discountIntrest;
			}
			else
			{ 
				System.out.println("RRRR c :"+totalIntrestRemain + "disc C: "+discountIntrest);
				discountIntrest=totalIntrestRemain;
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Intrest Discount Can't be greater than Rs. "+tilldateInterest));
			}
			
			if(totalPenaltyRemain>=discountPenalty)
			{
				totalPenaltyRemain-=discountPenalty;
			}
			
			else
			{
				discountPenalty=totalPenaltyRemain;
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Penalty Discount Can't be greater than Rs. "+discountPenalty));
			}
			
			// disIntAmtAfterTenureTillDate
			if(calculatedIntAmtAfterTenureTillDate>=disIntAmtAfterTenureTillDate)
			{   
				//calculatedIntAmtAfterTenureTillDate-=disIntAmtAfterTenureTillDate;
			}
			
			else
			{
				disIntAmtAfterTenureTillDate=calculatedIntAmtAfterTenureTillDate;
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Calculated Interest Discount Can't be greater than Rs. "+calculatedIntAmtAfterTenureTillDate));
			}
			 calculateTotalDiscount();
			//discount=discountChequeBounce+discountIntrest+discountPenalty+disIntAmtAfterTenureTillDate;
			amount=totalRemaining-discount;
			System.out.println("amount is after discount"+amount);
			amount+=foreclosureCharges;
			System.out.println("amount after adding foreclosure chargeer"+amount);
			
			amount = Math.round(amount);
		}
		else
		{
			discount=discountChequeBounce=discountIntrest=discountPenalty=disIntAmtAfterTenureTillDate=0;
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Discount Can't be greater than Rs. "+maxDis));
		}
		amount=Double.parseDouble(dc.format(amount));
		
		amount = Math.round(amount);
		
		rdvalueTillDate();
		
		onAmountEntered();
	}

	

	public void checkTransferMode()
	{
		if(transfer.equals("Yes"))
		{
			showTransfer=true;
		}
		else
		{
			showTransfer=false;
		}
	}
	
	public void forPaymentMode()
	{
		renderPayMode=true;
		//// System.out.println(paymentMode);
		if (paymentMode.equals("0")) 
		{
			value1 = value2 = false;
		}
		else if (paymentMode.equalsIgnoreCase("Cash") || paymentMode.equalsIgnoreCase("transfer")) 
		{
			value1 = true;
			value2 = false;
			showTransfer=ecsDdNo=false;
			showTransferSelect=true;
			transfer=bankName=chequeNo="";
			chequeDate=null;
		}
		else
		{
			label=paymentMode;
			value2 = true;
			value1 =ecsDdNo= false;
			showTransferSelect=false;
			showTransfer=true;
			bankName=chequeNo="";
			chequeDate=null;
		}
	}
	
	public void deductRD()
	{
		if (deductRDAmount==true) 
		{
			totalRemaining = storeRDAmount-rdvalue;
		}
		else 
		{
			totalRemaining = storeRDAmount;
			amount=storeRDAmount;
		}
	}
	
	
	
	public void submit() throws IOException
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		FacesContext fc=FacesContext.getCurrentInstance();
		int flag=1;
		String savingAccountNo="";
		if(paymentMode.equalsIgnoreCase("Transfer")  && chkLoanSettlement==false)
		{
			UserInfo savingDetail=obj.savingAccountDetailByShareHolderNo(user_info.getShareHolderNo());
			savingAccountNo=savingDetail.getAccountNo();
			if(savingDetail!=null && savingDetail.getAmount()<amount)
			{	
				flag=96;
			}
			
			Timestamp curr=new Timestamp(paidDate.getTime());
			curr.setHours(0);curr.setMinutes(0);curr.setSeconds(0);curr.setNanos(0);
			if(savingDetail!=null && savingDetail.getEntryDate().after(curr))
			{
				flag=95;
			}
		}
		
		
		
		if(flag==1)
		{
			
			
			String addloancloser=obj.addLoanCloser(receipt_no, totalPenaltyRemainLocal, totalInterestRemainLocal, totalChqChrgRemainLocal,totalRemaining,discount,amount,
					paidDate,paymentMode,transfer,loanNo,discountIntrest,discountPenalty,discountChequeBounce,chequeNo,chequeDate,totalPrincipalRemain,dsaName,branchId,foreclosureCharges,rating,remark,calculatedIntAmtAfterTenureTillDate,disIntAmtAfterTenureTillDate);
			Connection conn=DataBaseConnection.JAVAConnection();
			if(paymentMode.equalsIgnoreCase("cash") || paymentMode.equalsIgnoreCase("Transfer"))
			{
				submittedBankName="N/A";
			}
			
			
			int n = 0;
			double principalIntrest = amount
					- (totalChqChargeRemain + totalPenaltyRemain + savingAmount + foreclosureCharges);

			if (bothMode) {
			//	String voucherNo = obj.generateVoucherNo(branchId, "gst_table", conn);
				
				receipt_no = String.valueOf(obj.loanPayReceiptNo());
				n = obj.payLoanEMI(branchId, loanNo, loanType, upiAmount, paidDate, paymentMode, chequeNo, chequeDate,
						bankName, 0, receipt_no, submittedBankName, "No", discountIntrest, -1, loan_info.getDsacode(),
						"", "");

				double cash = cashAmount - chargeAmount;
				if (cash > 0) {
					receipt_no = String.valueOf(obj.loanPayReceiptNo());
					n = obj.payLoanEMI(branchId, loanNo, loanType, Math.round(cash), paidDate, "Cash", "", null, "", 0,
							receipt_no, "N/A", "No", discountIntrest, -1, loan_info.getDsacode(), "", "");
				}
			} else {
				//String voucherNo = obj.generateVoucherNo(branchId, "gst_table", conn);
				
				receipt_no = String.valueOf(obj.loanPayReceiptNo());
				n = obj.payLoanEMI(branchId, loanNo, loanType, principalIntrest, paidDate, paymentMode, chequeNo,
						chequeDate, bankName, 0, receipt_no, submittedBankName, "No", discountIntrest, -1,
						loan_info.getDsacode(), "", "");
			}			MyId=n;
			if (n >= 1) 
			{   
				addSavingAmount(conn);
				//totalIntrestRemain=totalIntrestRemain-discount;
				if(commission>0)
				{   
					System.out.println("commmison: "+commission);
					String emiNo="all";
					 boolean checkEntry=obj.checkDuplicacyInDsaCommissionTable(loan_info.getLoanNo(),emiNo);
					  if(checkEntry==false)
					  {
							String dsaName=obj.dsaNameById(loan_info.getDsacode(),conn);
							int j=obj.insertDataInDsaCommissionTable(branchId,loan_info.getLoanType(), loan_info.getLoanNo(), loan_info.getDsacode(), commission, paidDate, emiNo);
							if(j>0)
							{
								fc=FacesContext.getCurrentInstance();
								fc.addMessage(null, new FacesMessage("Commission Auto Credited to "+loan_info.getDsacode()+" - "+dsaName+" Rs.:- "+commission));
							}
					  }
				}
				if(paymentMode.equalsIgnoreCase("Cash") && transfer.equalsIgnoreCase("No"))
				{
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Payment Done SuccessFully..."));
					
					if ("SHREEHANUMAT MICROCARE FOUNDATION".equalsIgnoreCase(companyName)) 
					{
						obj.updateInterestAmountInLoanPayReceipt(branchId,n, tilldateInterest - discountIntrest);
					}
					else
					{
						obj.updateInterestAmountInLoanPayReceipt(branchId,n, totalIntrestRemain);
					}
					
					obj.decreaseSharedCompanyAmount(branchId,totalPrincipalRemain);
					RequestContext.getCurrentInstance().execute("window.open('loanPayReceipt.xhtml')");
				}
				else if(paymentMode.equalsIgnoreCase("Cash") && transfer.equalsIgnoreCase("Yes"))
				{
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Payment Done SuccessFully..."));
					
					if ("SHREEHANUMAT MICROCARE FOUNDATION".equalsIgnoreCase(companyName)) 
					{
						obj.updateInterestAmountInLoanPayReceiptWithoutIncreasingCompanyCapital(n, tilldateInterest - discountIntrest);
					}
					else
					{
						obj.updateInterestAmountInLoanPayReceiptWithoutIncreasingCompanyCapital(n, totalIntrestRemain);
					}
					
					obj.increaseBankBalance(submittedBankName, amount,conn);
					RequestContext.getCurrentInstance().execute("window.open('loanPayReceipt.xhtml')");
				}
				else if(paymentMode.equalsIgnoreCase("Transfer") && chkLoanSettlement==false)
				{
					String svRemark="Loan Closer "+loanNo+" EMI Deposit";
					int	m = obj.userWithdrwal(branchId,savingAccountNo, String.valueOf(principalIntrest), paidDate,paymentMode, chequeNo, chequeDate, bankName, "","approved",svRemark,"");
					if (m >= 1) 
					{
						double preAmount=obj.acconuntHolderAmountByAccountNo(savingAccountNo);
						Double newAmount=preAmount-principalIntrest;
						obj.updateSavingAmountByAccountNo(savingAccountNo,newAmount);
						
						if ("SHREEHANUMAT MICROCARE FOUNDATION".equalsIgnoreCase(companyName)) 
						{
							obj.updateInterestAmountInLoanPayReceipt(branchId, n, tilldateInterest - discountIntrest);
						}
						else
						{
							obj.updateInterestAmountInLoanPayReceipt(branchId,n, totalIntrestRemain);
						}
					}
				}	
				else
				{
					if ("SHREEHANUMAT MICROCARE FOUNDATION".equalsIgnoreCase(companyName)) 
					{
						obj.updateInterestAmountInLoanPayReceiptWithoutIncreasingCompanyCapital(n, tilldateInterest - discountIntrest);
					}
					else
					{
						obj.updateInterestAmountInLoanPayReceiptWithoutIncreasingCompanyCapital(n, totalIntrestRemain);
					}
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Payment Done SuccessFully... Please Approve Your Payment"));
				}
				
				detailsForLoanPrint();
				obj.updateStatusOfLoan(loanType,loanNo);
				
				discount=0;
				
				if(totalPenaltyRemain>0 && chkLoanSettlement==false)
				{
					totalPenaltyRemain=Double.parseDouble(dc.format(totalPenaltyRemain));
					voucherNo=obj.generateVoucherNo(branchId,"income_table",conn);
					int i=new DataBaseIncomeExpense().addIncome(branchId,paidDate,"Other_Cr",paymentMode,String.valueOf(totalPenaltyRemain) ,chequeNo,"",bankName,chequeDate,
							"Penalty Income","Receive Penalty",0,submittedBankName, "0", discountPenalty,loanNo, loanType,voucherNo,"",0,"active",""); 
					if(i>=1)
					{
					    //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Income Added Successfully"));
					    if(paymentMode.equalsIgnoreCase("Cash") && transfer.equals("No"))
						{
							obj.increaseCompanyCapitalAmount(branchId,totalPenaltyRemain,conn);
						}
						else if(paymentMode.equalsIgnoreCase("Cash") && transfer.equals("Yes"))
						{
							obj.increaseBankBalance(submittedBankName, totalPenaltyRemain,conn);
						}
					    
						else if(paymentMode.equalsIgnoreCase("Transfer") && chkLoanSettlement==false)
						{
							String svRemark=loanNo+" Penalty Deposit";
							int	m = obj.userWithdrwal(branchId,savingAccountNo, String.valueOf(totalPenaltyRemain), paidDate,paymentMode, chequeNo, chequeDate, bankName, "","approved",svRemark,"");
							if (m >= 1) 
							{
								double preAmount=obj.acconuntHolderAmountByAccountNo(savingAccountNo);
								Double newAmount=preAmount-totalPenaltyRemain;
								obj.updateSavingAmountByAccountNo(savingAccountNo,newAmount);
							}
						}	
					}   
				
				}
				
				if(totalChqChargeRemain>0 && chkLoanSettlement==false)
				{
					voucherNo=obj.generateVoucherNo(branchId,"income_table",conn);
					int j=new DataBaseIncomeExpense().addIncome(branchId,paidDate,"Other_Cr",paymentMode,String.valueOf(totalChqChargeRemain) ,chequeNo,"",bankName,
							chequeDate,"Cheque Bounce Income","Receive Cheque Bounce Charges",0,submittedBankName, "0", discountChequeBounce,loanNo, loanType,voucherNo,"",0,"active",""); 
					if(j>=1)
					{
					    //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Income Added Successfully"));
					    if(paymentMode.equalsIgnoreCase("Cash") && transfer.equals("No"))
						{
							obj.increaseCompanyCapitalAmount(branchId,Double.valueOf(totalChqChargeRemain),conn);
						}
						else if(paymentMode.equalsIgnoreCase("Cash") && transfer.equals("Yes"))
						{
							obj.increaseBankBalance(submittedBankName, Double.valueOf(totalChqChargeRemain),conn);
						}
						else if(paymentMode.equalsIgnoreCase("Transfer") && chkLoanSettlement==false)
						{
							String svRemark=loanNo+" Bounce Charge Deposit";
							int	m = obj.userWithdrwal(branchId,savingAccountNo, String.valueOf(totalChqChargeRemain), paidDate,paymentMode, chequeNo, chequeDate, bankName, "","approved",svRemark,"");
							if (m >= 1) 
							{
								double preAmount=obj.acconuntHolderAmountByAccountNo(savingAccountNo);
								Double newAmount=preAmount-totalChqChargeRemain;
								obj.updateSavingAmountByAccountNo(savingAccountNo,newAmount);
							}
						}	
					}   
				}
				
				if(foreclosureCharges>0 && chkLoanSettlement==false)
				{
					voucherNo=obj.generateVoucherNo(branchId,"income_table",conn);
					int j=new DataBaseIncomeExpense().addIncome(branchId,paidDate,"Other_Cr",paymentMode,String.valueOf(foreclosureCharges) ,chequeNo,"",bankName,
							chequeDate,"Receive Loan Foreclosure Charges","Loan Foreclosure Charges",0,submittedBankName, "0", 
							discountChequeBounce,loanNo, loanType,voucherNo,"",0,"active",""); 
					if(j>=1)
					{
					    //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Income Added Successfully"));
					    if(paymentMode.equalsIgnoreCase("Cash") && transfer.equals("No"))
						{
							obj.increaseCompanyCapitalAmount(branchId,foreclosureCharges,conn);
						}
						else if(paymentMode.equalsIgnoreCase("Cash") && transfer.equals("Yes"))
						{
							obj.increaseBankBalance(submittedBankName, foreclosureCharges,conn);
						}
						else if(paymentMode.equalsIgnoreCase("Transfer") && chkLoanSettlement==false)
						{
							String svRemark=loanNo+" Foreclosure Charges";
							int	m = obj.userWithdrwal(branchId,savingAccountNo, String.valueOf(foreclosureCharges), paidDate,paymentMode, chequeNo, chequeDate, bankName, "","approved",svRemark,"");
							if (m >= 1) 
							{
								double preAmount=obj.acconuntHolderAmountByAccountNo(savingAccountNo);
								Double newAmount=preAmount-foreclosureCharges;
								obj.updateSavingAmountByAccountNo(savingAccountNo,newAmount);
							}
						}	
					}   
				}
				
				loanSettlementAmount=amount;
				if(chkLoanSettlement==true)
				{
					voucherNo=obj.generateVoucherNo(branchId,"expense_table",conn);
					int x=new DataBaseIncomeExpense().addExpense(branchId,paidDate,"Other_Dr",paymentMode,String.valueOf(loanSettlementAmount),chequeNo,"",submittedBankName,
							chequeDate,"Loan Settlement", "Loan Settlement","0", voucherNo, 0,"0",loanNo,loanType); 
				}
				
				value2= false;paymentMode=chequeNo=bankName="";
				amount=0;chequeNo=bankName="";chequeDate=null;show=false;
				try {
					conn.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
				FacesContext.getCurrentInstance().getExternalContext().redirect("loanCloser.xhtml");
			}
			else 
			{
				fc = FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
			}
		}
		else if(flag==96)
 		{
 			fc.addMessage(null, new FacesMessage("Saving Account No. "+savingAccountNo+" doesn't have sufficient Balance. "));
 		}
		else
		{
			fc.addMessage(null, new FacesMessage("Some Error Occured!!!"));
		}
		
	}
    
	
	public void addSavingAmount(Connection conn)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		if(savingAmount>0)
 		{
 			String accno=obj.savingAccountByShareHolderNo(user_info.getShareHolderNo());
 			String app_status="approved";
 			String detail=loanNo+" EMI Deposit";
 			int	n = obj.userDeposit(branchId,accno, String.valueOf(savingAmount), paidDate,"cash", "", null, "",app_status,"N/A",detail, "");
			if (n >= 1) 
			{
				double preAmount=obj.acconuntHolderAmountByAccountNo(accno);
				Double newAmount=preAmount+savingAmount;
				obj.updateSavingAmountByAccountNo(accno,newAmount);
				obj.increaseCompanyCapitalAmount(branchId,savingAmount,conn);
			}
 		}
	}
	public void detailsForLoanPrint()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		ss.setAttribute("shareHolderNo", user_info.getShareHolderNo());
		ss.setAttribute("loanNo",loanNo);
		ss.setAttribute("receipt_no",receipt_no);
		ss.setAttribute("installment_amount",amount);
		ss.setAttribute("loanType", loanType);
		ss.setAttribute("id",MyId);
		ss.setAttribute("receipt_date",new SimpleDateFormat("dd/MM/yyyy").format(paidDate));
		ss.setAttribute("instlmnt_no","Loan Closure");
	}
	
	
//	public void changePaidAmountByPaidDate() throws ParseException
//	{
//		try 
//		{
//			checkDetailRR();
//		} 
//		catch (ParseException e) 
//		{
//			e.printStackTrace();
//		}
//		upAmount();
//	}
	
	
	
	public void changePaidAmountByPaidDate() throws ParseException
	{
	    checkDetailRR();

	    if (longOverdueClosure == true)
	    {
	        prepareLongOverdueCalculation();
	    }
	    else
	    {
	        calculatedIntAmtAfterTenureTillDate = 0.0;
	        disIntAmtAfterTenureTillDate = 0.0;
	    }

	    calculateTotalDiscount();

	    amount = totalRemaining - discount;

	    if (longOverdueClosure == true)
	    {
	        amount += calculatedIntAmtAfterTenureTillDate;
	    }

	    amount += (foreclosureCharges == null
	            ? 0.0
	            : foreclosureCharges);

	    amount = Math.round(amount);
	}
	
	
	
	public void changeInterestAmount() throws Exception
	{
		System.out.println("noob");
		System.out.println(companyName);
		System.out.println(interestType);
		
		if (interestType.equalsIgnoreCase("date")) 
		{
			checkPaid();
		}
		else if (interestType.equalsIgnoreCase("end")) 
		{
			userInfo();
		}
	}
	
	
	
	
	public void calculateClosureByCheck() throws ParseException
	{
	    if (longOverdueClosure)
	    {
	        prepareLongOverdueCalculation();
	    }
	    else
	    {
	        calculatedIntAmtAfterTenureTillDate = 0.0;
	        disIntAmtAfterTenureTillDate = 0.0;
	    }

	    calculateTotalDiscount();

	    amount = totalRemaining;

	    if (longOverdueClosure)
	    {
	        amount += calculatedIntAmtAfterTenureTillDate;
	    }

	    amount -= discount;

	    if (foreclosureCharges != null)
	    {
	        amount += foreclosureCharges;
	    }

	    amount = Math.round(amount);

	    System.out.println("================================");
	    System.out.println("BASE TOTAL              : " + totalRemaining);
	    System.out.println("AFTER TENURE INTEREST   : " + calculatedIntAmtAfterTenureTillDate);
	    System.out.println("TOTAL DISCOUNT          : " + discount);
	    System.out.println("FORECLOSURE CHARGES     : " + foreclosureCharges);
	    System.out.println("FINAL AMOUNT            : " + amount);
	    System.out.println("================================");
	}
	
	
	
	private void calculateTotalDiscount()
	{
	    discount = discountChequeBounce
	             + discountIntrest
	             + discountPenalty;

	    if (longOverdueClosure)
	    {
	        discount += disIntAmtAfterTenureTillDate;
	    }
	    else
	    {
	        // Checkbox OFF hone par old long overdue discount ignore
	        disIntAmtAfterTenureTillDate = 0.0;
	    }
	}
	
	
	
	public void prepareLongOverdueCalculation() throws ParseException 
	{ 
	    if (loanEMIList == null || loanEMIList.isEmpty()) 
	    { 
	        System.out.println("EMI list is empty"); 
	        return; 
	    } 
	    
	    int loanTerm = (int) Double.parseDouble(loan_info.getLoanTerm());	  
	    LoanInfo lastTermEmi = null; 
	 
	    // Find last EMI according to loan term 
	    for (LoanInfo emi : loanEMIList) 
	    { 
	       if (emi.getSno() != 0 && emi.getSno() == loanTerm)
	        { System.out.println("Last Term EMI not found. EMI No = " + emi.getSno()); 
	            lastTermEmi = emi; 
	            break; 
	        } 
	    } 
	 
	    if (lastTermEmi == null) 
	    { 
	        System.out.println("Last Term EMI not found. EMI No = " + loanTerm); 
	        return; 
	    } 
	 
	    // Last EMI Date  
	    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); 
	 
	    Date lastEmiDate = sdf.parse(lastTermEmi.getStrInstlmntDate()); 
	 
	    //Selected date
	    if (paidDate == null) 
	    { 
	        System.out.println("Selected Date is null"); 
	        return; 
	    } 
	 
	    Date newDate = sdf.parse(sdf.format(paidDate)); 
	 
	    // Calculate Days between last emi and selected date
	     
	    long difference = newDate.getTime() - lastEmiDate.getTime(); 
	 
	    long numberOfDays =  TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS); 
	 
	    if (numberOfDays < 0) 
	    { 
	        numberOfDays = 0; 
	    } 
	 
	    double totalAmountRemaining =  totalRemaining; 
	    double roi = Double.parseDouble(loan_info.getLoanInterest());
	    double rateOfInterest = roi / 100;
	    
	     calculatedIntAmtAfterTenureTillDate = totalAmountRemaining * rateOfInterest * numberOfDays / 365;
	     
	 }
	
	
	public void paymentByCashAndUPI() {
		paymentMode = "UPI";
		if (bothMode) {
			if (paymentMode.equalsIgnoreCase("UPI")) {
				chargeAmount = totalPenaltyRemain + totalChqChargeRemain + foreclosureCharges + gstAmount;

				renCashAmount = true;
				renUPIAmount = true;
				disCashAmount = true;
				disUPIAmount = false;
				disPayMode = true;

				cashAmount = chargeAmount;
				cashAmount = Math.round(cashAmount);

				upiAmount = amount - cashAmount;
				upiAmount = Math.round(upiAmount);
			} else {
				renCashAmount = false;
				renUPIAmount = false;
				disCashAmount = true;
				disUPIAmount = true;
				disPayMode = false;
			}
		}

		forPaymentMode();
	}
	
	
	public void changeCashUPIAmount() {
		cashAmount = amount - upiAmount;

		if (cashAmount < chargeAmount) {
			cashAmount = chargeAmount;
			cashAmount = Math.round(cashAmount);

			upiAmount = amount - cashAmount;
			upiAmount = Math.round(upiAmount);
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage("Cash amount cannot be less than " + chargeAmount));
		}
	}
	
	
	
	public void printForclosureAmount()
	{
		if (longOverdueClosure)
		{
			afterTenureInterest = calculatedIntAmtAfterTenureTillDate;
		}
		else
		{
			afterTenureInterest = 0;
		}
		
		afterTenureInterest = Math.round(afterTenureInterest);
		
		totalForCloser = totalPrincipalRemain + tilldateInterest + totalPenaltyRemain + totalChqChargeRemain + afterTenureInterest;

		totalForCloser = Math.round(totalForCloser);
	}
	
	
	
	public String getLoanNo() {
		return loanNo;
	}

	public void setLoanNo(String loanNo) {
		this.loanNo = loanNo;
	}

	public String getLoanType() {
		return loanType;
	}

	public void setLoanType(String loanType) {
		this.loanType = loanType;
	}

	public ArrayList<LoanInfo> getLoanEMIList() {
		return loanEMIList;
	}

	public void setLoanEMIList(ArrayList<LoanInfo> loanEMIList) {
		this.loanEMIList = loanEMIList;
	}

	public LoanInfo getLoan_info() {
		return loan_info;
	}

	public void setLoan_info(LoanInfo loan_info) {
		this.loan_info = loan_info;
	}

	public LoanInfo getSelectedLoan() {
		return selectedLoan;
	}

	public void setSelectedLoan(LoanInfo selectedLoan) {
		this.selectedLoan = selectedLoan;
	}

	public ArrayList<SelectItem> getLoanTypeList() {
		return loanTypeList;
	}

	public void setLoanTypeList(ArrayList<SelectItem> loanTypeList) {
		this.loanTypeList = loanTypeList;
	}

	public UserInfo getUser_info() {
		return user_info;
	}

	public void setUser_info(UserInfo user_info) {
		this.user_info = user_info;
	}

	public List<String> getNameList() {
		return nameList;
	}

	public void setNameList(List<String> nameList) {
		this.nameList = nameList;
	}

	public double getTotalPenaltyDue() {
		return totalPenaltyDue;
	}

	public void setTotalPenaltyDue(double totalPenaltyDue) {
		this.totalPenaltyDue = totalPenaltyDue;
	}

	public String getDsaName() {
		return dsaName;
	}

	public void setDsaName(String dsaName) {
		this.dsaName = dsaName;
	}

	public double getCommission() {
		return commission;
	}

	public void setCommission(double commission) {
		this.commission = commission;
	}

	public double getTotalPenaltyPaid() {
		return totalPenaltyPaid;
	}

	public void setTotalPenaltyPaid(double totalPenaltyPaid) {
		this.totalPenaltyPaid = totalPenaltyPaid;
	}

	public double getTotalIntrest() {
		return totalIntrest;
	}

	public void setTotalIntrest(double totalIntrest) {
		this.totalIntrest = totalIntrest;
	}

	public double getTotalEmi() {
		return totalEmi;
	}

	public void setTotalEmi(double totalEmi) {
		this.totalEmi = totalEmi;
	}

	public double getTotalPrincipal() {
		return totalPrincipal;
	}

	public void setTotalPrincipal(double totalPrincipal) {
		this.totalPrincipal = totalPrincipal;
	}

	public double getTotalDue() {
		return totalDue;
	}

	public void setTotalDue(double totalDue) {
		this.totalDue = totalDue;
	}

	public double getTotalPaid() {
		return totalPaid;
	}

	public void setTotalPaid(double totalPaid) {
		this.totalPaid = totalPaid;
	}

	public double getTotalChqCharge() {
		return totalChqCharge;
	}

	public void setTotalChqCharge(double totalChqCharge) {
		this.totalChqCharge = totalChqCharge;
	}

	public double getPaidChqcharge() {
		return paidChqcharge;
	}

	public void setPaidChqcharge(double paidChqcharge) {
		this.paidChqcharge = paidChqcharge;
	}

	public boolean isShow() {
		return show;
	}

	public void setShow(boolean show) {
		this.show = show;
	}

	public double getTotalRemaining() {
		return totalRemaining;
	}

	public void setTotalRemaining(double totalRemaining) {
		this.totalRemaining = totalRemaining;
	}

	public double getTotalIntrestRemain() {
		return totalIntrestRemain;
	}

	public void setTotalIntrestRemain(double totalIntrestRemain) {
		this.totalIntrestRemain = totalIntrestRemain;
	}

	public double getTotalPrincipalRemain() {
		return totalPrincipalRemain;
	}

	public void setTotalPrincipalRemain(double totalPrincipalRemain) {
		this.totalPrincipalRemain = totalPrincipalRemain;
	}

	public double getTotalPenaltyRemain() {
		return totalPenaltyRemain;
	}

	public void setTotalPenaltyRemain(double totalPenaltyRemain) {
		this.totalPenaltyRemain = totalPenaltyRemain;
	}

	public double getTotalChqChargeRemain() {
		return totalChqChargeRemain;
	}

	public void setTotalChqChargeRemain(double totalChqChargeRemain) {
		this.totalChqChargeRemain = totalChqChargeRemain;
	}

	public ArrayList<SelectItem> getBankList() {
		return bankList;
	}

	public void setBankList(ArrayList<SelectItem> bankList) {
		this.bankList = bankList;
	}

	public boolean isValue() {
		return value;
	}

	public void setValue(boolean value) {
		this.value = value;
	}

	public boolean isValue1() {
		return value1;
	}

	public void setValue1(boolean value1) {
		this.value1 = value1;
	}

	public boolean isValue2() {
		return value2;
	}

	public void setValue2(boolean value2) {
		this.value2 = value2;
	}

	public boolean isShowTransfer() {
		return showTransfer;
	}

	public void setShowTransfer(boolean showTransfer) {
		this.showTransfer = showTransfer;
	}

	public boolean isShowTransferSelect() {
		return showTransferSelect;
	}

	public void setShowTransferSelect(boolean showTransferSelect) {
		this.showTransferSelect = showTransferSelect;
	}

	public boolean isEcsDdNo() {
		return ecsDdNo;
	}

	public void setEcsDdNo(boolean ecsDdNo) {
		this.ecsDdNo = ecsDdNo;
	}

	public String getChequeNo() {
		return chequeNo;
	}

	public void setChequeNo(String chequeNo) {
		this.chequeNo = chequeNo;
	}

	public String getBankName() {
		return bankName;
	}

	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	public String getPaymentMode() {
		return paymentMode;
	}

	public void setPaymentMode(String paymentMode) {
		this.paymentMode = paymentMode;
	}

	public String getTransfer() {
		return transfer;
	}

	public void setTransfer(String transfer) {
		this.transfer = transfer;
	}

	public String getSubmittedBankName() {
		return submittedBankName;
	}

	public void setSubmittedBankName(String submittedBankName) {
		this.submittedBankName = submittedBankName;
	}

	public String getPayType() {
		return payType;
	}

	public void setPayType(String payType) {
		this.payType = payType;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public Date getChequeDate() {
		return chequeDate;
	}

	public void setChequeDate(Date chequeDate) {
		this.chequeDate = chequeDate;
	}

	
	public Date getPaidDate() {
		return paidDate;
	}

	public void setPaidDate(Date paidDate) {
		this.paidDate = paidDate;
	}

	public String getReceipt_no() {
		return receipt_no;
	}

	public void setReceipt_no(String receipt_no) {
		this.receipt_no = receipt_no;
	}

	public double getAmount() {
		return amount;
	}

	public void setAmount(double amount) {
		this.amount = amount;
	}

	public double getDiscount() {
		return discount;
	}

	public void setDiscount(double discount) {
		this.discount = discount;
	}

	public String getVoucherNo() {
		return voucherNo;
	}

	public void setVoucherNo(String voucherNo) {
		this.voucherNo = voucherNo;
	}

	public int getMyId() {
		return MyId;
	}

	public void setMyId(int myId) {
		MyId = myId;
	}

	public double getDiscountPenalty() {
		return discountPenalty;
	}

	public void setDiscountPenalty(double discountPenalty) {
		this.discountPenalty = discountPenalty;
	}

	public double getDiscountChequeBounce() {
		return discountChequeBounce;
	}

	public void setDiscountChequeBounce(double discountChequeBounce) {
		this.discountChequeBounce = discountChequeBounce;
	}

	public double getDiscountIntrest() {
		return discountIntrest;
	}

	public void setDiscountIntrest(double discountIntrest) {
		this.discountIntrest = discountIntrest;
	}

	public boolean isShowDsaField() {
		return showDsaField;
	}

	public void setShowDsaField(boolean showDsaField) {
		this.showDsaField = showDsaField;
	}

	public double getDsaCommission() {
		return commission;
	}

	public void setDsaCommission(double commission) {
		this.commission = commission;
	}

	public DsaListInfo getCommissionInfo() {
		return commissionInfo;
	}

	public void setCommissionInfo(DsaListInfo commissionInfo) {
		this.commissionInfo = commissionInfo;
	}

	public boolean isRenderTableField() {
		return renderTableField;
	}

	public void setRenderTableField(boolean renderTableField) {
		this.renderTableField = renderTableField;
	}

	public double getSavingAmount() {
		return savingAmount;
	}

	public void setSavingAmount(double savingAmount) {
		this.savingAmount = savingAmount;
	}

	

	

	public boolean isChkLoanSettlement() {
		return chkLoanSettlement;
	}

	public void setChkLoanSettlement(boolean chkLoanSettlement) {
		this.chkLoanSettlement = chkLoanSettlement;
	}

	public boolean isRenderPayMode() {
		return renderPayMode;
	}

	public void setRenderPayMode(boolean renderPayMode) {
		this.renderPayMode = renderPayMode;
	}

	public double getLoanSettlementAmount() {
		return loanSettlementAmount;
	}

	public void setLoanSettlementAmount(double loanSettlementAmount) {
		this.loanSettlementAmount = loanSettlementAmount;
	}

	public String getPrintDt() {
		return printDt;
	}

	public void setPrintDt(String printDt) {
		this.printDt = printDt;
	}

	public ArrayList<ReportInfo> getDailyPayList() {
		return dailyPayList;
	}

	public void setDailyPayList(ArrayList<ReportInfo> dailyPayList) {
		this.dailyPayList = dailyPayList;
	}

	public double getForeClosureInterest() {
		return foreClosureInterest;
	}

	public void setForeClosureInterest(double foreClosureInterest) {
		this.foreClosureInterest = foreClosureInterest;
	}

	public double getForeClosureTotalRemaining() {
		return foreClosureTotalRemaining;
	}

	public void setForeClosureTotalRemaining(double foreClosureTotalRemaining) {
		this.foreClosureTotalRemaining = foreClosureTotalRemaining;
	}

	public double getTilldateInterest() {
		return tilldateInterest;
	}

	public void setTilldateInterest(double tilldateInterest) {
		this.tilldateInterest = tilldateInterest;
	}

	public double getTotalForCloser() {
		return totalForCloser;
	}

	public void setTotalForCloser(double totalForCloser) {
		this.totalForCloser = totalForCloser;
	}

	public double getsA() {
		return sA;
	}

	public void setsA(double sA) {
		this.sA = sA;
	}


	

	public String getRating() {
		return rating;
	}

	public void setRating(String rating) {
		this.rating = rating;

	}




	public double getGrossTotal() {
		return grossTotal;
	}

	public void setGrossTotal(double grossTotal) {
		this.grossTotal = grossTotal;
	}

	


	

	public double getStoreRDAmount() {
		return storeRDAmount;
	}

	public void setStoreRDAmount(double storeRDAmount) {
		this.storeRDAmount = storeRDAmount;
	}



	public void setLoanAmount(String loanAmount) {
		this.loanAmount = loanAmount;
	}

	public double getAfterTodayTotalInterest() {
		return afterTodayTotalInterest;
	}

	public void setAfterTodayTotalInterest(double afterTodayTotalInterest) {
		this.afterTodayTotalInterest = afterTodayTotalInterest;
	}

	public double getTotalInterestAmountRemaining() {
		return totalInterestAmountRemaining;
	}

	public void setTotalInterestAmountRemaining(double totalInterestAmountRemaining) {
		this.totalInterestAmountRemaining = totalInterestAmountRemaining;
	}

	public boolean isDisableForeclosureCharges() {
		return disableForeclosureCharges;
	}

	public void setDisableForeclosureCharges(boolean disableForeclosureCharges) {
		this.disableForeclosureCharges = disableForeclosureCharges;
	}

	public boolean isDeductRDAmount() {
		return deductRDAmount;
	}

	public void setDeductRDAmount(boolean deductRDAmount) {
		this.deductRDAmount = deductRDAmount;
	}

	public boolean isShowRdDetailsOnLoanCloser() {
		return showRdDetailsOnLoanCloser;
	}

	public void setShowRdDetailsOnLoanCloser(boolean showRdDetailsOnLoanCloser) {
		this.showRdDetailsOnLoanCloser = showRdDetailsOnLoanCloser;
	}

	public String getRdNumber() {
		return rdNumber;
	}

	public void setRdNumber(String rdNumber) {
		this.rdNumber = rdNumber;
	}

	public double getRdInstallmentAmount() {
		return rdInstallmentAmount;
	}

	public void setRdInstallmentAmount(double rdInstallmentAmount) {
		this.rdInstallmentAmount = rdInstallmentAmount;
	}

	public double getPaidInstallments() {
		return paidInstallments;
	}

	public void setPaidInstallments(double paidInstallments) {
		this.paidInstallments = paidInstallments;
	}

	public int getRdvalue() {
		return rdvalue;
	}

	public void setRdvalue(int rdvalue) {
		this.rdvalue = rdvalue;
	}

	public int getPeriod() {
		return period;
	}

	public void setPeriod(int period) {
		this.period = period;
	}

	public Double getForeCloseChargeinper() {
		return foreCloseChargeinper;
	}

	public void setForeCloseChargeinper(Double foreCloseChargeinper) {
		this.foreCloseChargeinper = foreCloseChargeinper;
	}

	public void setForeclosureCharges(Double foreclosureCharges) {
		this.foreclosureCharges = foreclosureCharges;
	}

	public Double getForeclosureCharges() {
		return foreclosureCharges;
	}

	public double getFinalAmount() {
		return finalAmount;
	}

	public void setFinalAmount(double finalAmount) {
		this.finalAmount = finalAmount;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public double getAdvanceInterest() {
		return advanceInterest;
	}

	public void setAdvanceInterest(double advanceInterest) {
		this.advanceInterest = advanceInterest;
	}

	public String getInterestType() {
		return interestType;
	}

	public void setInterestType(String interestType) {
		this.interestType = interestType;
	}

	public boolean isShowInterestType() {
		return showInterestType;
	}

	public void setShowInterestType(boolean showInterestType) {
		this.showInterestType = showInterestType;
	}

	public double getTotalChqCharge1() {
		return totalChqCharge1;
	}

	public void setTotalChqCharge1(double totalChqCharge1) {
		this.totalChqCharge1 = totalChqCharge1;
	}

	public double getTotalChqCharge2() {
		return totalChqCharge2;
	}

	public void setTotalChqCharge2(double totalChqCharge2) {
		this.totalChqCharge2 = totalChqCharge2;
	}

	public Boolean getLongOverdueClosure() {
		return longOverdueClosure;
	}

	public void setLongOverdueClosure(Boolean longOverdueClosure) {
		this.longOverdueClosure = longOverdueClosure;
	}

	public double getCalculatedIntAmtAfterTenureTillDate() {
		return calculatedIntAmtAfterTenureTillDate;
	}

	public void setCalculatedIntAmtAfterTenureTillDate(double CalculatedIntAmtAfterTenureTillDate) {
		this.calculatedIntAmtAfterTenureTillDate = CalculatedIntAmtAfterTenureTillDate;
	}
    
	public void setCalculatedIntAmtAfterTenureTillDate(Double CalculatedIntAmtAfterTenureTillDate) {
		this.calculatedIntAmtAfterTenureTillDate = CalculatedIntAmtAfterTenureTillDate;
	}

	

	public double getDisIntAmtAfterTenureTillDate() {
		return disIntAmtAfterTenureTillDate;
	}

	public void setDisIntAmtAfterTenureTillDate(double disIntAmtAfterTenureTillDate) {
		this.disIntAmtAfterTenureTillDate = disIntAmtAfterTenureTillDate;
	}

	public String getCompanyName() {
		return companyName;
	}

	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}

	public double getTotalInterestRemainLocal() {
		return totalInterestRemainLocal;
	}

	public void setTotalInterestRemainLocal(double totalInterestRemainLocal) {
		this.totalInterestRemainLocal = totalInterestRemainLocal;
	}

	public double getTotalChqChrgRemainLocal() {
		return totalChqChrgRemainLocal;
	}

	public void setTotalChqChrgRemainLocal(double totalChqChrgRemainLocal) {
		this.totalChqChrgRemainLocal = totalChqChrgRemainLocal;
	}

	public double getTotalPrincipalRemainLocal() {
		return totalPrincipalRemainLocal;
	}

	public void setTotalPrincipalRemainLocal(double totalPrincipalRemainLocal) {
		this.totalPrincipalRemainLocal = totalPrincipalRemainLocal;
	}

	public double getTotalPenaltyRemainLocal() {
		return totalPenaltyRemainLocal;
	}

	public void setTotalPenaltyRemainLocal(double totalPenaltyRemainLocal) {
		this.totalPenaltyRemainLocal = totalPenaltyRemainLocal;
	}

	public double getCalculatedIntAmtAfterTenureTillDateLocal() {
		return calculatedIntAmtAfterTenureTillDateLocal;
	}

	public void setCalculatedIntAmtAfterTenureTillDateLocal(double calculatedIntAmtAfterTenureTillDateLocal) {
		this.calculatedIntAmtAfterTenureTillDateLocal = calculatedIntAmtAfterTenureTillDateLocal;
	}

	public DataBaseMethodsHemant getDbmt() {
		return dbmt;
	}

	public void setDbmt(DataBaseMethodsHemant dbmt) {
		this.dbmt = dbmt;
	}

	public DataBaseMethodTaheer getDbt() {
		return dbt;
	}

	public void setDbt(DataBaseMethodTaheer dbt) {
		this.dbt = dbt;
	}

	public DataBaseMethodsRaviK getDbrk() {
		return dbrk;
	}

	public void setDbrk(DataBaseMethodsRaviK dbrk) {
		this.dbrk = dbrk;
	}

	public boolean isBothMode() {
		return bothMode;
	}

	public void setBothMode(boolean bothMode) {
		this.bothMode = bothMode;
	}

	public boolean isRenCashAmount() {
		return renCashAmount;
	}

	public void setRenCashAmount(boolean renCashAmount) {
		this.renCashAmount = renCashAmount;
	}

	public boolean isRenUPIAmount() {
		return renUPIAmount;
	}

	public void setRenUPIAmount(boolean renUPIAmount) {
		this.renUPIAmount = renUPIAmount;
	}

	public boolean isDisCashAmount() {
		return disCashAmount;
	}

	public void setDisCashAmount(boolean disCashAmount) {
		this.disCashAmount = disCashAmount;
	}

	public boolean isDisUPIAmount() {
		return disUPIAmount;
	}

	public void setDisUPIAmount(boolean disUPIAmount) {
		this.disUPIAmount = disUPIAmount;
	}

	public boolean isDisPayMode() {
		return disPayMode;
	}

	public void setDisPayMode(boolean disPayMode) {
		this.disPayMode = disPayMode;
	}

	public EditSource getLastEdited() {
		return lastEdited;
	}

	public void setLastEdited(EditSource lastEdited) {
		this.lastEdited = lastEdited;
	}

	public int getBranchId() {
		return branchId;
	}

	public void setBranchId(int branchId) {
		this.branchId = branchId;
	}

	public DataBaseMethods getObj() {
		return obj;
	}

	public void setObj(DataBaseMethods obj) {
		this.obj = obj;
	}

	public DataBaseMethodRahul getDbr() {
		return dbr;
	}

	public void setDbr(DataBaseMethodRahul dbr) {
		this.dbr = dbr;
	}

	public DecimalFormat getDc() {
		return dc;
	}

	public void setDc(DecimalFormat dc) {
		this.dc = dc;
	}

	public SimpleDateFormat getSf() {
		return sf;
	}

	public void setSf(SimpleDateFormat sf) {
		this.sf = sf;
	}

	public HeaderBean getHb() {
		return hb;
	}

	public void setHb(HeaderBean hb) {
		this.hb = hb;
	}

	public String getLoanAmount() {
		return loanAmount;
	}

	public double getGst() {
		return gst;
	}

	public void setGst(double gst) {
		this.gst = gst;
	}

	public double getGstAmount() {
		return gstAmount;
	}

	public void setGstAmount(double gstAmount) {
		this.gstAmount = gstAmount;
	}

	public double getCashAmount() {
		return cashAmount;
	}

	public void setCashAmount(double cashAmount) {
		this.cashAmount = cashAmount;
	}

	public double getUpiAmount() {
		return upiAmount;
	}

	public void setUpiAmount(double upiAmount) {
		this.upiAmount = upiAmount;
	}

	public double getChargeAmount() {
		return chargeAmount;
	}

	public void setChargeAmount(double chargeAmount) {
		this.chargeAmount = chargeAmount;
	}

	public double getAfterTenureInterest() {
		return afterTenureInterest;
	}

	public void setAfterTenureInterest(double afterTenureInterest) {
		this.afterTenureInterest = afterTenureInterest;
	}

	


	
	
	
}
/*package finance;

import income_expense_module.DataBaseMethodsIncome_Expense;

import java.io.Serializable;
import java.text.DecimalFormat;
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;

@ViewScoped
@ManagedBean(name="loanCloser")
public class LoanCloserBean implements Serializable
{
	String loanNo, loanType;
	ArrayList<LoanInfo> loanEMIList;
	LoanInfo loan_info,selectedLoan;
	ArrayList<SelectItem> bankList, loanTypeList;
	UserInfo user_info;
	List<String> nameList;
	double totalPenaltyDue, totalPenaltyPaid, totalIntrest, totalEmi, totalPrincipal, totalDue, totalPaid, totalRemaining, totalIntrestRemain, totalPrincipalRemain, amount, 
	totalPenaltyRemain, totalChqChargeRemain, discount;
	double totalChqCharge, paidChqcharge;
	boolean show;
	boolean value, value1, value2,showTransfer, showTransferSelect=true, ecsDdNo;
	String chequeNo, bankName, paymentMode="Cash",transfer="No",submittedBankName, payType, label, receipt_no, voucherNo;
	Date chequeDate, paidDate=new Date();
	int MyId;
	
	public LoanCloserBean() 
	{
		//loanTypeList=obj.allTypeLoanNameList();
		bankList=new DataBaseMethodsIncome_Expense().allBankList();
		receipt_no=String.valueOf(obj.loanPayReceiptNo());
	}
	
	public List<String> completeLoanNo(String name)
	{
		if(loanType!=null)
		{
			nameList=new DataBaseMethodsAutoComplete().showLoanNoByLoanType(name,loanType);
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null,new FacesMessage("Please Select Loan Type First"));
		}
		return nameList;
	}
	
	public void userInfo() throws ParseException 
	{
		HttpSession ss1=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		pageName=(String) ss1.getAttribute("pageName");
		if(pageName!=null && pageName.equals("particularLoan"))
		{
			// System.out.println("if");
			loanNo=((LoanInfo) ss1.getAttribute("selectedLoan")).getLoanNo();
		}
		else
		{
			// System.out.println("else");
			loanNo=loanNo.substring(0,loanNo.indexOf("/"));
		}
		
		show=true;
		loanNo=loanNo.substring(0,loanNo.indexOf("/"));
		
		user_info=obj.userInfoByLoanNoLoanType(loanNo,loanType);
		loan_info=obj.loanInfoByLoanNoLoanType(loanNo,loanType);
		//amount=loan_info.getInstallAmount();
		//// System.out.println(loan_info.getEmiMode());
		
		loanEMIList=obj.loanInstallment(loanType,loanNo);
		

		loanEMIList=obj.penaltyCalculationMethod(loanType, loanNo, loanEMIList);
		
		double totPaid=obj.totalPaidPenaltyAndChequeBounceCharges(loanNo, "Penalty",loanType);
		if(totPaid>0)
		{
			for(int i=0; i<loanEMIList.size(); i++)
			{
				if(totPaid>loanEMIList.get(i).getPenaltyDue())
				{
					loanEMIList.get(i).setPenaltyPaid(loanEMIList.get(i).getPenaltyDue());
				}
				else
				{
					loanEMIList.get(i).setPenaltyPaid(totPaid);
					break;
				}
				totPaid=totPaid-loanEMIList.get(i).getPenaltyDue();
			}
			
		}
	
		
		totalPenaltyDue=totalPenaltyPaid=totalIntrest=totalEmi=totalPrincipal=totalDue=totalPaid=totalIntrestRemain=totalPrincipalRemain=totalChqCharge=0;
		for(LoanInfo ll: loanEMIList)
		{
			totalEmi+=ll.getInstallAmount();
			totalIntrest+=Double.parseDouble(ll.getInterestAmount());
			totalPrincipal+=Double.parseDouble(ll.getPrincipalAmount());
			totalPaid+=ll.getPaidAmount();
			totalDue+=ll.getDueAmount();
			totalPenaltyDue+=ll.getPenaltyDue();
			totalPenaltyPaid+=ll.getPenaltyPaid();
			
			if(ll.getStatus().equals("Due"))
			{
				totalIntrestRemain+=Double.parseDouble(ll.getInterestAmount());
				totalPrincipalRemain+=Double.parseDouble(ll.getPrincipalAmount());
			}
		}
		
		double totPrPaid=obj.totalPrincipalPaidByLoanNo(loanNo);
		double totIrPaid=obj.totalIntrestPaidByLoanNo(loanNo);
		totalPrincipalRemain=totalPrincipal-totPrPaid;
		totalIntrestRemain=totalIntrest-totIrPaid;
		
		// System.out.println(totalPrincipal+"====="+totPrPaid);
		
		totalChqCharge=obj.calculatePenaltyAndChequeBounceCharges(loanNo, "Cheque Bounce",loanType);
		paidChqcharge=obj.totalPaidPenaltyAndChequeBounceCharges(loanNo, "Cheque Bounce",loanType);
		totalChqChargeRemain=Double.parseDouble(dc.format(totalChqCharge-paidChqcharge));
		
		totalEmi=Double.parseDouble(dc.format(totalEmi));
		totalIntrest=Double.parseDouble(dc.format(totalIntrest));
		totalPrincipal=Double.parseDouble(dc.format(totalPrincipal));
		totalPaid=Double.parseDouble(dc.format(totalPaid));
		totalDue=Double.parseDouble(dc.format(totalDue));
		totalPenaltyDue=Double.parseDouble(dc.format(totalPenaltyDue));
		totalPenaltyPaid=Double.parseDouble(dc.format(totalPenaltyPaid));
		totalPenaltyRemain=Double.parseDouble(dc.format(totalPenaltyDue-totalPenaltyPaid));
		totalIntrestRemain=Double.parseDouble(dc.format(totalIntrestRemain));
		totalPrincipalRemain=Double.parseDouble(dc.format(totalPrincipalRemain));
		totalRemaining=Double.parseDouble(dc.format(totalIntrestRemain+totalPrincipalRemain+totalChqChargeRemain+totalPenaltyRemain));
		
		amount=totalRemaining;
		
		
	}
	
	public void checkPaid()
	{
		// System.out.println(discount);
		if(discount<=totalIntrestRemain)
		{
			amount=totalRemaining-discount;
		}
		else
		{
			discount=totalIntrestRemain;
			amount=totalRemaining-discount;
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Discount Can't be greater than Total Intrest amount remaining."));
		}
	}

	public void checkTransferMode()
	{
		if(transfer.equals("Yes"))
		{
			showTransfer=true;
		}
		else
		{
			showTransfer=false;
		}
	}
	
	public void forPaymentMode()
	{
		//// System.out.println(paymentMode);
		if (paymentMode.equals("0")) 
		{
			value1 = value2= false;
		}
		else if (paymentMode.equals("Cash")) 
		{
			value1 = true;
			value2 = false;
			showTransfer=ecsDdNo=false;
			showTransferSelect=true;
			transfer=bankName=chequeNo="";
			chequeDate=null;
		}
		else if(paymentMode.equals("ecs"))
		{
			ecsDdNo=true;
			value1 = true;
			value2 = false;
			showTransfer=true;
			showTransferSelect=false;
			transfer="Yes";
			bankName=chequeNo="";
			chequeDate=null;
		}
		else if (paymentMode.equals("Cheque") || paymentMode.equals("neft")) 
		{
			value2 = true;
			value1 =ecsDdNo= false;
			showTransferSelect=false;
			showTransfer=true;
			transfer=bankName=chequeNo="";
			chequeDate=null;
		}
		else if(paymentMode.equals("neft"))
		{
			ecsDdNo=true;
			value1 = true;
			value2 = true;
			showTransfer=true;
			showTransferSelect=false;
			transfer="Yes";
			bankName=chequeNo="";
			chequeDate=null;
		}
		
		
		checkMode();
			
		
	}
	
	private void checkMode() 
	{
		if(paymentMode.equals("Cheque"))
		{
			label="Cheque";
		}
		else if(paymentMode.equals("neft"))
		{
			label="RTGS/NEFT/IMPS";
		}
		else
		{
			label="Demand Draft";
		}
	}
	
	
	public String submit()
	{
		if(paymentMode.equalsIgnoreCase("cash"))
		{
			submittedBankName="N/A";
		}
		
		
		// System.out.println("called "+amount);
		receipt_no=String.valueOf(obj.loanPayReceiptNo());
		int	n = obj.payLoanEMI(loanNo,loanType,amount,paidDate,paymentMode,chequeNo,chequeDate,bankName,0,receipt_no,submittedBankName,"No", discount,-1);
		MyId=n;
		if (n >= 1) 
		{
			totalIntrestRemain=totalIntrestRemain-discount;
			if(paymentMode.equalsIgnoreCase("Cash") && transfer.equalsIgnoreCase("No"))
			{
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Payment Done SuccessFully..."));
				
				obj.updateInterestAmountInLoanPayReceipt(n, totalIntrestRemain);
				obj.decreaseSharedCompanyAmount(totalPrincipalRemain);
				RequestContext.getCurrentInstance().execute("window.open('loanPayReceipt.xhtml')");
			}
			else if(paymentMode.equalsIgnoreCase("Cash") && transfer.equalsIgnoreCase("Yes"))
			{
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Payment Done SuccessFully..."));
				
				obj.updateInterestAmountInLoanPayReceiptWithoutIncreasingCompanyCapital(n, totalIntrestRemain);
				obj.increaseBankBalance(submittedBankName, amount);
				RequestContext.getCurrentInstance().execute("window.open('loanPayReceipt.xhtml')");
			}
			else
			{
				obj.updateInterestAmountInLoanPayReceiptWithoutIncreasingCompanyCapital(n, totalIntrestRemain);
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Payment Done SuccessFully... Please Approve Your Payment"));
			}
			
			detailsForLoanPrint();
			obj.updateStatusOfLoan(loanType,loanNo);
			
			discount=0;
			
			if(totalPenaltyRemain>0)
			{
				voucherNo=obj.generateVoucherNo("income_table");
				int i=new DataBaseMethodsIncome_Expense().addIncome(paidDate,"Other_Cr",paymentMode,String.valueOf(totalPenaltyRemain) ,chequeNo,"",bankName,chequeDate,
						"Penalty Income","Receive Penalty",0,submittedBankName, "0", discount,loanNo, loanType,voucherNo,"",0); 
				if(i>=1)
				{
				    //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Income Added Successfully"));
				    if(paymentMode.equalsIgnoreCase("Cash") && transfer.equals("No"))
					{
						obj.increaseCompanyCapitalAmount(totalPenaltyRemain);
					}
					else if(paymentMode.equalsIgnoreCase("Cash") && transfer.equals("Yes"))
					{
						obj.increaseBankBalance(submittedBankName, totalPenaltyRemain);
					}
				}   
			}
			
			if(totalChqChargeRemain>0)
			{
				voucherNo=obj.generateVoucherNo("income_table");
				int j=new DataBaseMethodsIncome_Expense().addIncome(paidDate,"Other_Cr",paymentMode,String.valueOf(totalChqChargeRemain) ,chequeNo,"",bankName,
						chequeDate,"Cheque Bounce Income","Receive Cheque Bounce Charges",0,submittedBankName, "0", discount,loanNo, loanType,voucherNo,"",0); 
				if(j>=1)
				{
				    //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Income Added Successfully"));
				    if(paymentMode.equalsIgnoreCase("Cash") && transfer.equals("No"))
					{
						obj.increaseCompanyCapitalAmount(Double.valueOf(totalChqChargeRemain));
					}
					else if(paymentMode.equalsIgnoreCase("Cash") && transfer.equals("Yes"))
					{
						obj.increaseBankBalance(submittedBankName, Double.valueOf(totalChqChargeRemain));
					}
				}   
			}
			
			value2= false;paymentMode=chequeNo=bankName="";
			amount=0;chequeNo=bankName="";chequeDate=null;show=false;
			return "userBlockDashboard.xhtml";
		}
		else
		{
			FacesContext fc = FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
			return "";
		}
	}
	
	public void detailsForLoanPrint()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		ss.setAttribute("shareHolderNo", user_info.getShareHolderNo());
		ss.setAttribute("loanNo",loanNo);
		ss.setAttribute("receipt_no",receipt_no);
		ss.setAttribute("installment_amount",amount);
		ss.setAttribute("loanType", loanType);
		ss.setAttribute("id",MyId);
		ss.setAttribute("receipt_date",new SimpleDateFormat("dd/MM/yyyy").format(paidDate));
		ss.setAttribute("instlmnt_no","Loan Closure");
	}
	
	public String getLoanNo() {
		return loanNo;
	}

	public void setLoanNo(String loanNo) {
		this.loanNo = loanNo;
	}

	public String getLoanType() {
		return loanType;
	}

	public void setLoanType(String loanType) {
		this.loanType = loanType;
	}

	public ArrayList<LoanInfo> getLoanEMIList() {
		return loanEMIList;
	}

	public void setLoanEMIList(ArrayList<LoanInfo> loanEMIList) {
		this.loanEMIList = loanEMIList;
	}

	public LoanInfo getLoan_info() {
		return loan_info;
	}

	public void setLoan_info(LoanInfo loan_info) {
		this.loan_info = loan_info;
	}

	public LoanInfo getSelectedLoan() {
		return selectedLoan;
	}

	public void setSelectedLoan(LoanInfo selectedLoan) {
		this.selectedLoan = selectedLoan;
	}

	public ArrayList<SelectItem> getLoanTypeList() {
		return loanTypeList;
	}

	public void setLoanTypeList(ArrayList<SelectItem> loanTypeList) {
		this.loanTypeList = loanTypeList;
	}

	public UserInfo getUser_info() {
		return user_info;
	}

	public void setUser_info(UserInfo user_info) {
		this.user_info = user_info;
	}

	public List<String> getNameList() {
		return nameList;
	}

	public void setNameList(List<String> nameList) {
		this.nameList = nameList;
	}

	public double getTotalPenaltyDue() {
		return totalPenaltyDue;
	}

	public void setTotalPenaltyDue(double totalPenaltyDue) {
		this.totalPenaltyDue = totalPenaltyDue;
	}

	public double getTotalPenaltyPaid() {
		return totalPenaltyPaid;
	}

	public void setTotalPenaltyPaid(double totalPenaltyPaid) {
		this.totalPenaltyPaid = totalPenaltyPaid;
	}

	public double getTotalIntrest() {
		return totalIntrest;
	}

	public void setTotalIntrest(double totalIntrest) {
		this.totalIntrest = totalIntrest;
	}

	public double getTotalEmi() {
		return totalEmi;
	}

	public void setTotalEmi(double totalEmi) {
		this.totalEmi = totalEmi;
	}

	public double getTotalPrincipal() {
		return totalPrincipal;
	}

	public void setTotalPrincipal(double totalPrincipal) {
		this.totalPrincipal = totalPrincipal;
	}

	public double getTotalDue() {
		return totalDue;
	}

	public void setTotalDue(double totalDue) {
		this.totalDue = totalDue;
	}

	public double getTotalPaid() {
		return totalPaid;
	}

	public void setTotalPaid(double totalPaid) {
		this.totalPaid = totalPaid;
	}

	public double getTotalChqCharge() {
		return totalChqCharge;
	}

	public void setTotalChqCharge(double totalChqCharge) {
		this.totalChqCharge = totalChqCharge;
	}

	public double getPaidChqcharge() {
		return paidChqcharge;
	}

	public void setPaidChqcharge(double paidChqcharge) {
		this.paidChqcharge = paidChqcharge;
	}

	public boolean isShow() {
		return show;
	}

	public void setShow(boolean show) {
		this.show = show;
	}

	public double getTotalRemaining() {
		return totalRemaining;
	}

	public void setTotalRemaining(double totalRemaining) {
		this.totalRemaining = totalRemaining;
	}

	public double getTotalIntrestRemain() {
		return totalIntrestRemain;
	}

	public void setTotalIntrestRemain(double totalIntrestRemain) {
		this.totalIntrestRemain = totalIntrestRemain;
	}

	public double getTotalPrincipalRemain() {
		return totalPrincipalRemain;
	}

	public void setTotalPrincipalRemain(double totalPrincipalRemain) {
		this.totalPrincipalRemain = totalPrincipalRemain;
	}

	public double getTotalPenaltyRemain() {
		return totalPenaltyRemain;
	}

	public void setTotalPenaltyRemain(double totalPenaltyRemain) {
		this.totalPenaltyRemain = totalPenaltyRemain;
	}

	public double getTotalChqChargeRemain() {
		return totalChqChargeRemain;
	}

	public void setTotalChqChargeRemain(double totalChqChargeRemain) {
		this.totalChqChargeRemain = totalChqChargeRemain;
	}

	public ArrayList<SelectItem> getBankList() {
		return bankList;
	}

	public void setBankList(ArrayList<SelectItem> bankList) {
		this.bankList = bankList;
	}

	public boolean isValue() {
		return value;
	}

	public void setValue(boolean value) {
		this.value = value;
	}

	public boolean isValue1() {
		return value1;
	}

	public void setValue1(boolean value1) {
		this.value1 = value1;
	}

	public boolean isValue2() {
		return value2;
	}

	public void setValue2(boolean value2) {
		this.value2 = value2;
	}

	public boolean isShowTransfer() {
		return showTransfer;
	}

	public void setShowTransfer(boolean showTransfer) {
		this.showTransfer = showTransfer;
	}

	public boolean isShowTransferSelect() {
		return showTransferSelect;
	}

	public void setShowTransferSelect(boolean showTransferSelect) {
		this.showTransferSelect = showTransferSelect;
	}

	public boolean isEcsDdNo() {
		return ecsDdNo;
	}

	public void setEcsDdNo(boolean ecsDdNo) {
		this.ecsDdNo = ecsDdNo;
	}

	public String getChequeNo() {
		return chequeNo;
	}

	public void setChequeNo(String chequeNo) {
		this.chequeNo = chequeNo;
	}

	public String getBankName() {
		return bankName;
	}

	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	public String getPaymentMode() {
		return paymentMode;
	}

	public void setPaymentMode(String paymentMode) {
		this.paymentMode = paymentMode;
	}

	public String getTransfer() {
		return transfer;
	}

	public void setTransfer(String transfer) {
		this.transfer = transfer;
	}

	public String getSubmittedBankName() {
		return submittedBankName;
	}

	public void setSubmittedBankName(String submittedBankName) {
		this.submittedBankName = submittedBankName;
	}

	public String getPayType() {
		return payType;
	}

	public void setPayType(String payType) {
		this.payType = payType;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public Date getChequeDate() {
		return chequeDate;
	}

	public void setChequeDate(Date chequeDate) {
		this.chequeDate = chequeDate;
	}

	
	public Date getPaidDate() {
		return paidDate;
	}

	public void setPaidDate(Date paidDate) {
		this.paidDate = paidDate;
	}

	public String getReceipt_no() {
		return receipt_no;
	}

	public void setReceipt_no(String receipt_no) {
		this.receipt_no = receipt_no;
	}

	public double getAmount() {
		return amount;
	}

	public void setAmount(double amount) {
		this.amount = amount;
	}

	public double getDiscount() {
		return discount;
	}

	public void setDiscount(double discount) {
		this.discount = discount;
	}

	
	
	
}
*/