package main_package;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.primefaces.context.RequestContext;

@ManagedBean(name="pendingPersonalLoan")
@ViewScoped
public class PendingPersonalLoan implements Serializable
{
	private static final long serialVersionUID = 1L;
	ArrayList<LoanInfo> personalLoanList,vechileLoanList,propertyLoanList,grouplLoanList,finalList;
	ArrayList<LoanInfo> selectedFinalList=new ArrayList<>();
	LoanInfo selectedLoan; 
	Date approveDate=new Date(), emiDueDate=null;
	boolean showDueDateField;
	DsaListInfo commissionInfo;
	double commission=0;
	String userId;
	DataBaseMethods obj=new DataBaseMethods();
	public PendingPersonalLoan() 
	{
		userId=obj.userId();
		createList();
	}

	public void createList()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		personalLoanList=obj.pendingPersonalLoanList(branchId);
		System.out.println(personalLoanList.size());
	}
	
	public void checkDueField()
	{
		showDueDateField=true;
		/*if(selectedLoan.getFrequency().equals("12"))
		{
			showDueDateField=true;
		}
		else
		{
			showDueDateField=false;
		}*/   //Need for only monthly
	}
	public String printSanctionLoan()
    {
		selectedLoan.setEmiPaidDate(approveDate);
        if(emiDueDate!=null)
		{
			selectedLoan.setEmiPaidDate(emiDueDate);
        }
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        ss.setAttribute("selectedLoan",selectedLoan);
        RequestContext.getCurrentInstance().execute("window.open('printFormatOfSanctionNote.xhtml')");
        return "";
    }
	
	
	
	public String approveLoan()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		int i=0;
		Connection conn=DataBaseConnection.JAVAConnection();
		if(selectedFinalList.size() > 0)
		{
			for(LoanInfo tt : selectedFinalList)
			{
		if(tt.getLoanType().equals("Personal Loan"))
		{
			i=obj.updateStatusForPersonalLoan(tt.getId(),"Approve",approveDate,tt.getLoanAmount(), emiDueDate, conn);
		}
		else if(tt.getLoanType().equals("Vehicle Loan"))
		{
			i=obj.updateStatusForVechileLoan(tt.getId(),"Approve",approveDate,tt.getLoanAmount(), emiDueDate, conn);
		}
		else if(tt.getLoanType().equals("Property Loan"))
		{
			i=obj.updateStatusForPropertyLoan(tt.getId(),"Approve",approveDate,tt.getLoanAmount(), emiDueDate, conn);
		}
		else if(tt.getLoanType().equals("Group Loan"))
		{
			i=obj.updateStatusForGroupLoan(tt.getId(),"Approve",approveDate,tt.getLoanAmount(), emiDueDate, tt.getLoanNo(), tt.getSubLoanNo(), conn);
		}
		
		String loanNo="";
		if(tt.getLoanType().equals("Group Loan") || tt.getLoanType().equals("grouploan"))
		{
			loanNo=tt.getSubLoanNo();
		}
		else
		{
			loanNo=tt.getLoanNo();
		}
		
		if(i>=1)
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Loan Approved Successfully"));
			
			// File Charge Amount Add on Loan Approval
			String fcStatus=obj.checkSettingFromMasterSettingNewTable("File Charge", conn);
			if(fcStatus.equalsIgnoreCase("loan_approve"))
			{
				int z=obj.updateIncomeTableSelectedPendingEntryStatus("File Charge","active" , loanNo,conn, approveDate);
				if(z>0)
				{
					if(Double.valueOf(tt.getFileCharge())>0)
					{
						obj.increaseCompanyCapitalAmount(branchId,Double.valueOf(tt.getFileCharge()), conn);
						fc.addMessage(null, new FacesMessage("File Charge "+tt.getFileCharge() +" Rs. Add Sucessfully."));
					}
				}
			}	
			
			// Insurance Fee Amount Add on Loan Approval
			String insFeeStatus=obj.checkSettingFromMasterSettingNewTable("Insurance Fee", conn);
			if(insFeeStatus.equalsIgnoreCase("loan_approve"))
			{
				int z=obj.updateIncomeTableSelectedPendingEntryStatus("Insurance Fee","active" , loanNo,conn, approveDate);
				if(z>0)
				{
					if(Double.valueOf(tt.getInsuranceFee())>0)
					{
						obj.increaseCompanyCapitalAmount(branchId,Double.valueOf(tt.getInsuranceFee()), conn);
						fc.addMessage(null, new FacesMessage("Insurance Fee "+tt.getInsuranceFee() +" Rs. Add Sucessfully."));
					}
				}
			}	
			
			
			sendMessageForMultiple(tt.getApplicantName(),tt.getLoanNo(),tt.getLoanType(),tt.getLoanAmount(),tt.getContactNo(), conn);
	//		printSanctionLoan();
			double amount=Double.parseDouble(tt.getLoanAmount());
			if(tt.getDsacode()==null || tt.getDsacode().equals(""))
			{
				commission=0;
			}
			else
			{
				calculateCommissionForMultiple(tt.getDsacode(),tt.getPlanNo(), conn);
			}
			if(commission>0)
			{
				String emiNo="all";
				 boolean checkEntry=obj.checkDuplicacyInDsaCommissionTable(tt.getLoanNo(),emiNo);
				  if(checkEntry==false)
				  {
						String dsaName=obj.dsaNameById(tt.getDsacode(),conn);
						int j=obj.insertDataInDsaCommissionTable(branchId,tt.getLoanType(), tt.getLoanNo(), tt.getDsacode(), commission, approveDate, emiNo);
						if(j>0)
						{
							fc.addMessage(null, new FacesMessage("Commission Auto Credited to "+tt.getDsacode()+" - "+dsaName+" Rs.:- "+commission));
						}
				  }
				  try {
					conn.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			//obj.increaseSharedCompanyAmount(amount);
			
			createList();
		}
		else if(i<0)
		{
			 FacesContext fc=FacesContext.getCurrentInstance();
			 fc.addMessage(null, new FacesMessage("Sorry! Loan Request Can't Be Treated. Company's Capital Amount is '"+(-i)+"'"));
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
		}
		}
		}
		else if(selectedFinalList.size() ==0)
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Please Select Atleat One Loan No."));
		}
		
		return "checkLoanRequest";
	}

	public String approveForSingle()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		int i=0;
		Connection conn=DataBaseConnection.JAVAConnection();
		if(selectedLoan.getLoanType().equals("Personal Loan"))
		{
			i=obj.updateStatusForPersonalLoan(selectedLoan.getId(),"Approve",approveDate,selectedLoan.getLoanAmount(), emiDueDate, conn);
		}
		else if(selectedLoan.getLoanType().equals("Vehicle Loan"))
		{
			i=obj.updateStatusForVechileLoan(selectedLoan.getId(),"Approve",approveDate,selectedLoan.getLoanAmount(), emiDueDate, conn);
		}
		else if(selectedLoan.getLoanType().equals("Property Loan"))
		{
			i=obj.updateStatusForPropertyLoan(selectedLoan.getId(),"Approve",approveDate,selectedLoan.getLoanAmount(), emiDueDate, conn);
		}
		else if(selectedLoan.getLoanType().equals("Group Loan"))
		{
			i=obj.updateStatusForGroupLoan(selectedLoan.getId(),"Approve",approveDate,selectedLoan.getLoanAmount(), emiDueDate, selectedLoan.getLoanNo(),
					selectedLoan.getSubLoanNo(), conn);
			
		}
		
		String loanNo="";
		if(selectedLoan.getLoanType().equals("Group Loan") || selectedLoan.getLoanType().equals("grouploan"))
		{
			loanNo=selectedLoan.getSubLoanNo();
		}
		else
		{
			loanNo=selectedLoan.getLoanNo();
		}
		
		if(i>=1)
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Loan Approved Successfully"));
			
			// File Charge Amount Add on Loan Approval
			String fcStatus=obj.checkSettingFromMasterSettingNewTable("File Charge", conn);
			if(fcStatus.equalsIgnoreCase("loan_approve"))
			{
				int z=obj.updateIncomeTableSelectedPendingEntryStatus("File Charge","active" , loanNo,conn, approveDate);
				if(z>0)
				{
					if(Double.valueOf(selectedLoan.getFileCharge())>0)
					{
						obj.increaseCompanyCapitalAmount(branchId,Double.valueOf(selectedLoan.getFileCharge()), conn);
						fc.addMessage(null, new FacesMessage("File Charge "+selectedLoan.getFileCharge() +" Rs. Add Sucessfully."));
					}
				}
			}	
			
			// Insurance Fee Amount Add on Loan Approval
			String insFeeStatus=obj.checkSettingFromMasterSettingNewTable("Insurance Fee", conn);
			if(insFeeStatus.equalsIgnoreCase("loan_approve"))
			{
				int z=obj.updateIncomeTableSelectedPendingEntryStatus("Insurance Fee","active" , loanNo,conn, approveDate);
				if(z>0)
				{
					if(Double.valueOf(selectedLoan.getInsuranceFee())>0)
					{
						obj.increaseCompanyCapitalAmount(branchId,Double.valueOf(selectedLoan.getInsuranceFee()), conn);
						fc.addMessage(null, new FacesMessage("Insurance Fee "+selectedLoan.getInsuranceFee() +" Rs. Add Sucessfully."));
					}
				}
			}	
			
			
			sendMessage(conn);
			printSanctionLoan();
			double amount=Double.parseDouble(selectedLoan.getLoanAmount());
			if(selectedLoan.getDsacode()==null || selectedLoan.getDsacode().equals(""))
			{
				commission=0;
			}
			else
			{
				calculateCommission(conn);
			}
			if(commission>0)
			{
				String emiNo="all";
				 boolean checkEntry=obj.checkDuplicacyInDsaCommissionTable(selectedLoan.getLoanNo(),emiNo);
				  if(checkEntry==false)
				  {
						String dsaName=obj.dsaNameById(selectedLoan.getDsacode(),conn);
						int j=obj.insertDataInDsaCommissionTable(branchId,selectedLoan.getLoanType(), selectedLoan.getLoanNo(), selectedLoan.getDsacode(), commission, approveDate, emiNo);
						if(j>0)
						{
							fc.addMessage(null, new FacesMessage("Commission Auto Credited to "+selectedLoan.getDsacode()+" - "+dsaName+" Rs.:- "+commission));
						}
				  }
				  try {
					conn.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			//obj.increaseSharedCompanyAmount(amount);
			
			createList();
		}
		else if(i<0)
		{
			 FacesContext fc=FacesContext.getCurrentInstance();
			 fc.addMessage(null, new FacesMessage("Sorry! Loan Request Can't Be Treated. Company's Capital Amount is '"+(-i)+"'"));
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
		}
		return "";
		
		
	}
	
	
	private void sendMessage(Connection conn) 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		String check=obj.checkStatusInMessageSettingTable("Loan Approve");
		if(check.equals("active"))
		{
			String typeMessage="Dear "+selectedLoan.getApplicantName()+", Your "+selectedLoan.getLoanType()+" No. "+selectedLoan.getLoanNo() +", Loan Amount "+selectedLoan.getLoanAmount()+",  is Approved Sucessfully.";
			obj.runMessageUrl(branchId,selectedLoan.getContactNo(), typeMessage, "System","1207161785241372327", conn);
			typeMessage="";
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Message For This Module is not Active. Please Go to In User Block and Active Message For This Module."));
		}
	}
	
	
	private void sendMessageForMultiple(String applicantName, String loanNo, String loanType, String loanAmount, String contactNo, Connection conn) 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		String check=obj.checkStatusInMessageSettingTable("Loan Approve");
		if(check.equals("active"))
		{
			String typeMessage="Dear "+applicantName+", Your "+loanType+" No. "+loanNo +", Loan Amount "+loanAmount+",  is Approved Sucessfully.";
			obj.runMessageUrl(branchId,contactNo, typeMessage, "System","1207161785241372327", conn);
			typeMessage="";
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Message For This Module is not Active. Please Go to In User Block and Active Message For This Module."));
		}
	}
	
	public void calculateCommission(Connection conn)
	{
		if(selectedLoan.getDsacode()==null || selectedLoan.getDsacode().equals(""))
		{
			commission=0;
		}
		else
		{
			commissionInfo=obj.checkPlanCommissionDetail(selectedLoan.getPlanNo(), conn);
			if(commissionInfo==null)
			{
				// // System.out.println("null pointer: hello Loan Approve");
				commission=0;
			}
			else
			{
				// // System.out.println("method called:");
				double val=0;
				val=Double.parseDouble(selectedLoan.getLoanAmount());
				   if(commissionInfo.getCommissionBase().equalsIgnoreCase("approval"))
				   {
					   if(commissionInfo.getCommission_type().equalsIgnoreCase("percent"))
					   {
						   commission=(val/100)*commissionInfo.getCommission_value();
					   }
					   else
					   {
						   commission=commissionInfo.getCommission_value();
					   }
				   }
				   else
				   {
					   commission=0;
				   }
				   commission=Double.parseDouble(new DecimalFormat("##.##").format(commission));
			}
		}
	}
	
	
	public void calculateCommissionForMultiple(String dsaCode, String planNo, Connection conn)
	{
		if(dsaCode==null || dsaCode.equals(""))
		{
			commission=0;
		}
		else
		{
			commissionInfo=obj.checkPlanCommissionDetail(planNo, conn);
			if(commissionInfo==null)
			{
				// // System.out.println("null pointer: hello Loan Approve");
				commission=0;
			}
			else
			{
				// // System.out.println("method called:");
				double val=0;
				val=Double.parseDouble(selectedLoan.getLoanAmount());
				   if(commissionInfo.getCommissionBase().equalsIgnoreCase("approval"))
				   {
					   if(commissionInfo.getCommission_type().equalsIgnoreCase("percent"))
					   {
						   commission=(val/100)*commissionInfo.getCommission_value();
					   }
					   else
					   {
						   commission=commissionInfo.getCommission_value();
					   }
				   }
				   else
				   {
					   commission=0;
				   }
				   commission=Double.parseDouble(new DecimalFormat("##.##").format(commission));
			}
		}
	}
	public void denyLoan()
	{
		int i=0;
		Connection conn=DataBaseConnection.JAVAConnection();
		if(selectedLoan.getLoanType().equals("Personal Loan"))
		{
			i=obj.updateStatusForPersonalLoan(selectedLoan.getId(),"notApprove",approveDate,selectedLoan.getLoanAmount(), emiDueDate, conn);
		}
		else if(selectedLoan.getLoanType().equals("Vehicle Loan"))
		{
			i=obj.updateStatusForVechileLoan(selectedLoan.getId(),"notApprove",approveDate,selectedLoan.getLoanAmount(), emiDueDate, conn);
		}
		else if(selectedLoan.getLoanType().equals("Property Loan"))
		{
			i=obj.updateStatusForPropertyLoan(selectedLoan.getId(),"notApprove",approveDate,selectedLoan.getLoanAmount(), emiDueDate, conn);
		}
		else if(selectedLoan.getLoanType().equals("Group Loan"))
		{
			i=obj.updateStatusForGroupLoan(selectedLoan.getId(),"notApprove",approveDate,selectedLoan.getLoanAmount(), emiDueDate,selectedLoan.getLoanNo(),
					selectedLoan.getSubLoanNo(), conn);
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(i>=1)
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Loan Denied SuccessFully"));
		    
			createList();
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
		}
		
	}
	
	public String viewLoan()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		ss.setAttribute("selectedLoan",selectedLoan);
		if(selectedLoan.getLoanType().equals("Personal Loan"))
		{
			ss.setAttribute("pageName","editViewPersonalLoan.xhtml");
			return "viewPersonalLoan.xhtml";
		}
		else if(selectedLoan.getLoanType().equals("Vehicle Loan"))
		{
			ss.setAttribute("pageName","editViewVechileLoan.xhtml");
			return "viewVehicleLoan.xhtml";
		}
		else if(selectedLoan.getLoanType().equals("Property Loan"))
		{
			ss.setAttribute("pageName","editViewPropertyLoan.xhtml");
			return "viewPropertyLoan.xhtml";
		}
		else if(selectedLoan.getLoanType().equals("Group Loan"))
		{
			ss.setAttribute("pageName","editViewGroupLoan.xhtml");
			return "viewGroupLoan.xhtml";
		}
		return "";
	}
	
	public LoanInfo getSelectedLoan() {
		return selectedLoan;
	}
	public void setSelectedLoan(LoanInfo selectedLoan) {
		this.selectedLoan = selectedLoan;
	}
	public ArrayList<LoanInfo> getFinalList() {
		return finalList;
	}
	public void setFinalList(ArrayList<LoanInfo> finalList) {
		this.finalList = finalList;
	}
	public Date getApproveDate() {
		return approveDate;
	}
	public void setApproveDate(Date approveDate) {
		this.approveDate = approveDate;
	}

	public Date getEmiDueDate() {
		return emiDueDate;
	}

	public void setEmiDueDate(Date emiDueDate) {
		this.emiDueDate = emiDueDate;
	}

	public boolean isShowDueDateField() {
		return showDueDateField;
	}

	public void setShowDueDateField(boolean showDueDateField) {
		this.showDueDateField = showDueDateField;
	}

	public ArrayList<LoanInfo> getSelectedFinalList() {
		return selectedFinalList;
	}

	public void setSelectedFinalList(ArrayList<LoanInfo> selectedFinalList) {
		this.selectedFinalList = selectedFinalList;
	}

	public ArrayList<LoanInfo> getPersonalLoanList() {
		return personalLoanList;
	}

	public void setPersonalLoanList(ArrayList<LoanInfo> personalLoanList) {
		this.personalLoanList = personalLoanList;
	}
	
	
	
	
}
