package main_package;

import java.io.Serializable;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

@ManagedBean(name = "loanLedgerBean")
@ViewScoped

public class LoanLedgerBean implements Serializable
{
	String operationType = "";

	
	double principal, totalBalance, totalCredit, totalDebit, bookedAmount;
	
	private double totalEmi, totalInterest, totalPrinciple, totalPaid, totalDue, totalPenaltyDue, totalPenaltyPaid;
	 
	
	boolean showLoanPaidStatus;
	
	
	ArrayList<LoanLedgerInfo> list = new ArrayList<>();
	ArrayList<LoanInfo> emiList = new ArrayList<>();
	
	
	LoanInfo selectedVal;
	
	
	DataBaseMethodTaheer dbmt = new DataBaseMethodTaheer();
	
	DataBaseMethods dbm = new DataBaseMethods();
	
	SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	
	
	public LoanLedgerBean() 
	{
	    HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		
		selectedVal= (LoanInfo) ss.getAttribute("selectedVal");
		totalEmi = (double) ss.getAttribute("totalEmi");
		
		totalInterest = (double) ss.getAttribute("totalIntrest");
		totalPrinciple = (double) ss.getAttribute("totalPrincipal");
		totalPaid = (double) ss.getAttribute("totalPaid");
		totalDue = (double) ss.getAttribute("reportClosingBalance");
		totalPenaltyDue = (double) ss.getAttribute("penaltyDue");
		totalPenaltyPaid = (double) ss.getAttribute("penaltyPaid");
		
		if(selectedVal.getPaidStatus()!=null && selectedVal.getPaidStatus().equalsIgnoreCase("paid"))
		{
			showLoanPaidStatus=true;
		}
		
		Connection conn = DataBaseConnection.JAVAConnection();
		
		int i = 1;
		double dbAmount = dbmt.debitLoanAmountByLoanNo(selectedVal.getLoanNo(), conn);
		double chargeAmt = 0, totalChargeAmt = 0;
		double principalOutstanding = 0, scheduledInterest = 0, bookedReceivable = 0;
		String dbDate = dbmt.debitDateByLoanNo(selectedVal.getLoanNo(), conn);
		String loanType = dbmt.loanTypeByLoanNo(selectedVal.getLoanNo());
		
		principal = dbAmount;
		bookedAmount = 0;
		emiList = dbm.loanInstallment(loanType, selectedVal.getLoanNo(), conn);
		
		
		ArrayList<String> chargeList = dbmt.allChargesList(conn);
		
		for (String charge : chargeList)
		{
//			if(charge.equalsIgnoreCase("Broken Period Interest"))
//			{
//				double ibpc = dbmt.fetchBrokenPeriodChargeByLoanNoFromIncomeAndExpenseTable("income_table", selectedVal.getLoanNo(), 
//																						    conn);
//				double ebpc = dbmt.fetchBrokenPeriodChargeByLoanNoFromIncomeAndExpenseTable("expense_table", selectedVal.getLoanNo(), 
//						   																	conn);
//				
//				LoanLedgerInfo ci = new LoanLedgerInfo();
//				
//				ci.setStrDate(dbDate);
//				
//				if (ibpc > 0) 
//				{
//					ci.setParticular(charge + " Income");
//					ci.setDebit(0);
//					ci.setPrincipal(0);
//				}
//				else if (ebpc > 0) 
//				{
//					ci.setParticular(charge + " Expense");
//					ci.setDebit(0);
//					ci.setPrincipal(0);
//				}
//				
//				ci.setCredit(0);
//				ci.setInterest(0);
//				ci.setBooked(0);
//				ci.setBalance(totalChargeAmt);
//				
//				if (ibpc > 0 || ebpc > 0) 
//				{
//					ci.setsNo(i++);
//					list.add(ci);
//				}
//			}
//			else 
//			{
			chargeAmt = dbmt.fetchAmountByLoanNoFromIncomeAndExpenseTable("income_table", selectedVal.getLoanNo(), charge, conn);
				totalChargeAmt += chargeAmt;
				
				LoanLedgerInfo ci = new LoanLedgerInfo();
				
				ci.setStrDate(dbDate);
				ci.setParticular(charge);
				ci.setDebit(chargeAmt);
				ci.setCredit(0);
				ci.setPrincipal(0);
				ci.setInterest(0);
				ci.setBooked(0);
				ci.setBalance(0);
				
				if (chargeAmt > 0) 
				{
					ci.setsNo(i++);
					list.add(ci);
				}
			
		}	
		
		
		
		LoanLedgerInfo ll = new LoanLedgerInfo();
		
		ll.setsNo(i++);
		ll.setStrDate(dbDate);
		ll.setParticular("Loan Disbursement");
		ll.setDebit(dbAmount);
		ll.setCredit(0);
		ll.setPrincipal(dbAmount);
		ll.setInterest(totalInterest);
		ll.setBooked(0);
		ll.setBalance(dbAmount);
		
		list.add(ll);
		
		
		for (LoanInfo li : emiList)
		{
			boolean check = dbmt.checkDuplicateBooking(li, selectedVal.getLoanNo(), "Interest", conn);
			Date ascPaidDate = dbmt.loanPaidDateByASCOrder(li.getSno(), selectedVal.getLoanNo(), conn);	
			Date bookDate = dbmt.fetchDateInterestBooked(li, selectedVal.getLoanNo(), "Interest", conn);
			
			
			if (check) 
			{
				LoanLedgerInfo ll1 = new LoanLedgerInfo();
								
				ll1.setsNo(i++);
				ll1.setStrDate(li.getStrInstlmntDate());
				ll1.setParticular("Interest Receivable");
				
//				if (Double.valueOf(li.getInterestAmount()) > li.getPaidAmount()) 
//				{
					ll1.setDebit(dbmt.fetchInterestAmountBooked(li, selectedVal.getLoanNo(), "Interest", conn));
//				}
//				else 
//				{
//					ll1.setDebit(Double.valueOf(li.getInterestAmount()));
//				}
				
				ll1.setCredit(0);
				ll1.setPrincipal(round(principal));
				ll1.setBooked(round(bookedAmount += ll1.getDebit()));
				ll1.setInterest(round(totalInterest -= ll1.getDebit()));
				ll1.setBalance(round(dbAmount += ll1.getDebit()));
				
				if (ll1.getInterest() < 0) 
				{
					ll1.setInterest(0);
				}
				if (ll1.getPrincipal() < 0) 
				{
					ll1.setPrincipal(0);
				}
				if (ll1.getBooked() < 0) 
				{
					ll1.setBooked(0);
				}
				if (ll1.getBalance() < 0) 
				{
					ll1.setBalance(0);
				}
				
				list.add(ll1);
			}
			
			Date paidDate = dbmt.loanPaidDate(li.getSno(), selectedVal.getLoanNo(), conn);
			
			if (li.getStatus().equalsIgnoreCase("Paid")) 
			{
				double interestPaid = 0;
				
//				if (check) 
//				{
//					double paidAmount = dbmt.loanPaidAmountByLoanNoAndEMINo(li.getSno(), selectedVal.getLoanNo(), conn);
//					double bookedAmt = dbmt.fetchInterestAmountBooked(li, selectedVal.getLoanNo(), "Interest", conn);
										
//					LoanLedgerInfo ll3 = new LoanLedgerInfo();
//					
//					ll3.setStrDate(sdf.format(paidDate));
//					ll3.setsNo(i++);
//					ll3.setParticular("Interest Received");
//					ll3.setDebit(0);
//					if (li.getPaidAmount() < Double.valueOf(li.getInterestAmount())) 
//					{
//						ll3.setCredit(li.getPaidAmount());
//						ll3.setBooked(bookedAmount -= li.getPaidAmount());
//						ll3.setBalance(dbAmount -= li.getPaidAmount());
//					}
//					else 
//					{
//						ll3.setCredit(Double.valueOf(li.getInterestAmount()));
//						ll3.setBooked(bookedAmount -= Double.valueOf(li.getInterestAmount()));
//						ll3.setBalance(dbAmount -= Double.valueOf(li.getInterestAmount()));
//					}
//					ll3.setPrincipal(principal);
//					ll3.setInterest(totalInterest);
//					ll3.setInterest(totalInterest);
//					ll3.setBooked(bookedAmount);
//					
//					if (ll3.getInterest() < 0) 
//					{
//						ll3.setInterest(0);
//					}
//					if (ll3.getPrincipal() < 0) 
//					{
//						ll3.setPrincipal(0);
//					}
//					if (ll3.getBooked() < 0) 
//					{
//						ll3.setBooked(0);
//					}
//					if (ll3.getBalance() < 0) 
//					{
//						ll3.setBalance(0);
//					}
//					
//					interestPaid = ll3.getCredit();
//					
//					list.add(ll3);
//				}
				
				LoanLedgerInfo ll4 = new LoanLedgerInfo();
				
				ll4.setStrDate(sdf.format(paidDate));
				ll4.setParticular("Interest Received");
				ll4.setDebit(0);
				ll4.setCredit(round(Double.valueOf(li.getInterestAmount()) - interestPaid));
				ll4.setPrincipal(round(principal));
				
				if (check) 
				{
					ll4.setInterest(round(totalInterest));
					ll4.setBooked(round(bookedAmount -= ll4.getCredit()));
				}
				else
				{
					ll4.setInterest(round(totalInterest -= ll4.getCredit()));
					ll4.setBooked(round(bookedAmount));
				}
				
				ll4.setBalance(round(dbAmount));
				
				if (ll4.getInterest() < 0) 
				{
					ll4.setInterest(0);
				}
				if (ll4.getPrincipal() < 0) 
				{
					ll4.setPrincipal(0);
				}
				if (ll4.getBooked() < 0) 
				{
					ll4.setBooked(0);
				}
				if (ll4.getBalance() < 0) 
				{
					ll4.setBalance(0);
				}
				
				if (ll4.getCredit() > 0)
				{
					ll4.setsNo(i++);
					list.add(ll4);
				}
				
				LoanLedgerInfo ll2 = new LoanLedgerInfo();
				
				ll2.setsNo(i++);
				ll2.setStrDate(sdf.format(paidDate));
				ll2.setParticular("Principal Received");
				ll2.setDebit(0);
				ll2.setCredit(round(Double.valueOf(li.getPrincipalAmount())));
				ll2.setPrincipal(round(principal -= Double.valueOf(li.getPrincipalAmount())));
				ll2.setInterest(round(totalInterest));
				ll2.setBooked(round(bookedAmount));
				ll2.setBalance(round(dbAmount -= Double.valueOf(li.getPrincipalAmount())));
				
				if (ll2.getInterest() < 0) 
				{
					ll2.setInterest(0);
				}
				if (ll2.getPrincipal() < 0) 
				{
					ll2.setPrincipal(0);
				}
				if (ll2.getBooked() < 0) 
				{
					ll2.setBooked(0);
				}
				if (ll2.getBalance() < 0) 
				{
					ll2.setBalance(0);
				}
				
				list.add(ll2);
			}
			else 
			{
				if (li.getPaidAmount() > 0) 
				{
					double interestInPaidAmt = li.getPaidAmount() - Double.valueOf(li.getInterestAmount());
					
					LoanLedgerInfo ll4 = new LoanLedgerInfo();
					
					ll4.setStrDate(sdf.format(paidDate));
					ll4.setParticular("Interest Received");
					ll4.setDebit(0);
					
					if (li.getPaidAmount() >= Double.valueOf(li.getInterestAmount())) 
					{
						ll4.setCredit(Double.valueOf(li.getInterestAmount()));
					}
					else 
					{
						ll4.setCredit(li.getPaidAmount());
					}
					
					ll4.setPrincipal(principal);
					
					if (check) 
					{
						ll4.setInterest(round(totalInterest -= (Double.valueOf(li.getInterestAmount()) - bookedAmount)));
						
						if (ascPaidDate != null && bookDate != null && ascPaidDate.before(bookDate)) 
						{
							ll4.setBooked(round(bookedAmount));
							ll4.setBalance(round(dbAmount));
						}
						else
						{
							ll4.setBooked(round(bookedAmount -= ll4.getCredit()));
							ll4.setBalance(round(dbAmount -= ll4.getCredit()));
						}
					}
					else 
					{
						ll4.setInterest(round(totalInterest -= Double.valueOf(li.getInterestAmount())));
						ll4.setBalance(round(dbAmount));
						ll4.setBooked(round(bookedAmount));
					}
					
					if (ll4.getInterest() < 0) 
					{
						ll4.setInterest(0);
					}
					if (ll4.getPrincipal() < 0) 
					{
						ll4.setPrincipal(0);
					}
					if (ll4.getBooked() < 0) 
					{
						ll4.setBooked(0);
					}
					if (ll4.getBalance() < 0) 
					{
						ll4.setBalance(0);
					}
					
					if (ll4.getCredit() > 0)
					{
						ll4.setsNo(i++);
						list.add(ll4);
					}
					
					LoanLedgerInfo ll2 = new LoanLedgerInfo();
					
					ll2.setStrDate(sdf.format(paidDate));
					ll2.setParticular("Principal Received");
					ll2.setDebit(0);
					
					if (interestInPaidAmt > 0) 
					{
						ll2.setsNo(i++);
						ll2.setCredit(round(interestInPaidAmt));
						ll2.setPrincipal(round(principal -= ll2.getCredit()));
						ll2.setInterest(round(totalInterest));
						ll2.setBooked(round(bookedAmount));
						ll2.setBalance(round(dbAmount -= ll2.getCredit()));
					
						if (ll2.getInterest() < 0) 
						{
							ll2.setInterest(0);
						}
						if (ll2.getPrincipal() < 0) 
						{
							ll2.setPrincipal(0);
						}
						if (ll2.getBooked() < 0) 
						{
							ll2.setBooked(0);
						}
						if (ll2.getBalance() < 0) 
						{
							ll2.setBalance(0);
						}
						
						list.add(ll2);
					}
				}
			}
		}
		
		
		try 
		{
			conn.close();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		for (LoanLedgerInfo li : list)
		{
			totalDebit += li.getDebit();
			totalCredit += li.getCredit();
			totalPrinciple = li.getPrincipal();
			totalBalance += li.getDebit() - li.getCredit();
			
			totalDebit = Math.round(totalDebit);
			totalCredit = Math.round(totalCredit);
			totalPrinciple = Math.round(totalPrinciple);
			totalBalance = Math.round(totalBalance);
		
	}
	}
	
	
	private double round(double x)
	{
	    return Math.round(x*100.0)/100.0;
	}



	public String getOperationType() {
		return operationType;
	}



	public void setOperationType(String operationType) {
		this.operationType = operationType;
	}



	public double getTotalEmi() {
		return totalEmi;
	}



	public void setTotalEmi(double totalEmi) {
		this.totalEmi = totalEmi;
	}



	public double getTotalPrinciple() {
		return totalPrinciple;
	}



	public void setTotalPrinciple(double totalPrinciple) {
		this.totalPrinciple = totalPrinciple;
	}



	public double getTotalPaid() {
		return totalPaid;
	}



	public void setTotalPaid(double totalPaid) {
		this.totalPaid = totalPaid;
	}



	public double getTotalDue() {
		return totalDue;
	}



	public void setTotalDue(double totalDue) {
		this.totalDue = totalDue;
	}



	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 boolean isShowLoanPaidStatus() {
		return showLoanPaidStatus;
	}



	public void setShowLoanPaidStatus(boolean showLoanPaidStatus) {
		this.showLoanPaidStatus = showLoanPaidStatus;
	}
	


	public LoanInfo getSelectedVal() {
		return selectedVal;
	}



	public void setSelectedVal(LoanInfo selectedVal) {
		this.selectedVal = selectedVal;
	}



	public ArrayList<LoanLedgerInfo> getList() {
		return list;
	}



	public void setList(ArrayList<LoanLedgerInfo> list) {
		this.list = list;
	}



	public double getTotalBalance() {
		return totalBalance;
	}



	public void setTotalBalance(double totalBalance) {
		this.totalBalance = totalBalance;
	}



	public double getTotalCredit() {
		return totalCredit;
	}



	public void setTotalCredit(double totalCredit) {
		this.totalCredit = totalCredit;
	}



	public double getTotalDebit() {
		return totalDebit;
	}



	public void setTotalDebit(double totalDebit) {
		this.totalDebit = totalDebit;
	}



	public double getPrincipal() {
		return principal;
	}



	public void setPrincipal(double principal) {
		this.principal = principal;
	}



	public double getTotalInterest() {
		return totalInterest;
	}



	public void setTotalInterest(double totalInterest) {
		this.totalInterest = totalInterest;
	}



	public double getBookedAmount() {
		return bookedAmount;
	}



	public void setBookedAmount(double bookedAmount) {
		this.bookedAmount = bookedAmount;
	}
	
}