package main_package;

import group_head_package.DataBaseIncomeExpense;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

@ManagedBean(name="dueDebit")
@ViewScoped

public class DueChequeDebitBean implements Serializable
{
	ArrayList<DueDebitInfo> debitLoanList,expenseList,returnDSAList,salPayoutList,fdrExpenseList,rdFdList,finalList,withDrawList, instantLoanList, 
	returnInstantBorrowList,rPromotorsCapitalList, tdsSubList;
	DueDebitInfo selectedNotification;
	String identity="", reason, voucherNo;
	Date chqReturnDate=new Date(), chqClearDate=new Date();
	int n=0;
	double amount;
	DataBaseMethods obj=new DataBaseMethods();
	
	public DueChequeDebitBean() 
	{
		basicMethod();
	}
	
	private void basicMethod() 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		finalList=new ArrayList<>();
		debitLoanList=obj.pendingDebitLoanList(branchId);
		expenseList=obj.pendingExpenseList(branchId);
		withDrawList=obj.pendingWithdrawList(branchId);
		fdrExpenseList=obj.pendingFdrExpenseList(branchId);
		rdFdList=obj.pendingReturnAmountRdFdList(branchId);
		instantLoanList=obj.pendingInstantLoanList(branchId);
		rPromotorsCapitalList=obj.pendingReturnPromotorsCapitalList(branchId);
		returnInstantBorrowList=obj.pendingReturnInstantBorrowList(branchId);
		returnDSAList=obj.pendingReturnDSAList(branchId);
		salPayoutList=obj.pendingSalPayoutList(branchId);
		tdsSubList=obj.pendingTdsSubList(branchId);
	   
		finalList.addAll(rPromotorsCapitalList);
		finalList.addAll(returnInstantBorrowList);
		finalList.addAll(returnDSAList);
		finalList.addAll(salPayoutList);
		finalList.addAll(instantLoanList);
		finalList.addAll(debitLoanList);
		finalList.addAll(expenseList);
		finalList.addAll(fdrExpenseList);
		finalList.addAll(rdFdList);
		finalList.addAll(withDrawList);
		finalList.addAll(tdsSubList);		
	}

	public void dateSettingMethod()
	{
		chqClearDate=selectedNotification.getChequeDate();
	}
	
	public void approveCheque()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		n=0;
		String status="approved",bankId="",notificationId="",type="",loanNo="",shareHolderNo="";
		double amount=0;
		double loanAmount=0,paidLoanAmount=0,maturityValue=0,paidMaturity=0;
		bankId=selectedNotification.getBankId();
		amount=Double.valueOf(selectedNotification.getAmount());
		notificationId=selectedNotification.getId();
		type=selectedNotification.getType();
		Connection conn=DataBaseConnection.JAVAConnection();
		
		identity="approve";
		if(type.equals("personalloan") || type.equals("propertyloan") || type.equals("vechicleloan") || type.equals("grouploan") || type.equals("business_loan") || type.equals("secure_loan"))
		{
		

			loanNo=selectedNotification.getItem_loan_fdr();
			shareHolderNo=selectedNotification.getShareHolderNo();
			loanAmount=obj.findLoanAmountByLoanNoLoanType(type, loanNo, shareHolderNo,conn);
			paidLoanAmount=obj.paidDebitLoanAmount(type, loanNo, shareHolderNo,conn);
			if(loanAmount>paidLoanAmount)
			{
				n=obj.updateChequeStatusForDebit(type,notificationId,identity,selectedNotification.getItem_loan_fdr(), chqClearDate);
			}
			else
			{
				n=-1;
			}
			
		}
		else if(type.equals("Maturity Amount(RD/FD)"))
		{
			maturityValue=obj.obtainMaturityValueByUserNo(selectedNotification.getItem_loan_fdr());
			paidMaturity=obj.obtainPaidMaturityValueByUserNo(selectedNotification.getItem_loan_fdr());
			if(maturityValue>paidMaturity)
			{
				n=obj.updateChequeStatusForDebit(type,notificationId,identity,selectedNotification.getItem_loan_fdr(), chqClearDate);
			}
			else
			{
				n=-2;
			}
		}
		else
		{
			n=0;
			n=obj.updateChequeStatusForDebit(type,notificationId,identity,selectedNotification.getItem_loan_fdr(), chqClearDate);
		}
		
		
		if(n>=1)
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Amount Released Successfully!"));
			
			obj.decreaseBankBalance(bankId, amount,conn);
			if(type.equals("Savings Account Withdrawl"))
			{
				double preAmount=obj.acconuntHolderAmountByAccountNo(selectedNotification.getItem_loan_fdr());
				Double newAmount=preAmount-amount;
				obj.updateSavingAmountByAccountNo(selectedNotification.getItem_loan_fdr(),newAmount);
				obj.updateStatusForWithDrawl(notificationId,status);
			}
			
			if(type.equals("Return Promotor Capital"))
			{
				DsaListInfo promotorDetail=obj.selectedPromotorDetail(selectedNotification.getPromotorId());
				Double newAmount=promotorDetail.getAmount()-amount;
				obj.updatePromotorAmountByID(promotorDetail.getId(),newAmount);
			}
			
			basicMethod();
			identity="";
		}
		else if(n==-1)
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("only Rs."+(loanAmount-paidLoanAmount)+" is to be paid. Please Check Or Return This Cheque!"));
		}
		else if(n==-2)
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("only Rs."+(maturityValue-paidMaturity)+" is to be paid. Please Check Or Return This Cheque!"));
		}
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
	private void addChqBounce() 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		voucherNo=obj.generateVoucherNo(branchId,"expense_table",conn);
		new DataBaseIncomeExpense().addExpense(branchId,chqReturnDate,  "Other_Dr", "Cheque", String.valueOf(amount), selectedNotification.getChequeNo(), "", 
				selectedNotification.getBankId(),selectedNotification.getChequeDate(), "Cheque Bounce Charge", "Cheque Bounce Charge", "0", voucherNo, 0,"0","","");
	}

	public void denyCheque()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId = (int) ss.getAttribute("branchId");
		String status="returned",bankId="",notificationId="",type="";
		n=0;
		bankId=selectedNotification.getBankId();
		notificationId=selectedNotification.getId();
		type=selectedNotification.getType();
		
		identity="deny";
		int x=obj.updateChequeStatusForDebit(type,notificationId,identity,selectedNotification.getItem_loan_fdr(), chqClearDate);
		if(x>=1)
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Cheque denied Successfully!"));
			if(amount>0)
			{
				addChqBounce();
			}
		
			
			if(type.equals("Savings Account Withdrawl"))
			{
				obj.updateStatusForWithDrawl(notificationId,status);
			}
			basicMethod();
			identity="";
		}
		
	}
	
	
	public ArrayList<DueDebitInfo> getDebitLoanList() {
		return debitLoanList;
	}
	public void setDebitLoanList(ArrayList<DueDebitInfo> debitLoanList) {
		this.debitLoanList = debitLoanList;
	}
	public ArrayList<DueDebitInfo> getExpenseList() {
		return expenseList;
	}
	public void setExpenseList(ArrayList<DueDebitInfo> expenseList) {
		this.expenseList = expenseList;
	}
	public ArrayList<DueDebitInfo> getFdrExpenseList() {
		return fdrExpenseList;
	}
	public void setFdrExpenseList(ArrayList<DueDebitInfo> fdrExpenseList) {
		this.fdrExpenseList = fdrExpenseList;
	}
	public ArrayList<DueDebitInfo> getFinalList() {
		return finalList;
	}
	public void setFinalList(ArrayList<DueDebitInfo> finalList) {
		this.finalList = finalList;
	}
	public DueDebitInfo getSelectedNotification() {
		return selectedNotification;
	}
	public void setSelectedNotification(DueDebitInfo selectedNotification) {
		this.selectedNotification = selectedNotification;
	}

	public Date getChqReturnDate() {
		return chqReturnDate;
	}

	public void setChqReturnDate(Date chqReturnDate) {
		this.chqReturnDate = chqReturnDate;
	}

	public Date getChqClearDate() {
		return chqClearDate;
	}

	public void setChqClearDate(Date chqClearDate) {
		this.chqClearDate = chqClearDate;
	}

	public double getAmount() {
		return amount;
	}

	public void setAmount(double amount) {
		this.amount = amount;
	}

	public String getReason() {
		return reason;
	}

	public void setReason(String reason) {
		this.reason = reason;
	}
	
	
}
