package main_package;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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="login")
@ViewScoped

public class LoginBean implements Serializable
{
	private static final long serialVersionUID = 1L;
	String userId,password,type, selectedSession,otp,branchUserId, backImage;
	DataBaseMethods db=new DataBaseMethods();
	ArrayList<SelectItem> loanTypeList,bankNameList, cityNameList,sessionList,payModeList;
	UserInfo selected,selectCom;
	boolean showAdmin, showDeposit,showEmployee, showTdsModule, showMsgModule, showUserApp, showAdminApp,showPersonalLoan, 
			showPropertyLoan, showVehicleLoan, showGroupLoan, showOdLoan;
	boolean showMemberOdReport, showSoftwareType, showSecureLoan, showBusinessLoan,checkBranch=false, showHighMarkReport;
	boolean masterAdmin,showLogo,overDraftModuleRender = false;
	DecimalFormat df = new DecimalFormat("##.##");
	int randomOtp;
	Date minFinYearDate, maxFinYearDate, todayDate;
	int branchId;
	String backImgCont,logo,homeLogo,tabTitle,gargLogoHref;
	List<SelectItem> branchList = new ArrayList<SelectItem>();
	DataBaseMethodTaheer dbmt = new DataBaseMethodTaheer();
	
	
	public LoginBean()
	{    
		homeLogo = "images/home.png";
	    tabTitle = "FINANCE SOFT";
	    gargLogoHref = "https://www.gargwebinfotech.com/";
	    backImgCont = "IF ANY QUERY, PLEASE CALL ON THIS NO. 6377720344, 9352197619, 0144-4059189 AND WHATS APP ON THIS NO. 9982311326, 9351199546";
	    logo="garg.png";
	    showLogo=true;
	    selected=db.firmDetailsLogo();
		    
		 if (selected != null && "aapni_logo.png".equalsIgnoreCase(selected.getLogo())) 
		 {
			    // do something	                                                      		
			 backImage="aapni_bg.jpeg";
		 }
		 else if(selected.getLogo().equalsIgnoreCase("varitas_logo.jpg") || selected.getLogo().equalsIgnoreCase("kredifree_logo.jpg"))
		 {
			 backImage="comman.jpeg"; 
		 }
		 else
		 {
			 backImage="bg-image-1.jpg";
		 } 
		 
		 if(selected.getName().equalsIgnoreCase("FINKO MICRO FINANCE PRIVATE LIMITED")) {
			 
		   backImage = "finkoBack1.png";
		   backImgCont = "For further assistance, please reach out to us at  01130446481" ;
		   logo = "logocoverphotoFinko.png";
		   showLogo=false;
		   homeLogo = "images/finko_logo.jpg";
		   tabTitle = "Finko Login Portal";
		   gargLogoHref = "www.google.com";
		 	overDraftModuleRender = true;
			
		 }
		 
		 else if(selected.getName().equalsIgnoreCase("SUDERSHANA FINANCE"))
		 {			  
			   backImgCont = "" ;
			   logo = "";
			   showLogo=false;
			   homeLogo = "images/home.png";
			   tabTitle = "Sudershana Login Portal";
			   gargLogoHref = "www.google.com";			   
	     }	      
	}
	
	public void loginUser() throws IOException, SQLException
	{
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		ss.setAttribute("companyName", selected.name);
		
		selected=db.firmDetails(branchId);
	    
		String cc=selected.getName();


		Connection conn=DataBaseConnection.JAVAConnection();
		
		if(userId.equals("g@rgwebinfo") && password.equals("grgweb1326"))
		{	
			
			ss.setAttribute("showWelcomeAdmin", true);
    		ss.setAttribute("showWelcomeEmployee", true);
    		ss.setAttribute("showSoftwareType", true);
    		ss.setAttribute("showWelcomeHighMarkReport", true);
    		ss.setAttribute("showWelcomeDeposit", false);
    		ss.setAttribute("branchId",1); 
    		ss.setAttribute("sessionFlag",true);
    		ss.setAttribute("disableEntryDate",true);
    		ss.setAttribute("companyName", selected.name);    		
    		UserInfo rr=new UserInfo();
    		ss.setAttribute("selectedDataForHeaderBean",rr);
    		ss.setAttribute("type","admin");
    		
    		ss.setAttribute("userType",selected.type);
    		
    		selectSessionDetail(conn);   
    		
			FacesContext.getCurrentInstance().getExternalContext().redirect("basicSetupDashboard.xhtml"); //"";
		}   
		
		else		
		{   			
			type=db.userAuth(userId,password, conn);
			// Login only for admin and employee usertype
			if(type.equals("admin") || type.equals("employee") )
			{
				 boolean bb=DataBaseMethods.dateTrialPeriod(conn);  //Simple Trial Period Check
				 if(bb==true)
				 {   
					branchUserId= db.branchUserId(userId,password,conn);
					
					branchList = db.branchList(branchUserId,conn);
					if(branchList.size()==0)
					{
						FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You dont have any active branch. Contact to Admin"));  
					}
					else if(branchList.size()==1)
					{
						branchId = Integer.valueOf(branchList.get(0).getValue().toString());
		        		
						branchAssign();
					}
					else 
					{
						RequestContext context = RequestContext.getCurrentInstance();
						context.execute("PF('branchDialog').show();");
					}
				 }
				 else
				 {
					 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Your trial period has been Expired, please Contact to Administrator"));
				 }
				 masterAdmin =false;
			}
               	 	    
			     else if(type.equals("masterAdmin"))
			     {
				 boolean bb=DataBaseMethods.dateTrialPeriod(conn);  //Simple Trial Period Check
				 if(bb==true)
				 {  
					branchUserId= db.branchUserId(userId,password,conn);
					
					branchList = db.branchList(branchUserId,conn);
					if(branchList.size()==0)
					{
						FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You dont have any active branch. Contact to Admin"));  
					}
					else if(branchList.size()==1)
					{
						branchId = Integer.valueOf(branchList.get(0).getValue().toString());
		        		
						branchAssign();
					}
					else 
					{   
						RequestContext context = RequestContext.getCurrentInstance();
						context.execute("PF('branchDialog').show();");
					}
				 }
				 masterAdmin = true;
			}
			else
			{
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Username Or Password Is Wrong", "Validation error"));  
			}			
		}
	}
	

	public void branchAssign() throws IOException, SQLException 
	{
		
		if(branchId==-1)
		{
			 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Select Branch First"));	
		}
		else
		{
			Connection conn = DataBaseConnection.JAVAConnection();
			String check=db.checkStatusInMessageSettingTable("OTP Login");
    		if(check.equals("active") && !userId.equalsIgnoreCase("321024") && !userId.equalsIgnoreCase("admin"))
    		{
    			randomOtp=(int) (Math.random()*999999);
 			 	String typeMsg="Your OTP is: "+randomOtp;
 			 	String concactNo=db.contactNoByUserId(userId, conn);
 			 	
 			 	boolean isDLT = dbmt.isDLTMessageApi(conn);
				if (isDLT) 
				{
					DataBaseMethodTaheer dbmt = new DataBaseMethodTaheer();
					Map<String, String> variables = new HashMap<>();
					variables.put("var", String.valueOf(randomOtp));
//					variables.put("name", String.valueOf("HEMANT"));
//					variables.put("memberno", String.valueOf("PL-10100521"));
//					variables.put("amount", String.valueOf("15500"));
                    
					dbmt.sendDLTMessage(concactNo, null, variables, conn, "otp");
//					dbmt.sendDLTMessage("9352197619", null, variables, conn, "member no");
//					dbmt.sendDLTMessage("9352197619", null, variables, conn, "loan disbursed");
//					dbmt.sendDLTMessage("9352197619", null, variables, conn, "upcoming emi");
//					dbmt.sendDLTMessage("9352197619", null, variables, conn, "loan EMI payment");
//					dbmt.sendDLTMessage("9352197619", null, variables, conn, "secure loan disbursed");
				}
				else 
				{
					db.runMessageUrl(branchId, concactNo, typeMsg, "Mesgee","1207167395060976761", conn); 
				}
 			 	
     		  //  RequestContext.getCurrentInstance().execute("PF('otpDlg').show();");
     			  RequestContext.getCurrentInstance().execute("PF('otpDlg').show(); startOtpTimer();");
     			  RequestContext.getCurrentInstance().update("otpForm");
     			 
     			  
    		}
    		
    		else
    		{
    			goToNext(conn);
    			
    		}
			
	        conn.close();	
		}
		
	}
	
	public void goToNext(Connection conn) throws IOException
	{
		HttpSession ss = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	    selected = db.firmDetails(branchId);
	    
//	    if(selected!=null)
//	    {
//	    	System.out.println("sel: "+selected.getName());
//	    }
//	    else
//	    {
//	    	System.out.println("nullllllllllllllll");
//	    }
	    
		ss.setAttribute("branchId", branchId);
		ss.setAttribute("username", userId);
		
		ss.setAttribute("type",type);
		ss.setAttribute("branchUserId",branchUserId);
		
		 
            db.insertLogDetails(userId,branchId,conn);
            loanTypeList=db.loanTypeList(conn);
     		bankNameList=db.bankNameSelectItemList(conn);
     		cityNameList=db.cityNameList(branchId,conn);
     		payModeList=db.paymentModeOptionList(conn);

     		ss.setAttribute("selectedDataForHeaderBean", selected);
     		ss.setAttribute("loanTypeList", loanTypeList);
     		ss.setAttribute("bankNameList", bankNameList);
    		ss.setAttribute("cityNameList", cityNameList);
    		ss.setAttribute("payModeList", payModeList);
             		
//    		// Detail set for header bean and use for session
    		String tds=db.checkTdsBasis(branchId,conn);
    		if(tds.equals(""))
    		{
    			showTdsModule=false;
    		}
    		else
    		{
    			showTdsModule=true;
    		}
    		
    		if(type.equalsIgnoreCase("admin")||type.equalsIgnoreCase("masterAdmin"))
    		{
    			showAdmin=true;
    			
    		}
    		else
    		{
    			showAdmin=false;
    		}

    		
    		String 	softType=db.checkSMessageApiDetailFromTable("software_type","", conn);	
    		if(softType.equalsIgnoreCase("customized"))
    		{
    			showSoftwareType=true;
    		}
    		
    		String crifNo=db.checkSMessageApiDetailFromTable("crif_no","", conn);
    		if(crifNo!=null && !crifNo.equalsIgnoreCase(""))
    		{
    			showHighMarkReport=true; 
    		}
    		else
    		{
    			showHighMarkReport=false;
    		}
    		ss.setAttribute("showMasterAdmin", masterAdmin);
    		ss.setAttribute("showWelcomeAdmin", showAdmin);
    		ss.setAttribute("showWelcomeEmployee", showEmployee);
    		ss.setAttribute("showSoftwareType", showSoftwareType);
    		ss.setAttribute("showWelcomeHighMarkReport", showHighMarkReport);
    		
    		showDeposit=db.checkDepositModuleStatus(conn);
    		ss.setAttribute("showWelcomeDeposit", showDeposit);
    		
    		
    		ss.setAttribute("sessionFlag", true);
    		selectSessionDetail(conn);
     		
			if(type.equals("admin")||type.equalsIgnoreCase("masterAdmin"))
				{
				
     			FacesContext.getCurrentInstance().getExternalContext().redirect("mainDashBoard.xhtml");
				}
     		else if(type.equals("employee"))
     		{
     			String attStatus=db.checkSMessageApiDetailFromTable("employee_attendance","", conn);
     			boolean chk=db.checkEmpAttendanceOfCurrentDate(userId);
				if(chk==true || attStatus.equalsIgnoreCase("inactive"))
				{
					FacesContext.getCurrentInstance().getExternalContext().redirect("mainDashBoard3.xhtml");
				}
				else
				{
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You Can Login After Marking of Attendance Today. Thank You..."));
				}
     		}
	}


	public void selectSessionDetail(Connection conn)
	{
        	
		sessionList=db.financialYearList(branchId,conn);
		
		Calendar now = Calendar.getInstance();
		int year = now.get(Calendar.YEAR);
		int month=now.get(Calendar.MONTH)+1;
		int day=now.get(Calendar.DAY_OF_MONTH);
		
		if(month>=4)
		{
		    selectedSession=String.valueOf(year)+"-"+String.valueOf(year+1);
		}
		
		else		
		{
			selectedSession=String.valueOf(year-1)+"-"+String.valueOf(year);
		}
		
		String arr[]=selectedSession.split("-");
		String startFinYear=arr[0];
		String endFinYear=arr[1];
		
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		ss.setAttribute("session", selectedSession);
		ss.setAttribute("currentSession", selectedSession);
		ss.setAttribute("startFinYear", startFinYear);
		ss.setAttribute("endFinYear", endFinYear);
		
		
		SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy");
		String sDate="01-04-"+startFinYear;
		String eDate=day+"-"+month+"-"+year;
		
		boolean disableEntryDate=db.checkDataFreezing(branchId,selectedSession,conn);
		try 
		{
			String userType=db.userType();
			if(userType.equals("admin") || userType.equals("masterAdmin"))
			{
				minFinYearDate=f.parse(sDate);
			}
			else
			{
				
				int backEntryDays=db.backEntryDaysForEmployee(userId, conn);
				minFinYearDate=new Date();
				if(selected.getFirm_name().contains("BHAWANA"))  /// SPECIAL CONDITION FOR BHAWANA FINANCE 12-10-2026
				{
					minFinYearDate.setDate(1);
					//showMasterAdmin=false;
				}
				else
				{
					if(backEntryDays>0)
					{
						minFinYearDate.setDate(minFinYearDate.getDate()-backEntryDays);
					}
					else
					{
						minFinYearDate.setDate(minFinYearDate.getDate()-2);
					}
				}
				
				
			}
		
			maxFinYearDate=f.parse(eDate);
		} 
		catch (ParseException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ss.setAttribute("minFinYearDate", minFinYearDate);
		ss.setAttribute("maxFinYearDate", maxFinYearDate);
				
		ss.setAttribute("disableEntryDate", disableEntryDate);
		
	}
	
	
	public void confirmOtpDetail() throws IOException, SQLException
	{
		if(otp!=null && !otp.trim().equals(""))
		{
			if(randomOtp==Integer.parseInt(otp.trim()))
			{
				Connection conn=DataBaseConnection.JAVAConnection();
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Validate Successfully!!!. Thank You..."));
				RequestContext.getCurrentInstance().execute("PF('otpDlg').hide();");
				goToNext(conn);
			}
			else
			{
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Wrong OTP !!! Please Try Again...", "Validation error"));
				HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
				ss.invalidate();
				FacesContext.getCurrentInstance().getExternalContext().redirect("loginPage.xhtml");
			}
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"OTP is Required to Login. Pleasse Enter Valid OTP Detail.", "Validation error"));
		}
	}
	
	
	public String getUserId() {
		return userId;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public UserInfo getSelected() {
		return selected;
	}

	public void setSelected(UserInfo selected) {
		this.selected = selected;
	}
	
	public String getSelectedSession() {
		return selectedSession;
	}

	public void setSelectedSession(String selectedSession) {
		this.selectedSession = selectedSession;
	}

	public ArrayList<SelectItem> getSessionList() {
		return sessionList;
	}

	public void setSessionList(ArrayList<SelectItem> sessionList) {
		this.sessionList = sessionList;
	}

	public String getOtp() {
		return otp;
	}

	public void setOtp(String otp) {
		this.otp = otp;
	}

	public boolean isShowSecureLoan() {
		return showSecureLoan;
	}

	public void setShowSecureLoan(boolean showSecureLoan) {
		this.showSecureLoan = showSecureLoan;
	}

	public boolean isShowBusinessLoan() {
		return showBusinessLoan;
	}

	public void setShowBusinessLoan(boolean showBusinessLoan) {
		this.showBusinessLoan = showBusinessLoan;
	}


	public int getBranchId() {
		return branchId;
	}





	public void setBranchId(int branchId) {
		this.branchId = branchId;
	}





	public List<SelectItem> getBranchList() {
		return branchList;
	}


	public void setBranchList(List<SelectItem> branchList) {
		this.branchList = branchList;
	}





	public String getBackImage() {
		return backImage;
	}





	public void setBackImage(String backImage) {
		this.backImage = backImage;
	}





	public boolean isShowDeposit() {
		return showDeposit;
	}





	public void setShowDeposit(boolean showDeposit) {
		this.showDeposit = showDeposit;
	}

	public boolean isMasterAdmin() {
		return masterAdmin;
	}

	public void setMasterAdmin(boolean masterAdmin) {
		this.masterAdmin = masterAdmin;
	}

	public String getBackImgCont() {
		return backImgCont;
	}

	public void setBackImgCont(String backImgCont) {
		this.backImgCont = backImgCont;
	}

	public String getLogo() {
		return logo;
	}

	public void setLogo(String logo) {
		this.logo = logo;
	}

	public boolean isShowLogo() {
		return showLogo;
	}

	public void setShowLogo(boolean showLogo) {
		this.showLogo = showLogo;
	}

	public String getHomeLogo() {
		return homeLogo;
	}

	public void setHomeLogo(String homeLogo) {
		this.homeLogo = homeLogo;
	}

	public String getTabTitle() {
		return tabTitle;
	}

	public void setTabTitle(String tabTitle) {
		this.tabTitle = tabTitle;
	}

	public String getGargLogoHref() {
		return gargLogoHref;
	}

	public void setGargLogoHref(String gargLogoHref) {
		this.gargLogoHref = gargLogoHref;
	}

	
	public boolean isOverDraftModuleRender() {
		return overDraftModuleRender;
	}

	public void setOverDraftModuleRender(boolean overDraftModuleRender) {
		this.overDraftModuleRender = overDraftModuleRender;
	}
	
}