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 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="editBusinessLoan")
public class EditBusinessLoanBean implements Serializable
{
	DataBaseMethods obj=new DataBaseMethods();
	private static final long serialVersionUID = 1L;
	LoanInfo viewPrsnlLoan;
	UserInfo user_info,guarantorUser1,guarantorUser2;
	String shareHolderNo,guarantor1,guarantor2,loanNo,fileCharge,oldFileCharge,insuranceFee,oldInsuranceFee,id,reason,selectedScheme,rd_fdNo;
	boolean showField;
	Date requestDate;
	public static List<String> list;
	double loanAmount,interst,duration,emiPayment, extraAmount;
	String[] idProof;
	int frequency,discount;
	String appChqNo, appAccNo, appBankName, emiType,appBankBranch, g1ChqNo, g1AccNo, g1BankName, g1BankBranch, g2ChqNo, g2AccNo, g2BankName, g2BankBranch;
	ArrayList<SelectItem> dsaList,centerList;
	String dsaCode,center;
	DsaListInfo dsa_info;
	double commission=0;
	boolean showLoanField;
	
	public EditBusinessLoanBean()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		 int branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		dsaList=obj.allDsaList(branchId,"Loan",conn);
		viewPrsnlLoan=(LoanInfo) ss.getAttribute("selectedLoan");
		
		id=viewPrsnlLoan.getId();
		loanNo=viewPrsnlLoan.getLoanNo();
		dsaCode=viewPrsnlLoan.getDsacode();
		commission=viewPrsnlLoan.getCommission();
		discount=viewPrsnlLoan.getDiscount();
		shareHolderNo=viewPrsnlLoan.getShareHolderNo();
		idProof=viewPrsnlLoan.getIdProof().split(",");
		fileCharge=viewPrsnlLoan.getFileCharge();
		insuranceFee=viewPrsnlLoan.getInsuranceFee();
		extraAmount=viewPrsnlLoan.getExtraAmt();
		oldFileCharge=fileCharge;
		oldInsuranceFee=insuranceFee;
		loanAmount=Double.parseDouble(viewPrsnlLoan.getLoanAmount());
		interst=Double.parseDouble(viewPrsnlLoan.getLoanInterest());
		duration=Double.parseDouble(viewPrsnlLoan.getLoanTerm());
		frequency=Integer.parseInt(viewPrsnlLoan.getFrequency());
		rd_fdNo=viewPrsnlLoan.getRd_fdNo();
		selectedScheme=obj.checkSchemeByUserNo(rd_fdNo);
		reason=viewPrsnlLoan.getReason();
		emiType=viewPrsnlLoan.getEmiType();
		centerList=obj.allcenter(branchId,"all",conn);
		center=viewPrsnlLoan.getCenter();
		
		appChqNo=viewPrsnlLoan.getAppChqNo();
		appAccNo=viewPrsnlLoan.getAppAccNo();
		appBankName=viewPrsnlLoan.getAppBankName();
		appBankBranch=viewPrsnlLoan.getAppBankBranch();
		
		g1AccNo=viewPrsnlLoan.getG1AccNo();
		g1BankBranch=viewPrsnlLoan.getG1BankBranch();
		g1BankName=viewPrsnlLoan.getG1BankName();
		g1ChqNo=viewPrsnlLoan.getG1ChqNo(); 
		
		g2AccNo=viewPrsnlLoan.getG2AccNo();
		g2BankBranch=viewPrsnlLoan.getG2BankBranch();
		g2BankName=viewPrsnlLoan.getG2BankName();
		g2ChqNo=viewPrsnlLoan.getG2ChqNo();
		
		requestDate=viewPrsnlLoan.getRequestDate();
		emiPayment=viewPrsnlLoan.getInstallAmount();
		guarantor1=viewPrsnlLoan.getFirstGuarantor();
		guarantor2=viewPrsnlLoan.getSecondGuarantor();
		
		if(selectedScheme!=null)
		{
			showField=true;
		}
		else
		{
			showField=false;
		}
		if(viewPrsnlLoan.getStatus().equals("pending"))
		{
			HeaderBean hh=new HeaderBean();
			showLoanField=hh.isDisableEntryDate();
		}
		else
		{
			showLoanField=true;
		}
		
		user_info=obj.userInfoByShareHolderNo(viewPrsnlLoan.getShareHolderNo(), conn);
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public List<String> completeText(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		 int branchId = (int) ss.getAttribute("branchId");
		list=new DataBaseAutoCompAndDuplicate().shareHolderAllNo(branchId,name);
     	return list;
	}

	public void calculateCommission()
	{
		dsa_info=obj.dsaInfoByCode(dsaCode,"Loan");
		double loanAmt=loanAmount;
		String commType=dsa_info.getCommission_type();
		double commVal=dsa_info.getCommission_value();
		if(commType.equals("flat"))
		{
			commission=commVal;
		}
		else
		{
			commission=(loanAmt*commVal)/100;
			commission=Double.parseDouble(new DecimalFormat("##.##").format(commission));
		}
	}
	
	public void calculateEMI()
	{
		emiPayment=discount=0;
		if(emiType.equals("reducing"))
		{
			emiPayment=obj.calculateLoanEmi(loanAmount,duration, interst, frequency);  	
			if(loanAmount==0)
			{
				emiPayment=0;discount=0;
			}
			
			if(emiPayment>0)
			{
					double totalPayment=emiPayment*duration;
					double falseInterest=totalPayment-loanAmount;
					double trueInterest=obj.totalInterestForDiscount(loanAmount,duration,interst,frequency,emiPayment);
					trueInterest=Math.round(trueInterest);
					discount=(int) (falseInterest-trueInterest);
					discount=Math.round(discount);
			}
		}
		else
		{
			emiPayment=obj.calculateLoanEmiForCalculator(loanAmount,duration, interst, frequency, "both");  	
			if(loanAmount==0)
			{
				emiPayment=0;discount=0;
			}
			
			if(emiPayment>0)
			{
				double totalPayment=emiPayment*duration;
				double falseInterest=totalPayment-loanAmount;
				double trueInterest=(loanAmount*interst*duration)/(100*frequency);
				trueInterest=Math.round(trueInterest);
				discount=(int) (falseInterest-trueInterest);
				discount=Math.round(discount);	
				
				
			}
		}
		/*emiPayment=obj.calculateLoanEmi(loanAmount,duration, interst, frequency);  	
		if(loanAmount==0)
		{
			emiPayment=0;discount=0;
		}
		
		if(emiPayment>0)
		{
				double totalPayment=emiPayment*duration;
				double falseInterest=totalPayment-loanAmount;
				double trueInterest=obj.totalInterestForDiscount(loanAmount,duration,interst,frequency,emiPayment);
				trueInterest=Math.round(trueInterest);
				discount=(int) (falseInterest-trueInterest);
				discount=Math.round(discount);
		}*/
	}
	
	public void calculateDiscount()
	{
		
	}
	
	public List<String> completeFirstGuarantorText(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		 int branchId = (int) ss.getAttribute("branchId");
		list=new DataBaseAutoCompAndDuplicate().shareHolderForFirstGuarantor(branchId,name,shareHolderNo);
     	return list;
	}
	
	public void firstGuantorDetails()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		
		guarantorUser1=obj.userInfoByShareHolderNo(guarantor1, conn);
		if(guarantorUser1!=null)
		{
			RequestContext.getCurrentInstance().execute("PF('detailDialog').show()");	
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
		 	fc.addMessage(null, new FacesMessage("First Guarantor User Not Valid"));
	        guarantor1=""; 
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void viewDetailsFirst()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		guarantorUser1=obj.userInfoByShareHolderNo(guarantor1, conn);
		if(guarantorUser1!=null)
		{
			HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			ss.setAttribute("viewselecteduser", guarantorUser1);
			
	        RequestContext.getCurrentInstance().execute("window.open('viewCompleteDetails.xhtml')");
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("First Guarantor User Not Valid"));
			guarantor1="";
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public List<String> completeSecondGuarantorText(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		 int branchId = (int) ss.getAttribute("branchId");
		list=new DataBaseAutoCompAndDuplicate().shareHolderForSecondGuarantor(branchId,name,shareHolderNo,guarantor1);
     	return list;
	}
	
	public void secondGuantorDetails()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		guarantorUser1=obj.userInfoByShareHolderNo(guarantor2, conn);
		if(guarantorUser1!=null)
		{
			RequestContext.getCurrentInstance().execute("PF('detailDialog').show()");
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Second Guarantor User Not Valid"));
			guarantor2="";
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void viewDetailsSecond()
	{
		Connection conn=DataBaseConnection.JAVAConnection();
		guarantorUser1=obj.userInfoByShareHolderNo(guarantor2, conn);
		if(guarantorUser1!=null)
		{
			HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			ss.setAttribute("viewselecteduser", guarantorUser1);
			RequestContext.getCurrentInstance().execute("window.open('viewCompleteDetails.xhtml')");
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Second Guarantor User Not Valid"));
			guarantor2="";
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public List<String> complete_RD_FD_No(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		 int branchId = (int) ss.getAttribute("branchId");
		list=new DataBaseAutoCompAndDuplicate().rd_FD_NoOfUser(branchId,name,selectedScheme,shareHolderNo);
     	return list;
	}
	
	
	public void checkScheme()
	{
		if(!selectedScheme.equals(""))
		{
			showField=true;
		}
		else
		{
			showField=false;
		}
	}
		
	public String editRequestLoan()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		 int branchId = (int) ss.getAttribute("branchId");
		double capital=obj.totalCompanyCapitalAmount(branchId);
		calculateEMI();
		if(guarantor1==null || guarantor1.equals(""))
		    {
		    	guarantor1="";
		    }
		    else
		    {
		    	if(guarantor1.contains("/"))
		    	{
		    		guarantor1=guarantor1.substring(0,guarantor1.indexOf("/"));
		    	}
		    }
		    
		    if(guarantor2==null || guarantor2.equals(""))
		    {
		    	guarantor2="";
		    }
		    else
		    {
		    	if(guarantor2.contains("/"))
		    	{
		    		guarantor2=guarantor2.substring(0,guarantor2.indexOf("/"));
		    	}
		    	
		 	}
		    
		    
		  if(fileCharge.trim().equals(""))
		   {
			   fileCharge="0";
		   }
		   if(insuranceFee.trim().equals(""))
		   {
			   insuranceFee="0";
		   }
		int i=obj.updateBusinessLoanRequest(id,idProof,guarantor1,guarantor2,fileCharge,loanAmount,interst,duration,frequency,emiPayment,requestDate,rd_fdNo,
				reason,discount,appChqNo, appAccNo, appBankName, appBankBranch, g1ChqNo, g1AccNo, g1BankName, g1BankBranch,
				g2ChqNo, g2AccNo, g2BankName, g2BankBranch,dsaCode,commission,emiType, insuranceFee,center, extraAmount);
	    if(i>=1)
	    {
	    	 Connection conn=DataBaseConnection.JAVAConnection();
	    	capital=obj.totalCompanyCapitalAmount(branchId);
			if(Double.valueOf(fileCharge)!=Double.valueOf(oldFileCharge))
	    	{
				String entryStatus=obj.findFileChargeAndInsFeeEntryStatus(loanNo,"File Charge", conn);
	    		   if(entryStatus.equalsIgnoreCase("active"))
	    		   {
	    			   obj.updateCompanyCapital(branchId,fileCharge,oldFileCharge,capital);
	    		   }
	    		obj.updateFileChargeAndInsuranceFeeInIncomeTable(loanNo,fileCharge,"File Charge", conn);
		    }
			capital=obj.totalCompanyCapitalAmount(branchId);
			if(Double.valueOf(insuranceFee)!=Double.valueOf(oldInsuranceFee))
	    	{
				 String entryStatus=obj.findFileChargeAndInsFeeEntryStatus(loanNo,"Insurance Fee", conn);
	    		   if(entryStatus.equalsIgnoreCase("active"))
	    		   {
	    				obj.updateCompanyCapital(branchId,insuranceFee,oldInsuranceFee,capital);
	    		   }
	    		obj.updateFileChargeAndInsuranceFeeInIncomeTable(loanNo,insuranceFee,"Insurance Fee", conn);
		    }
	    	FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Loan Request Updated Succesfully"));
			return "manageBusinessLoan";
	    }
	    else
	    {
	        FacesContext fc=FacesContext.getCurrentInstance();
	        fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
	        return "";
	    }
	}


	public String getGuarantor1() {
		return guarantor1;
	}
	public void setGuarantor1(String guarantor1) {
		this.guarantor1 = guarantor1;
	}
	public String getGuarantor2() {
		return guarantor2;
	}
	public void setGuarantor2(String guarantor2) {
		this.guarantor2 = guarantor2;
	}
	public UserInfo getGuarantorUser1() {
		return guarantorUser1;
	}
	public void setGuarantorUser1(UserInfo guarantorUser1) {
		this.guarantorUser1 = guarantorUser1;
	}
	public UserInfo getGuarantorUser2() {
		return guarantorUser2;
	}
	public void setGuarantorUser2(UserInfo guarantorUser2) {
		this.guarantorUser2 = guarantorUser2;
	}
	public UserInfo getUser_info() {
		return user_info;
	}
	public void setUser_info(UserInfo user_info) {
		this.user_info = user_info;
	}
	public LoanInfo getViewPrsnlLoan() {
		return viewPrsnlLoan;
	}
	public void setViewPrsnlLoan(LoanInfo viewPrsnlLoan) {
		this.viewPrsnlLoan = viewPrsnlLoan;
	}
	public Date getRequestDate() {
		return requestDate;
	}
	public void setRequestDate(Date requestDate) {
		this.requestDate = requestDate;
	}
	public boolean isShowField() {
		return showField;
	}
	public void setShowField(boolean showField) {
		this.showField = showField;
	}
	public String getReason() {
		return reason;
	}
	public void setReason(String reason) {
		this.reason = reason;
	}
	public String getSelectedScheme() {
		return selectedScheme;
	}
	public void setSelectedScheme(String selectedScheme) {
		this.selectedScheme = selectedScheme;
	}
	public String getRd_fdNo() {
		return rd_fdNo;
	}
	public void setRd_fdNo(String rd_fdNo) {
		this.rd_fdNo = rd_fdNo;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getShareHolderNo() {
		return shareHolderNo;
	}
	public void setShareHolderNo(String shareHolderNo) {
		this.shareHolderNo = shareHolderNo;
	}
	public String getLoanNo() {
		return loanNo;
	}
	public void setLoanNo(String loanNo) {
		this.loanNo = loanNo;
	}
	public String getFileCharge() {
		return fileCharge;
	}
	public void setFileCharge(String fileCharge) {
		this.fileCharge = fileCharge;
	}
	public double getLoanAmount() {
		return loanAmount;
	}
	public void setLoanAmount(double loanAmount) {
		this.loanAmount = loanAmount;
	}
	public double getInterst() {
		return interst;
	}
	public void setInterst(double interst) {
		this.interst = interst;
	}
	public double getDuration() {
		return duration;
	}
	public void setDuration(double duration) {
		this.duration = duration;
	}
	public String[] getIdProof() {
		return idProof;
	}
	public void setIdProof(String[] idProof) {
		this.idProof = idProof;
	}
	public int getFrequency() {
		return frequency;
	}
	public void setFrequency(int frequency) {
		this.frequency = frequency;
	}
	public double getEmiPayment() {
		return emiPayment;
	}
	public void setEmiPayment(double emiPayment) {
		this.emiPayment = emiPayment;
	}

	public int getDiscount() {
		return discount;
	}

	public void setDiscount(int discount) {
		this.discount = discount;
	}

	public String getOldFileCharge() {
		return oldFileCharge;
	}

	public void setOldFileCharge(String oldFileCharge) {
		this.oldFileCharge = oldFileCharge;
	}

	public String getAppChqNo() {
		return appChqNo;
	}

	public void setAppChqNo(String appChqNo) {
		this.appChqNo = appChqNo;
	}

	public String getAppAccNo() {
		return appAccNo;
	}

	public void setAppAccNo(String appAccNo) {
		this.appAccNo = appAccNo;
	}

	public String getAppBankName() {
		return appBankName;
	}

	public void setAppBankName(String appBankName) {
		this.appBankName = appBankName;
	}

	public String getAppBankBranch() {
		return appBankBranch;
	}

	public void setAppBankBranch(String appBankBranch) {
		this.appBankBranch = appBankBranch;
	}

	public String getG1ChqNo() {
		return g1ChqNo;
	}

	public void setG1ChqNo(String g1ChqNo) {
		this.g1ChqNo = g1ChqNo;
	}

	public String getG1AccNo() {
		return g1AccNo;
	}

	public void setG1AccNo(String g1AccNo) {
		this.g1AccNo = g1AccNo;
	}

	public String getG1BankName() {
		return g1BankName;
	}

	public void setG1BankName(String g1BankName) {
		this.g1BankName = g1BankName;
	}

	public String getG1BankBranch() {
		return g1BankBranch;
	}

	public void setG1BankBranch(String g1BankBranch) {
		this.g1BankBranch = g1BankBranch;
	}

	public String getG2ChqNo() {
		return g2ChqNo;
	}

	public void setG2ChqNo(String g2ChqNo) {
		this.g2ChqNo = g2ChqNo;
	}

	public String getG2AccNo() {
		return g2AccNo;
	}

	public void setG2AccNo(String g2AccNo) {
		this.g2AccNo = g2AccNo;
	}

	public String getG2BankName() {
		return g2BankName;
	}

	public void setG2BankName(String g2BankName) {
		this.g2BankName = g2BankName;
	}

	public String getG2BankBranch() {
		return g2BankBranch;
	}

	public void setG2BankBranch(String g2BankBranch) {
		this.g2BankBranch = g2BankBranch;
	}

	public ArrayList<SelectItem> getDsaList() {
		return dsaList;
	}

	public void setDsaList(ArrayList<SelectItem> dsaList) {
		this.dsaList = dsaList;
	}

	public String getDsaCode() {
		return dsaCode;
	}

	public void setDsaCode(String dsaCode) {
		this.dsaCode = dsaCode;
	}

	public double getCommission() {
		return commission;
	}

	public void setCommission(double commission) {
		this.commission = commission;
	}

	public String getEmiType() {
		return emiType;
	}

	public void setEmiType(String emiType) {
		this.emiType = emiType;
	}

	

	public String getInsuranceFee() {
		return insuranceFee;
	}

	public void setInsuranceFee(String insuranceFee) {
		this.insuranceFee = insuranceFee;
	}

	public String getOldInsuranceFee() {
		return oldInsuranceFee;
	}

	public void setOldInsuranceFee(String oldInsuranceFee) {
		this.oldInsuranceFee = oldInsuranceFee;
	}

	public static List<String> getList() {
		return list;
	}

	public static void setList(List<String> list) {
		EditPersonalLoanBean.list = list;
	}

	public DsaListInfo getDsa_info() {
		return dsa_info;
	}

	public boolean isShowLoanField() {
		return showLoanField;
	}

	public void setShowLoanField(boolean showLoanField) {
		this.showLoanField = showLoanField;
	}

	public void setDsa_info(DsaListInfo dsa_info) {
		this.dsa_info = dsa_info;
	}

	public ArrayList<SelectItem> getCenterList() {
		return centerList;
	}

	public void setCenterList(ArrayList<SelectItem> centerList) {
		this.centerList = centerList;
	}

	public String getCenter() {
		return center;
	}

	public void setCenter(String center) {
		this.center = center;
	}

	public double getExtraAmount() {
		return extraAmount;
	}

	public void setExtraAmount(double extraAmount) {
		this.extraAmount = extraAmount;
	}
}	
