package main_package;

import group_head_package.DataBaseIncomeExpense;

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;

@ManagedBean(name="propertyLoan")
@ViewScoped
public class PropertyLoanBean implements Serializable
{DataBaseMethods obj=new DataBaseMethods();
	private static final long serialVersionUID = 1L;
	UserInfo selectedUser,guarantorUser1,guarantoruser2;
	double emiPayment,loanAmount,interst,duration;
	String Category,registryNo,verified,shareHolderNo,plan_no,guarantor1,guarantor2,loanNo,fileCharge="0",insuranceFee="0",jamabandi,patta,authorityPatta,emiType="flat";
	boolean showFirst,ShowSecond,show,showField;
	Date requestDate;
	int frequency,discount;
	public static List<String> list,list1;
	ArrayList<SelectItem> planList,centerList;
   	String[] idProof;
   	String selectedScheme,rd_fdNo;
   	String appChqNo, appAccNo, appBankName, appBankBranch, g1ChqNo, g1AccNo, g1BankName, g1BankBranch, g2ChqNo, g2AccNo, g2BankName, g2BankBranch, center;
   	ArrayList<SelectItem> dsaList;
	String dsaCode;
	DsaListInfo dsa_info;
	double commission=0;
	int branchId;
	public PropertyLoanBean() 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		Connection conn =DataBaseConnection.JAVAConnection();
		dsaList=obj.allDsaList(branchId,"Loan",conn);
		centerList=obj.allcenter(branchId,"all",conn);
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public List<String> completeText(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		list=new DataBaseAutoCompAndDuplicate().shareHolderAllNo(branchId,name);
     	return list;
	}
	
	public void shareHolderDetails()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();

		shareHolderNo=shareHolderNo.substring(0,shareHolderNo.indexOf("/"));
		selectedUser=obj.userInfoByShareHolderNo(shareHolderNo, conn);
		if(selectedUser!=null)
		{
			show=true;
	        loanNo=obj.propertyLoanNo(branchId); 	
	        if(loanNo.equals(""))
	        {
                loanNo="1";	        	
	        }
	        requestDate=new Date(); 
	        		
	        planList=obj.allPlans(branchId,"Loan");
		}
		else
		{
			show=false;
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Invalid Share Holder No"));
		}
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void checkPlan()
	{
		interst=obj.interestByPlanNo(plan_no);
	}
	
	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);	
				
				
			}
		}
	}
	
	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(true);
		 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(true);
		 branchId = (int) ss.getAttribute("branchId");
		list=new DataBaseAutoCompAndDuplicate().shareHolderForSecondGuarantor(branchId,name,shareHolderNo,guarantor1);
     	return list;
	}
	
	public List<String> complete_RD_FD_No(String name)
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 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 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 addRequestLoan()
	{
		 HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		//double remainingCompanyCapitalAmount=obj.remainingCompanyCapitalAmount();
		Connection conn =DataBaseConnection.JAVAConnection();
		calculateEMI();
		if(guarantor1==null)
	    {
	    	guarantor1="";
	    }
	    if(guarantor2==null)
	    {
	    	guarantor2="";
	    }
	    
//	    if(loanAmount<=200000)
//	    {
	    commission=0;  /// commission credit at Loan Approve 
	    	int i=obj.addPropertyLoanRequest(branchId,shareHolderNo,guarantor1,guarantor2,loanNo,idProof,fileCharge,loanAmount,interst,
	    		    duration,frequency,emiPayment,requestDate,Category,registryNo,verified,jamabandi,patta,authorityPatta,rd_fdNo,discount,emiType, appChqNo, appAccNo, 
	    		    appBankName, appBankBranch, g1ChqNo, g1AccNo, g1BankName, g1BankBranch, g2ChqNo, g2AccNo, g2BankName, g2BankBranch,dsaCode,commission, 
	    		    insuranceFee,center, plan_no);
	    	if(i>=1)
	    	{
	    	  FacesContext fc=FacesContext.getCurrentInstance();
	    	  fc.addMessage(null, new FacesMessage("Loan Request Submit Succesfully"));
	    	  obj.increaseCompanyCapitalAmount(branchId,Double.valueOf(fileCharge),conn);
	    	  obj.increaseCompanyCapitalAmount(branchId,Double.valueOf(insuranceFee),conn);
	    	  insertFileChargeAndInsuranceFeeInIncomeTable();
	    	  selectedUser=guarantorUser1=guarantoruser2=null;
	    	  emiPayment=loanAmount=interst=duration=frequency=0;
	    	  fileCharge=insuranceFee=guarantor1=guarantor2=shareHolderNo=Category=registryNo=verified="";
	    	  idProof=null;
	    	  show=false;
	    	  return "cashInOutFlow";
	    	}
	    	else
	    	{
	    		FacesContext fc=FacesContext.getCurrentInstance();
	    		fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
	    	}
//	    }
//	    else
//		   {
//			   FacesContext fc=FacesContext.getCurrentInstance();
//			   fc.addMessage(null, new FacesMessage("Sorry! Loan Amount Can't Greater Than Rs. 2 Lac. "));
//		   }
	    try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	    return "";
	}
	
	private void insertFileChargeAndInsuranceFeeInIncomeTable() 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		 branchId = (int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		if(Integer.parseInt(fileCharge)>0)
		{
			String voucherNo=obj.generateVoucherNo(branchId,"income_table",conn);
			new DataBaseIncomeExpense().addIncome(branchId,requestDate,"Other_Cr","cash",String.valueOf(fileCharge),"","",
					"",null,"File Charge Receive","File Charge",0,"N/A",
					"0",0,loanNo,"Property Loan", voucherNo,"",0,"active",""); 
		}
		if(Integer.parseInt(insuranceFee)>0)
		{
			String voucherNo=obj.generateVoucherNo(branchId,"income_table",conn);
			new DataBaseIncomeExpense().addIncome(branchId,requestDate,"Other_Cr","cash",String.valueOf(insuranceFee),"","",
					"",null,"Insurance Fee Receive","Insurance Fee",0,"N/A",
					"0",0,loanNo,"Property Loan", voucherNo,"",0,"active","");
		}
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	
	public UserInfo getSelectedUser() {
		return selectedUser;
	}
	public void setSelectedUser(UserInfo selectedUser) {
		this.selectedUser = selectedUser;
	}
	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 double getLoanAmount() {
		return loanAmount;
	}
	public void setLoanAmount(double loanAmount) {
		this.loanAmount = loanAmount;
	}
	public double getInterst() {
		return interst;
	}
	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 void setInterst(double interst) {
		this.interst = interst;
	}
	public double getDuration() {
		return duration;
	}
	public void setDuration(double duration) {
		this.duration = duration;
	}
	public int getFrequency() {
		return frequency;
	}
	public void setFrequency(int frequency) {
		this.frequency = frequency;
	}
	public String getCategory() {
		return Category;
	}
	public void setCategory(String category) {
		Category = category;
	}
	public String getRegistryNo() {
		return registryNo;
	}
	public void setRegistryNo(String registryNo) {
		this.registryNo = registryNo;
	}
	public String getVerified() {
		return verified;
	}
	public void setVerified(String verified) {
		this.verified = verified;
	}
	public String getShareHolderNo() {
		return shareHolderNo;
	}
	public void setShareHolderNo(String shareHolderNo) {
		this.shareHolderNo = shareHolderNo;
	}
	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 boolean isShowFirst() {
		return showFirst;
	}
	public void setShowFirst(boolean showFirst) {
		this.showFirst = showFirst;
	}
	public boolean isShowSecond() {
		return ShowSecond;
	}
	public void setShowSecond(boolean showSecond) {
		ShowSecond = showSecond;
	}
	public boolean isShow() {
		return show;
	}
	public void setShow(boolean show) {
		this.show = show;
	}
	public Date getRequestDate() {
		return requestDate;
	}
	public void setRequestDate(Date requestDate) {
		this.requestDate = requestDate;
	}
	public static List<String> getList() {
		return list;
	}
	public static void setList(List<String> list) {
		PropertyLoanBean.list = list;
	}
	public static List<String> getList1() {
		return list1;
	}
	public static void setList1(List<String> list1) {
		PropertyLoanBean.list1 = list1;
	}
	public String[] getIdProof() {
		return idProof;
	}
	public void setIdProof(String[] idProof) {
		this.idProof = idProof;
	}
	public String getJamabandi() {
		return jamabandi;
	}
	public boolean isShowField() {
		return showField;
	}
	public void setShowField(boolean showField) {
		this.showField = showField;
	}
	public void setJamabandi(String jamabandi) {
		this.jamabandi = jamabandi;
	}
	public String getPatta() {
		return patta;
	}
	public void setPatta(String patta) {
		this.patta = patta;
	}
	public String getAuthorityPatta() {
		return authorityPatta;
	}
	public void setAuthorityPatta(String authorityPatta) {
		this.authorityPatta = authorityPatta;
	}
	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 getPlan_no() {
		return plan_no;
	}

	public void setPlan_no(String plan_no) {
		this.plan_no = plan_no;
	}

	public ArrayList<SelectItem> getPlanList() {
		return planList;
	}

	public void setPlanList(ArrayList<SelectItem> planList) {
		this.planList = planList;
	}

	public String getEmiType() {
		return emiType;
	}

	public void setEmiType(String emiType) {
		this.emiType = emiType;
	}

	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 getInsuranceFee() {
		return insuranceFee;
	}

	public void setInsuranceFee(String insuranceFee) {
		this.insuranceFee = insuranceFee;
	}

	public DsaListInfo getDsa_info() {
		return dsa_info;
	}

	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;
	}
	
}
