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.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;

import org.primefaces.context.RequestContext;

@ManagedBean(name="editVehicleLoan")
public class EditVehicleLoanBean implements Serializable
{DataBaseMethods obj=new DataBaseMethods();
	private static final long serialVersionUID = 1L;
	LoanInfo viewVhclLoan;
	UserInfo user_info,guarantorUser1,guarantorUser2;
	String shareHolderNo,Category,guarantor1,guarantor2,loanNo,emiType,fileCharge,oldFilecharge, insuranceFee, oldInsuranceFee,id,selectedScheme,rd_fdNo,vechileName,model,engineNo,macNo;
	boolean showField;
	Date requestDate;
	public static List<String> list;
	double loanAmount,interst,freq,duration,emiPayment;
	String[] idProof;
	int frequency,discount;
	String appChqNo, appAccNo, appBankName, appBankBranch, g1ChqNo, g1AccNo, g1BankName, g1BankBranch, g2ChqNo, g2AccNo, g2BankName, g2BankBranch;
	ArrayList<SelectItem> dsaList,centerList;
	String dsaCode,center;
	DsaListInfo dsa_info;
	double commission=0;
	
	public EditVehicleLoanBean()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		 int branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		dsaList=obj.allDsaList(branchId,"Loan",conn);
		viewVhclLoan=(LoanInfo) ss.getAttribute("selectedLoan");
		id=viewVhclLoan.getId();
		loanNo=viewVhclLoan.getLoanNo();
		dsaCode=viewVhclLoan.getDsacode();
		commission=viewVhclLoan.getCommission();
		discount=viewVhclLoan.getDiscount();
		shareHolderNo=viewVhclLoan.getShareHolderNo();
		idProof=viewVhclLoan.getIdProof().split(",");
		loanAmount=Double.parseDouble(viewVhclLoan.getLoanAmount());
		interst=Double.parseDouble(viewVhclLoan.getLoanInterest());
		duration=Double.parseDouble(viewVhclLoan.getLoanTerm());
		frequency=Integer.parseInt(viewVhclLoan.getFrequency());
		emiPayment=viewVhclLoan.getInstallAmount();
		fileCharge=viewVhclLoan.getFileCharge();
		insuranceFee=viewVhclLoan.getInsuranceFee();
		oldInsuranceFee=insuranceFee;
		oldFilecharge=fileCharge;
		Category=viewVhclLoan.getCategory();
		vechileName=viewVhclLoan.getVechiclename();
		model=viewVhclLoan.getVechileModel();
		engineNo=viewVhclLoan.getEngineNo();
		macNo=viewVhclLoan.getMacNo();
		rd_fdNo=viewVhclLoan.getRd_fdNo();
		selectedScheme=obj.checkSchemeByUserNo(rd_fdNo);
		requestDate=viewVhclLoan.getRequestDate();
		guarantor1=viewVhclLoan.getFirstGuarantor();
		guarantor2=viewVhclLoan.getSecondGuarantor();
		emiType=viewVhclLoan.getEmiType();
		
		appAccNo=viewVhclLoan.getAppAccNo();
		appBankBranch=viewVhclLoan.getAppBankBranch();
		appBankName=viewVhclLoan.getAppBankName();
		appChqNo=viewVhclLoan.getAppChqNo();
		
		g1AccNo=viewVhclLoan.getG1AccNo();
		g1BankBranch=viewVhclLoan.getG1BankBranch();
		g1BankName=viewVhclLoan.getG1BankName();
		g1ChqNo=viewVhclLoan.getG1ChqNo();
		
		g2AccNo=viewVhclLoan.getG2AccNo();
		g2BankBranch=viewVhclLoan.getG2BankBranch();
		g2BankName=viewVhclLoan.getG2BankName();
		g2ChqNo=viewVhclLoan.getG2ChqNo();
		centerList=obj.allcenter(branchId,"all",conn);
		
		center=viewVhclLoan.getCenter();
		if(selectedScheme!=null)
		{
			showField=true;
		}
		else
		{
			showField=false;
		}
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		user_info=obj.userInfoByShareHolderNo(viewVhclLoan.getShareHolderNo(), conn);
	}
	
	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 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 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 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 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('Guarantor').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('Guarantor').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 String editRequestLoan() 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		 int branchId = (int) ss.getAttribute("branchId");
		calculateEMI();
		double capital=obj.totalCompanyCapitalAmount(branchId);
		if (guarantor1 == null)
		{
			guarantor1 = "";
		}
		if (guarantor2 == null) 
		{
			guarantor2 = "";
		}
		// System.out.println(guarantor1);
		int i = obj.updateVehicleLoanRequest(id, idProof,guarantor1, guarantor2, Category, vechileName, model, engineNo,
		macNo, fileCharge, loanAmount, interst, duration, frequency,emiPayment, requestDate, rd_fdNo,discount,appChqNo,
		appAccNo, appBankName, appBankBranch, g1ChqNo, g1AccNo, g1BankName, g1BankBranch, g2ChqNo, g2AccNo, g2BankName,
		g2BankBranch,dsaCode,commission,emiType,insuranceFee,center);
		if (i >= 1) 
		{
			 Connection conn=DataBaseConnection.JAVAConnection();
			capital=obj.totalCompanyCapitalAmount(branchId);
			if(Integer.parseInt(fileCharge)!=Integer.parseInt(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(Integer.parseInt(insuranceFee)!=Integer.parseInt(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 "editViewVechileLoan";
		} else
		{
			FacesContext fc = FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
			return "";
		}
	}
	
	public LoanInfo getViewVhclLoan() {
		return viewVhclLoan;
	}
	public void setViewVhclLoan(LoanInfo viewVhclLoan) {
		this.viewVhclLoan = viewVhclLoan;
	}
	public double getEmiPayment() {
		return emiPayment;
	}
	public void setEmiPayment(double emiPayment) {
		this.emiPayment = emiPayment;
	}
	public UserInfo getUser_info() {
		return user_info;
	}
	public void setUser_info(UserInfo user_info) {
		this.user_info = user_info;
	}
	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 String getShareHolderNo() {
		return shareHolderNo;
	}
	public void setShareHolderNo(String shareHolderNo) {
		this.shareHolderNo = shareHolderNo;
	}
	public String getCategory() {
		return Category;
	}
	public void setCategory(String category) {
		Category = category;
	}
	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 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 String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	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 getVechileName() {
		return vechileName;
	}
	public void setVechileName(String vechileName) {
		this.vechileName = vechileName;
	}
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	public String getEngineNo() {
		return engineNo;
	}
	public void setEngineNo(String engineNo) {
		this.engineNo = engineNo;
	}
	public String getMacNo() {
		return macNo;
	}
	public void setMacNo(String macNo) {
		this.macNo = macNo;
	}
	public boolean isShowField() {
		return showField;
	}
	public void setShowField(boolean showField) {
		this.showField = showField;
	}
	public Date getRequestDate() {
		return requestDate;
	}
	public void setRequestDate(Date requestDate) {
		this.requestDate = requestDate;
	}
	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 getFreq() {
		return freq;
	}
	public void setFreq(double freq) {
		this.freq = freq;
	}
	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 getDiscount() {
		return discount;
	}

	public void setDiscount(int discount) {
		this.discount = discount;
	}

	public int getFrequency() {
		return frequency;
	}
	public void setFrequency(int frequency) {
		this.frequency = frequency;
	}

	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 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;
	}
}
