package main_package;

import java.io.Serializable;
import java.sql.Connection;
import java.util.ArrayList;

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="manageCenter")
@ViewScoped
public class ManageCenterBean implements Serializable
{
	DataBaseMethods obj=new DataBaseMethods();
	private static final long serialVersionUID = 1L;
	CenterInfo selectedcenter;
	int totalLoan, totalCenter,TotActCenter;
	ArrayList<CenterInfo> center_info;
	ArrayList<CenterInfo> activeCenter;
	ArrayList<SelectItem> dsaList;
	String centerName,centerCode,descriptoin,id,oldName,oldCode, dsaCode, centerLeaderName, centerTime;
	boolean disDsa;
	
	public ManageCenterBean() 
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		//HeaderBean hh=new HeaderBean();
		HeaderBean hb= new HeaderBean();
		String companyName= hb.getCompanyName();
		
		
		Connection conn =DataBaseConnection.JAVAConnection();
		center_info = obj.allCenterInfo(branchId,"all",conn);
		
		//if(hh.getName().equalsIgnoreCase("SHREE RAJ LAXMI FINANCE"))
		{
			centerCode=obj.centerCodeNo(branchId);
		}
//		UserInfo uu = new UserInfo();
//	String companyName=	uu.getName();
//	System.out.println("company name is in center master:"+companyName);
//		
		
		String userId=obj.userId();
		
		dsaList=obj.allDsaList(branchId,"Loan",conn);
		
//		if(obj.userType().equals("employee") )
//		{
//			dsaCode=obj.dsaCodeByEmpUserId(userId, conn);
//			disDsa=true;     
//		}
		
		String designation = DataBaseMethodsHemant.getDesignationByUname(userId);
    
  	 	
		if (obj.userType().equals("employee") 
		        && designation != null 
		        && designation.equalsIgnoreCase("BRANCH MANAGER") && companyName.equals("SUDERSHANA FINANCE"))
		{
		    // Only Branch Manager employee → false
		    disDsa = false;
		//	dsaCode=obj.dsaCodeByEmpUserId(userId, conn);
		}
		else 
		{
			if(obj.userType().equals("employee") )
				{
					dsaCode=obj.dsaCodeByEmpUserId(userId, conn);
					disDsa=true;
			}
		}		   
        
		
		totalLoan=0;
		
		for(CenterInfo cc: center_info)
		{
			totalLoan+=cc.getTotalLoan();
		}
		totalCenter=center_info.size();
		
		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public void activeBranchFilter() {
		
		activeCenter = new ArrayList<>();
		int i=0; 
		
		for(CenterInfo pp :center_info) {
			
			if(pp.getTotalLoan()>0) {
			 
               CenterInfo info=new CenterInfo();
				
				info.setId(pp.getId());
				info.setCenterName(pp.getCenterName());
				
				info.setCenterCode(pp.getCenterCode());
				info.setDescription(pp.getDescription());
				info.setGroupNo(pp.getGroupNo());
				info.setTotalLoan(pp.getTotalLoan());
				info.setDsacode(pp.getDsacode());
				info.setDsaName(pp.getDsaName());
				
				
				activeCenter.add(info);		
				
			   i++;
				
			}
			
			
			
		}
		
		
		TotActCenter=i;
		
	}
	
	
	public void addCenterInfo()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		boolean duplicate=new DataBaseMethodsDuplicate().centerDuplicacy(centerName,centerCode,conn);
		if(duplicate==true)
		{
			FacesContext fc=FacesContext.getCurrentInstance();
			fc.addMessage(null, new FacesMessage("Duplicate Center Found... Please Change Either Name Or Code"));
		}
		else
		{
			int i =obj.addCenter(branchId,centerName,centerCode,descriptoin, dsaCode,centerLeaderName,centerTime,conn);
			if(i>=1)
			{
				FacesContext fc=FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Center Added Successfully"));
				centerName=centerCode=descriptoin=centerLeaderName=centerTime="";
				center_info = obj.allCenterInfo(branchId,"all",conn);
			}
			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 editDetails()
	{
		centerName = selectedcenter.getCenterName();
		centerCode = selectedcenter.getCenterCode();
		descriptoin = selectedcenter.getDescription();
		oldName=selectedcenter.getCenterName();
		oldCode=selectedcenter.getCenterCode();
		id =  selectedcenter.id;
		dsaCode=selectedcenter.getDsacode();
		centerLeaderName=selectedcenter.getCenterLeaderName();
		centerTime=selectedcenter.getCenterTime();
	}
	public void update()
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int branchId =(int) ss.getAttribute("branchId");
		Connection conn=DataBaseConnection.JAVAConnection();
		int flag=0;
		if(centerName.equalsIgnoreCase(oldName) && centerCode.equalsIgnoreCase(oldCode))
		{
			flag=1;
		}
		else
		{
			boolean duplicate=new DataBaseMethodsDuplicate().centerDuplicacy(centerName,centerCode,conn);
			if(duplicate==true)
			{
				FacesContext fc=FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Duplicate Center Found... Please Change Either Name Or Code"));
			}
			else
			{
				flag=1;
			}
		}
		
		if(flag==1)
		{
			int n = obj.updateCenter(id,centerName,centerCode,descriptoin, dsaCode,centerLeaderName, centerTime, conn);
			if(n==1)
			{
				FacesContext fc=FacesContext.getCurrentInstance();
				fc.addMessage(null, new FacesMessage("Center Updated Successfully"));
				obj.updateDsaInGroupLoanCenterWise(id, dsaCode, conn);
				center_info = obj.allCenterInfo(branchId,"all",conn);
				try {
					conn.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				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"));
			}
		}
	}
	public void delete()
	{
		FacesContext fc=FacesContext.getCurrentInstance();
		id =  selectedcenter.getId();
		boolean chk=new DataBaseAutoCompAndDuplicate().checkCenterInAllTable(id);
		if(chk==true)
		{
			fc.addMessage(null, new FacesMessage(selectedcenter.getCenterName()+" Center is Found in some tables."));
		}
		else
		{
			int n=obj.deleteCenter(id);
			if(n>=1)
			{
				fc.addMessage(null, new FacesMessage("Center Deleted Successfully"));
			}
			else
			{
				fc.addMessage(null, new FacesMessage("An Error Occured... Please Try Again"));
			}
		}
	}
	
	public String getCenterName() {
		return centerName;
	}

	public void setCenterName(String centerName) {
		this.centerName = centerName;
	}

	public String getCenterCode() {
		return centerCode;
	}

	public void setCenterCode(String centerCode) {
		this.centerCode = centerCode;
	}

	public String getDescriptoin() {
		return descriptoin;
	}

	public void setDescriptoin(String descriptoin) {
		this.descriptoin = descriptoin;
	}

	public CenterInfo getSelectedcenter() {
		return selectedcenter;
	}

	public void setSelectedcenter(CenterInfo selectedcenter) {
		this.selectedcenter = selectedcenter;
	}

	public ArrayList<CenterInfo> getCenter_info() {
		return center_info;
	}

	public void setCenter_info(ArrayList<CenterInfo> center_info) {
		this.center_info = center_info;
	}


	public int getTotalLoan() {
		return totalLoan;
	}


	public void setTotalLoan(int totalLoan) {
		this.totalLoan = totalLoan;
	}


	public int getTotalCenter() {
		return totalCenter;
	}


	public void setTotalCenter(int totalCenter) {
		this.totalCenter = totalCenter;
	}


	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 boolean isDisDsa() {
		return disDsa;
	}


	public void setDisDsa(boolean disDsa) {
		this.disDsa = disDsa;
	}


	public String getCenterLeaderName() {
		return centerLeaderName;
	}


	public void setCenterLeaderName(String centerLeaderName) {
		this.centerLeaderName = centerLeaderName;
	}


	public String getCenterTime() {
		return centerTime;
	}


	public void setCenterTime(String centerTime) {
		this.centerTime = centerTime;
	}

	public ArrayList<CenterInfo> getActiveCenter() {
		return activeCenter;
	}

	public void setActiveCenter(ArrayList<CenterInfo> activeCenter) {
		this.activeCenter = activeCenter;
	}

	public int getTotActCenter() {
		return TotActCenter;
	}

	public void setTotActCenter(int totActCenter) {
		TotActCenter = totActCenter;
	}
}
