package main_package;

import java.io.Serializable;
import java.sql.Connection;
import java.util.ArrayList;
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="managePlan")
@ViewScoped
public class ManagePlanBean implements Serializable
{
	String type,plan,interest, commissionType="", commissionBase="", commApplicable="no", label, penaltyBasis, emiType;
	double commissionValue=0, emiNo, penaltyAnnual, fileChargePlan, insuranceFeePlan,processingChargePlan;
	int totalEmi, loanAmount, terms, frequency, emi;
	boolean showEmiNo, showEmiList, showEmiAll, showCommission, showPenalty;
	ArrayList<DsaListInfo> emiCommissionList;
	ArrayList<SelectItem> emiList, cList;
	DataBaseMethods obj=new DataBaseMethods();
	CenterInfo selectedPlan;
	ArrayList<DsaListInfo> commissionList;
	ArrayList<CenterInfo> planList;
	String id,oldType,oldPlan,oldInterest, planType;
	String[] selectBranch;
	boolean showEmiField,showTable,showDeposit;
	ArrayList<String>list;
	List<SelectItem> branchList = new ArrayList<SelectItem>();
	DataBaseMethods db=new DataBaseMethods();

	
	public ManagePlanBean() 
	{		Connection conn = DataBaseConnection.JAVAConnection();

		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		showDeposit=(boolean) ss.getAttribute("showWelcomeDeposit");
		
		String branchUserId= (String) ss.getAttribute("branchUserId");
		branchList = db.branchList(branchUserId,conn);
		plan();
		planList=obj.allPlanInfo(branchId,"all");
		checkCommissionValid();
		showTable=true;
	}
	
	public void searchData()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		planList=obj.allPlanInfo(branchId,planType);
		showTable=true;
	}
	
	public void plan()
	{
		list=new ArrayList<>();
		
		if(showDeposit == true)
		{

			list.add("DD");
			list.add("RD");
			list.add("FD");
		}
		list.add("MIS");
		list.add("Loan");

	}
	
	
	public void editDetails()
	{
		type = selectedPlan.getType();
		plan = selectedPlan.getPlan();
		interest = selectedPlan.getInterest();
		oldType=selectedPlan.getType();
		oldPlan=selectedPlan.getPlan();
		oldInterest=selectedPlan.getInterest();
		id =  selectedPlan.getId();	
		loanAmount=selectedPlan.getLoanAmount();
		emi=selectedPlan.getEmi();
		emiType=selectedPlan.getEmiType();
		terms=selectedPlan.getTerms();
		frequency=selectedPlan.getFrequency();
		
		if(selectedPlan.getType().equalsIgnoreCase("loan"))
		{
			showPenalty=true;
			fileChargePlan=selectedPlan.getFileChargePlan();
			insuranceFeePlan=selectedPlan.getInsuranceFeePlan();
			penaltyAnnual=selectedPlan.getPenaltyAnnual();
			penaltyBasis=selectedPlan.getPenaltyBasis();
			processingChargePlan=selectedPlan.getProcessingChargePlan();
		}
		else
		{
			showPenalty=false;
		}
	}
	
	
	
	public void checkInterestRate()
	{
		if(Double.parseDouble(interest)>20 && type.equalsIgnoreCase("Loan"))
		{
			RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_INFO, "Interest Detail", "Dear User, Maximum Interest on Loan is 20% As Per Nidhi Company Rule. Thank You!!! "));
		}
	}
	
	public void update()
	{
		
		System.out.println("update hit");
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		int flag=0;
		if(type.toUpperCase().equalsIgnoreCase(oldType.toUpperCase()) && plan.toUpperCase().equalsIgnoreCase(oldPlan.toUpperCase())
				 && interest.equals(oldInterest))
		{
			flag=1;
		}  
		else
		{
			boolean duplicate=new DataBaseMethodsDuplicate().checkPlanDuplicacy(branchId,type.toUpperCase(),plan.toUpperCase(),interest,conn);
			if(duplicate==true)
			{
				FacesContext fc=FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Duplicate Plan Found... Please Check!"));
			}
			else
			{
				flag=1;
			}
		}
		if(flag==1)
		{
			int n = obj.updatePlan(id,type,plan.toUpperCase(),interest, fileChargePlan, insuranceFeePlan, penaltyAnnual, penaltyBasis,loanAmount, terms, emi, frequency, emiType,processingChargePlan);
			if(n==1)
			{
				FacesContext fc=FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Plan Updated Successfully"));
				planList = obj.allPlanInfo(branchId,planType);
				
				RequestContext.getCurrentInstance().execute("PF('editDialog').hide()");
				RequestContext.getCurrentInstance().update("form3");
				RequestContext.getCurrentInstance().update("instlmnt");
			}
			else
			{
				FacesContext fc=FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("An Error Occured...Please Try Again"));
			}
		}
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public void viewDetails()
	{
		if(selectedPlan.getType().equalsIgnoreCase("RD"))
		{
			showEmiField=true;
		}
		commissionList=obj.selectedPlanCommissionDetail(selectedPlan.getId()); 
	}
	
	public void delete()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		id =  selectedPlan.getId();
		int n=obj.deletePlan(id);
		if(n>=1)
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Plan Deleted Successfully"));
			planList=obj.allPlanInfo(branchId,planType);
		}
		else
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
		}
	}
	
	public void checkCommissionValid()
	{
		if(commApplicable.equals("yes"))
		{
			showCommission=true;
		}
		else
		{
			showCommission=false;
			commissionBase=commissionType="";
			commissionValue=0;
		}
	}
	
	public void checkLabel()
	{
		if(commissionType.equals("percent"))
		{
			label=" Percent (%)";
		}
		else
		{
			label=" Flat (Rs.)";
		}
	}
	
	public void checkSchemeType()
	{
		showPenalty=false;
		if(commApplicable.equals("yes"))
		{
			if(type.equalsIgnoreCase("RD"))
			{
				showEmiList=false;
				showEmiNo=true;
				showEmiAll=false;
				createEmiList();
			}
			else
			{
				showEmiList=false;
				showEmiAll=true;
				showEmiNo=false;
				emiNo=0;
			}
		}
		else
		{
			showEmiAll=true;
		}
		
		cList=new ArrayList<>();
		SelectItem ss1=new SelectItem();
		ss1.setValue("approval");
		ss1.setLabel("On Approval");
		cList.add(ss1);
		
		
		SelectItem ss2=new SelectItem();
		ss2.setValue("collection");
		ss2.setLabel("On Collection");
		cList.add(ss2);
		
		if(type.equalsIgnoreCase("loan"))
		{
			showPenalty=true;
			
			SelectItem ss3=new SelectItem();
			ss3.setValue("closure");
			ss3.setLabel("On Loan Closure");
			cList.add(ss3);
		}
	}
	
	public void checkCommission()
	{
		if(commissionType.equalsIgnoreCase("percent"))
		{
			if(commissionValue<0 || commissionValue>100)
			{
				commissionValue=0;
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please Enter valid Percent(%)."));
			}
		}
	}
	
	public void createEmiList()
	{
		emiList=new ArrayList<>();
		for(int i=1;i<=180;i++)
		{
			SelectItem ss=new SelectItem();
			
			ss.setLabel(String.valueOf(i));
			ss.setValue(i);
			
			emiList.add(ss);
		}
	}
	
	public void createEmiCommissionList()
	{
		if(commApplicable.equals("yes"))
		{
			// System.out.println("hello emi: "+emiNo);
			if(emiNo>0)
			{
				showEmiList=true;
				
				emiCommissionList=new ArrayList<>();
				for(int i=1;i<=emiNo;i++)
				{
					DsaListInfo ff=new DsaListInfo();
					
					ff.setEmiNo(i);
					
					emiCommissionList.add(ff);
				}	
			}
			else
			{
				showEmiList=false;
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please Select Valid EMI's in Selected Plan."));
			}
		}
	}

	public String addPlan()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		int flag=0;
		if(commApplicable.equals("yes"))
		{
			if(type.equals("RD"))
			{
				if(commissionType.equals(""))
				{
					commissionType="percent";
				}
				commissionBase="collection";
				flag=1;
			}
			
			if(!commissionType.equals("") && commissionValue>0 && !commissionBase.equals(""))
			{
				flag=1;
			}
			else
			{
				if(commissionType.equals(""))
				{
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("If Commmission Applicable On this Plan than Commission Type Can't Left Blank..."));
					flag=0;
				}
				else if(commissionBase.equals(""))
				{
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("If Commmission Applicable On this Plan than Commission Base Can't Left Blank..."));
					flag=0;
				}
				else
				{
					if(type.equals("RD"))
					{
						flag=1;
					}
					else
					{
						FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("If Commmission Applicable On this Plan than Commission Value Can't Left Blank..."));
						flag=0;
					}
				}
			}
		}
		else
		{
			commissionBase=commissionType="";
			commissionValue=0;
			flag=1;
		}
		
		for (int y = 0; y<selectBranch.length; y++) 
		{
			int branch=Integer.parseInt(selectBranch[y]);
			System.out.println(branch+"selectbranch");
		if(flag==1)
		{
			Connection conn=DataBaseConnection.JAVAConnection();
			plan=plan.toUpperCase();
			boolean check=new DataBaseMethodsDuplicate().checkPlanDuplicacy(branch,type,plan,interest,conn);
			
			if(check==false)
			{
				int i=obj.addPlan(branch,type,plan,interest, penaltyAnnual, penaltyBasis, fileChargePlan, insuranceFeePlan,loanAmount, terms, emi, frequency, emiType, processingChargePlan);
				if(i>=1)
				{
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Plan added Successfully!"));
					if(commApplicable.equals("yes"))
					{
						obj.insertInCommissionTable(type,i, commissionType, commissionValue, commissionBase,emiNo, emiCommissionList,branch);
					}
//					return "managePlan.xhtml";
				}
				else
				{
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Error Occur.Please check!"));
				}
			}
			else
			{
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Plan already exists.Please check!"));
			}
		}
		
		
		else
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Something went wrong.Please check!"));
		}
		}
		return "";
	}
	
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getPlan() {
		return plan;
	}

	public void setPlan(String plan) {
		this.plan = plan;
	}

	public String getInterest() {
		return interest;
	}

	public void setInterest(String interest) {
		this.interest = interest;
	}

	public String getCommissionType() {
		return commissionType;
	}

	public void setCommissionType(String commissionType) {
		this.commissionType = commissionType;
	}

	public String getCommissionBase() {
		return commissionBase;
	}

	public void setCommissionBase(String commissionBase) {
		this.commissionBase = commissionBase;
	}

	public double getCommissionValue() {
		return commissionValue;
	}

	public void setCommissionValue(double commissionValue) {
		this.commissionValue = commissionValue;
	}

	public double getEmiNo() {
		return emiNo;
	}

	public void setEmiNo(double emiNo) {
		this.emiNo = emiNo;
	}

	public int getTotalEmi() {
		return totalEmi;
	}

	public void setTotalEmi(int totalEmi) {
		this.totalEmi = totalEmi;
	}

	public boolean isShowEmiNo() {
		return showEmiNo;
	}

	public void setShowEmiNo(boolean showEmiNo) {
		this.showEmiNo = showEmiNo;
	}

	public boolean isShowEmiList() {
		return showEmiList;
	}

	public void setShowEmiList(boolean showEmiList) {
		this.showEmiList = showEmiList;
	}

	public boolean isShowEmiAll() {
		return showEmiAll;
	}

	public void setShowEmiAll(boolean showEmiAll) {
		this.showEmiAll = showEmiAll;
	}

	public ArrayList<DsaListInfo> getEmiCommissionList() {
		return emiCommissionList;
	}

	public void setEmiCommissionList(ArrayList<DsaListInfo> emiCommissionList) {
		this.emiCommissionList = emiCommissionList;
	}

	public ArrayList<SelectItem> getEmiList() {
		return emiList;
	}

	public void setEmiList(ArrayList<SelectItem> emiList) {
		this.emiList = emiList;
	}

	public ArrayList<SelectItem> getcList() {
		return cList;
	}

	public void setcList(ArrayList<SelectItem> cList) {
		this.cList = cList;
	}

	public String getCommApplicable() {
		return commApplicable;
	}

	public void setCommApplicable(String commApplicable) {
		this.commApplicable = commApplicable;
	}

	public boolean isShowCommission() {
		return showCommission;
	}

	public void setShowCommission(boolean showCommission) {
		this.showCommission = showCommission;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public String getPenaltyBasis() {
		return penaltyBasis;
	}

	public void setPenaltyBasis(String penaltyBasis) {
		this.penaltyBasis = penaltyBasis;
	}

	public double getPenaltyAnnual() {
		return penaltyAnnual;
	}

	public void setPenaltyAnnual(double penaltyAnnual) {
		this.penaltyAnnual = penaltyAnnual;
	}

	public boolean isShowPenalty() {
		return showPenalty;
	}

	public void setShowPenalty(boolean showPenalty) {
		this.showPenalty = showPenalty;
	}


	public DataBaseMethods getObj() {
		return obj;
	}


	public void setObj(DataBaseMethods obj) {
		this.obj = obj;
	}


	public CenterInfo getSelectedPlan() {
		return selectedPlan;
	}


	public void setSelectedPlan(CenterInfo selectedPlan) {
		this.selectedPlan = selectedPlan;
	}


	public ArrayList<DsaListInfo> getCommissionList() {
		return commissionList;
	}


	public void setCommissionList(ArrayList<DsaListInfo> commissionList) {
		this.commissionList = commissionList;
	}


	public ArrayList<CenterInfo> getPlanList() {
		return planList;
	}


	public void setPlanList(ArrayList<CenterInfo> planList) {
		this.planList = planList;
	}


	public String getId() {
		return id;
	}


	public void setId(String id) {
		this.id = id;
	}


	public String getOldType() {
		return oldType;
	}


	public void setOldType(String oldType) {
		this.oldType = oldType;
	}


	public String getOldPlan() {
		return oldPlan;
	}


	public void setOldPlan(String oldPlan) {
		this.oldPlan = oldPlan;
	}


	public String getOldInterest() {
		return oldInterest;
	}


	public void setOldInterest(String oldInterest) {
		this.oldInterest = oldInterest;
	}


	public String getPlanType() {
		return planType;
	}


	public void setPlanType(String planType) {
		this.planType = planType;
	}


	public boolean isShowEmiField() {
		return showEmiField;
	}


	public void setShowEmiField(boolean showEmiField) {
		this.showEmiField = showEmiField;
	}


	public boolean isShowTable() {
		return showTable;
	}


	public void setShowTable(boolean showTable) {
		this.showTable = showTable;
	}



	public double getFileChargePlan() {
		return fileChargePlan;
	}

	public void setFileChargePlan(double fileChargePlan) {
		this.fileChargePlan = fileChargePlan;
	}

	public double getInsuranceFeePlan() {
		return insuranceFeePlan;
	}

	public void setInsuranceFeePlan(double insuranceFeePlan) {
		this.insuranceFeePlan = insuranceFeePlan;
	}

	public int getLoanAmount() {
		return loanAmount;
	}

	public void setLoanAmount(int loanAmount) {
		this.loanAmount = loanAmount;
	}

	public int getTerms() {
		return terms;
	}

	public void setTerms(int terms) {
		this.terms = terms;
	}

	public int getFrequency() {
		return frequency;
	}

	public void setFrequency(int frequency) {
		this.frequency = frequency;
	}

	public int getEmi() {
		return emi;
	}

	public void setEmi(int emi) {
		this.emi = emi;
	}

	public String getEmiType() {
		return emiType;
	}

	public void setEmiType(String emiType) {
		this.emiType = emiType;
	}

	public double getProcessingChargePlan() {
		return processingChargePlan;
	}

	public void setProcessingChargePlan(double processingChargePlan) {
		this.processingChargePlan = processingChargePlan;
	}

	public boolean isShowDeposit() {
		return showDeposit;
	}

	public void setShowDeposit(boolean showDeposit) {
		this.showDeposit = showDeposit;
	}

	public ArrayList<String> getList() {
		return list;
	}

	public void setList(ArrayList<String> list) {
		this.list = list;
	}

	public List<SelectItem> getBranchList() {
		return branchList;
	}

	public void setBranchList(List<SelectItem> branchList) {
		this.branchList = branchList;
	}

	public String[] getSelectBranch() {
		return selectBranch;
	}

	public void setSelectBranch(String[] selectBranch) {
		this.selectBranch = selectBranch;
	}

	

	
}
