package com.sbig.ancillary.controller;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import com.sbig.ancillary.concurrentMap.PMSConcurrentMap;
import com.sbig.ancillary.dto.RoleMasterDto;
import com.sbig.ancillary.dto.UserMasterDto;
import com.sbig.ancillary.entity.EMSLoginDetails;
import com.sbig.ancillary.entity.MenuMasterTest;
import com.sbig.ancillary.entity.RegistrationPageEntity;
import com.sbig.ancillary.entity.RoleMasterTest;
import com.sbig.ancillary.entity.UserMaster;
import com.sbig.ancillary.service.LoginService;
import com.sbig.ancillary.service.RenewalRmsReportService;
import com.sbig.ancillary.service.SearchService;
import com.sbig.ancillary.util.GenerateToken;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

	Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	LoginService loginService;

	@Autowired
	PMSConcurrentMap pmsConcurrentMap;
	
	@Autowired
	SearchService searchService;
	@Autowired
	RenewalRmsReportService renewalreportService;
	
	
	@GetMapping("/Register")
	public String RegistrationPage(Model model) {
	RegistrationPageEntity regitration=	new RegistrationPageEntity();
		model.addAttribute("user",regitration);
		return "RegistrationPage";
		
	}

	@GetMapping(value = "Home")
	public String redirect(HttpServletRequest request, HttpSession session, ModelMap model) {
		// session.invalidate();
		return "redirect:/";
	}
	
	@PostMapping("/RegisterPage")
	public String RegisterRegistrationPage(@ModelAttribute("user") RegistrationPageEntity registration, Model model,RedirectAttributes redirect) {
	String message=	loginService.SaveRegistartion(registration);
	System.out.println(message);
	redirect.addFlashAttribute("message", message);
		//model.addAttribute("message", message);
		return "redirect:/Register";
		
	}
	@GetMapping("/uniqueEmpId")
	@ResponseBody
	public ResponseEntity<RegistrationPageEntity> CheckEmpIdExitOrNot(@RequestParam("empId") String Empid) {
		RegistrationPageEntity registration=null;
		registration=loginService.FindByEmpId(Empid);
		System.out.println(registration);
			return  new ResponseEntity<RegistrationPageEntity>(registration,HttpStatus.CREATED);
		
	}
	 

	@GetMapping(value = "Logout")
	public String Logout(HttpServletRequest request, HttpSession session, ModelMap model) {
		String mrcsuser = (String) session.getAttribute("user");
		pmsConcurrentMap.invalidateLogin(mrcsuser);
		session = request.getSession(false);
		if (session != null)
			session.invalidate();
		session = request.getSession(true);
		return "redirect:/Home";
	}

	@GetMapping(value = "No")
	public String No(HttpServletRequest request, HttpSession session, ModelMap model) {
		String mrcsuser = (String) session.getAttribute("user");

		if (mrcsuser != null) {

			session.removeAttribute("user");
			session.removeAttribute("userObj");
			session.removeAttribute("username");
			session.removeAttribute("rolemoduleactions");
		}
		return "redirect:/Home";
	}

//	@PostMapping("/continueLogin")
//	public String continueToLogin(HttpServletRequest request, HttpSession session, ModelMap model,
//			RedirectAttributes redirectAttrs) {
//		Boolean valid = GenerateToken.validateToken(request);
//
//		if (!valid) {
//			model.put("message", "invalid access of page");
//			model.put("already_login", "N");
//			GenerateToken.includeToken(model, request);
//			return "welcome";
//		}
//		String userId = new String((String) session.getAttribute("user"));
//
//		if (pmsConcurrentMap.getConcurrentLogin().get(userId) != null
//				&& !pmsConcurrentMap.getConcurrentLogin().get(userId).getId().equals(request.getSession().getId())) {
//			pmsConcurrentMap.invalidateLogin(userId);
//
//			pmsConcurrentMap.getLogin(userId, request.getSession());
//		}
//
//		GenerateToken.includeToken(redirectAttrs, request);
//		return "redirect:/index";
//	}

	

	@RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST })
	public String login(@ModelAttribute("userObj") UserMasterDto userObj, HttpServletRequest request,
			HttpSession session, ModelMap model, RedirectAttributes redirectAttrs) {
		RoleMasterDto rolemaster = null;
		String target = "error";
		try {
			// ------------------Verify LDAP login for catalyst user-----------------------
			if (request.getMethod().equals("GET")) {
				if (session != null && session.getAttribute("user") != null) {
					String pmsuser = (String) session.getAttribute("user");
					pmsConcurrentMap.invalidateLogin(pmsuser);
					return "redirect:/Home";
				}
			} /*
				 * else if (request.getMethod().equals("POST")) { Boolean valid =
				 * GenerateToken.validateToken(request); if (!valid) { model.put("message",
				 * "invalid access of page"); model.put("already_login", "N");
				 * GenerateToken.includeToken(model, request); return "loginPage"; }
				 * 
				 * }
				 */
			// LOGGER.info("user id: from request.getHeader:" +
			// request.getHeader("ssouser"));
			String pmsuser = request.getHeader("ssouser");
			if (!(pmsuser != null) && (!"".equals(pmsuser)) && userObj != null) {
				pmsuser = userObj.getEmpId();
			}
			// pmsuser="73722";
			// LOGGER.info("user id:going for verification:" + pmsuser);

			if ((pmsuser != null) && (!"".equals(pmsuser))) {
				UserMasterDto userData = loginService.validateUser(pmsuser);
				System.out.println(userData.toString());
				if (userData != null) {

					boolean loggedIn = pmsConcurrentMap.checkLoggedIn(pmsuser);
					if (loggedIn) {
						try {
							long lastAccessedTime = pmsConcurrentMap.getConcurrentLogin().get(pmsuser)
									.getLastAccessedTime();
						} catch (Exception e) {
							pmsConcurrentMap.invalidateLogin(pmsuser);
							loggedIn = false;
						}
					}
//					if (session.getAttribute("rolemoduleactions") == null && loggedIn == true) {
//						model.put("message",
//								"User already logged in with another session !<br>Do you want to invalidate previous session and Continue Login.");
//						setSessionData(pmsuser, userData, model, session);
//						
//						model.put("already_login", "Y");
//						GenerateToken.includeToken(model, request);
//						return "loginPage";
//
//					} else 
						if (session.getAttribute("rolemoduleactions") != null && loggedIn == true) {
						setSessionData(pmsuser, userData, model, session);
						if (userData.getRole() != null) {
							GenerateToken.includeToken(redirectAttrs, request);
							
							

							
							model.addAttribute("pmsuser1", userData);
							StoreLoginDetails(userData.getEmpId(),userData.getName());
							session.setAttribute("userData", userData.getEmpId());
							
							return "redirect:/Dashboard";

						}

					} else if (session.getAttribute("rolemoduleactions") == null && loggedIn == false) {

						pmsConcurrentMap.getLogin(pmsuser, session);

					} else {

						throw new Exception("error occurred");

					}

					setSessionData(pmsuser, userData, model, session);

					// LOGGER.info("user id:LDAP Verification successfull:" + pmsuser);
					if (userData.getRole() != null) {

						List<String> listmenudto = loginService.GetManuItem(userData.getRole());
			
						session.setAttribute("listdto", listmenudto);
							
					   
						
						GenerateToken.includeToken(redirectAttrs, request);
						session.setAttribute("pmsuser1", userData);
						session.setAttribute("userData", userData.getEmpId());
						StoreLoginDetails(userData.getEmpId(),userData.getName());
						target = "redirect:/Dashboard";

					}
				} 
			} else {

				model.put("message", "You are not authorized to use this Application.Contact Administrator.");
				// LOGGER.info("LDAP not authorized user:" + pmsuser);
				model.addAttribute("message", "You are not authorized to access the application");
				model.put("userObj", new UserMaster());
				GenerateToken.includeToken(model, request);
				model.put("already_login", "N");
				return "loginPage";

			}

		} catch (Exception e) {

			model.put("message", "You are not authorized to use this Application.Contact Administrator.");
			// LOGGER.error("LoginAction:execute():" + e.toString());
			model.put("userObj", new UserMaster());
			model.put("already_login", "N");
			GenerateToken.includeToken(model, request);
			return "loginPage";
		}

		return target;

	}
	public void StoreLoginDetails(String userId,String userName)
	{
		
		renewalreportService.ValidateLoginDetailsLog(userId, userName);
		
	}
	
	
	

	public void setSessionData(String pmsuser, UserMasterDto userData, ModelMap model, HttpSession session) {

		model.put("user", pmsuser);
		session.setAttribute("user", pmsuser);
		session.setAttribute("userObj", userData);
		session.setAttribute("username", userData.getEmpId());
		if (userData.getRole() != null) {
			if (userData.getRole() != null) {
				session.setAttribute("rolemoduleactions", userData.getRole());

			} else {
				model.put("message", "Role is not assigned to logged In User!!!Contact Administrator.");
			}
		}
	}
}<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> -->
<meta name="viewport"
	content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>EMS-Dashboard</title>
<!-- "src/main/resources/templates/Dashboard.html" -->
<link rel="stylesheet" type="text/css"
	href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
<link th:href="@{/css/sb-admin-2.min.css}" rel="stylesheet" />
<link th:href="@{/css/fontawesome-free-6.3.0-web/css/all.css}"
	rel="stylesheet" />
<link th:href="@{/css/layout.css}" rel="stylesheet" />
<link th:href="@{/css/header.css}" rel="stylesheet" />
<link th:href="@{/css/RenewalReportCardCommon.css}" rel="stylesheet" />
<link
	href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css"
	rel="stylesheet" />

<link
	href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
	rel="stylesheet"
	integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
	crossorigin="anonymous">

<script
	src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
	integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
	crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" th:src="@{/js/common2.js}"></script>
<script type="text/javascript" th:src="@{/js/index.js}"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<meta http-equiv="Content-Security-Policy"
	content="upgrade-insecure-requests">
<script
	src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.js"></script>
<script
	src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script type="text/javascript"
	src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script type="text/javascript"
	src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script type="text/javascript"
	src="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.10.20/b-1.6.1/b-colvis-1.6.1/b-html5-1.6.1/b-print-1.6.1/r-2.2.3/datatables.min.js"></script>
<script
	src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<style>
.dash-title {
	color: white;
	font-size: 15pt;
	display: block;
	margin: -10px;
}

/* .dash-sel {
	padding: 4px 10px;
	margin: 10px 0;
	display: inline-block;
	border: 1px solid #ccc;
	border-radius: 4px;
	box-sizing: border-box;
	outline: none;
}

.dash-tbl {
	width: 100%;
}

.dash-tbl tr th, td {
	padding: 1px 2px;
} */
.txt-center {
	text-align: center;
}

.transient-gradient {
	width: 100vw;
	background: linear-gradient(to bottom, rgb(255, 225, 255) 0%,
		rgb(248, 248, 248) 50%, rgb(156, 240, 255) 100%);
}

/* .das-tbl-link {
	color: black;
} */
</style>
</head>
<body style="overflow-y: hidden">
	<header id="header" th:include="common/header"> </header>
	<div id="body">
		<nav id="sidebar" th:include="common/sidebar"></nav>


		<div id="main">
			<div class="transient-gradient">



				<div class="container-fluid">

					<div class="row1">
						<!-- <div class="dashboard-container">
								<div class="dashboard-icon">
									<i class="fas fa-tachometer-alt">DashBoard</i>

								</div>
							</div> -->
						<section>
							<div class="nvabar">
								<!-- <ul class="nav nav-tabs">
									<th:block
										th:if="${#lists.contains(session.listdto ,'Dashboard')}">

										<li><a href="#tab_2" id="tab-2" data-toggle="tab"
											onclick="claim_chart();"> Renewal Summary</a></li>	
								</ul> -->

								<nav>
									<div class="nav nav-tabs nav-fill" id="nav-tab" role="tablist">
										<a class="nav-item nav-link active" id="rSum"
											data-value="rSum" data-toggle="tab" href="#nav-home"
											role="tab" aria-controls="nav-home" aria-selected="true">Renewal
											Summary</a> <a class="nav-item nav-link" id="productSum"
											data-value="productSum" data-toggle="tab" href="#nav-profile"
											role="tab" aria-controls="nav-profile" aria-selected="false">Product
											Wise Summary</a>
										<!--                       <a class="nav-item nav-link" id="newtabyet" data-value = "new tab" data-toggle="tab" href="#nav-profile" role="tab1" aria-controls="nav-profile" aria-selected="false">New TAB LOB</a> -->
									</div>
								</nav>

								<div class="grid-container">


									<div class="dash-section dropdown-box">
										<label for="yearMCRS">Year:</label> <select id="yearMCRS"
											class="dash-sel" name="Lob" required="required">
											<option value="">Year</option>
											<!-- Add your options here -->
										</select>
									</div>

									<div class="dash-section dropdown-box">
										<label for="month">Month:</label> <select id="month"
											class="dash-sel" name="month" required>
											<option value="">Month</option>
											<option th:each="monthIndex : ${#numbers.sequence(3, 15)}"
												th:value="${(monthIndex % 12) + 1}"
												th:selected="${monthIndex % 12 == currentMonth.ordinal() and (currentYear == (monthIndex < 12 ? currentYear - 1 : currentYear))}">
												<span
													th:text="${T(java.time.Month).values()[(monthIndex % 12) ].getDisplayName(T(java.time.format.TextStyle).FULL, T(java.util.Locale).US)}"></span>
											</option>
										</select>
									</div>

									<div class="dash-section dropdown-box">
										<label for="lobMcrs">Lob:</label> <select id="lobMcrs"
											class="dash-sel" name="Lob" required="required">
											<option value="">Lob</option>
											<option value="Motor">Motor</option>
											<option value="Health">Health</option>
											<option value="Sme">Other-Lob</option>
										</select>
									</div>

									<!-- <th:block
									th:if="${session.pmsuser1.RoleName == 'Renewal Coordinate' || session.pmsuser1.RoleName == 'Regional Head'}">
									<div class="dash-section dropdown-box">
										<label for="yearMCRS">Product:</label> <select id="yearMCRS"
											class="dash-sel" name="Lob" required="required">
											<option value="">Product</option>
											Add your options here
										</select>
									</div>
								</th:block> -->

									<th:block
										th:if="${session.pmsuser1.RoleName == 'National Manager' || session.pmsuser1.RoleName == 'Admin' || session.pmsuser1.RoleName == 'CBO'}">
										<div class="dash-section dropdown-box">
											<label for="Region">Region:</label> <select id="region"
												class="dash-sel" name="region" required="required">
												<option value="">Region:</option>
												<!-- Add your options here -->
												<option th:each="amountBy : ${region1}"
													th:value="${amountBy[0]}" th:text="${amountBy[0]}"></option>
											</select>
										</div>
									</th:block>

									<th:block
									
									th:if="${session.pmsuser1.RoleName == 'Renewal Coordinate' || session.pmsuser1.RoleName == 'Regional Head' || session.pmsuser1.RoleName == 'National Manager'||session.pmsuser1.RoleName == 'Admin'||session.pmsuser1.RoleName == 'National Manager(All Region Access)'}">
<!-- th:if="${session.pmsuser1.RoleName == 'Renewal Coordinate' || session.pmsuser1.RoleName == 'Regional Head' || session.pmsuser1.RoleName == 'National Manager'||session.pmsuser1.RoleName == 'Admin'||session.pmsuser1.RoleName == 'National Manager(All Region Access)' || insiderole == 'Sales User'}"> -->
									
										
										<div class="dash-section dropdown-box">
											<label for="Circle">Circle:</label> <select id="circle"
												class="dash-sel" name="circle" required="required">
												<option value="">Circle</option>

												<option th:each="amountBy : ${region}"
													th:value="${amountBy[1]}" th:text="${amountBy[1]}"></option>
											</select>
										</div>
									</th:block>

									<!-- <th:block th:if="${session.pmsuser1.RoleName == 'Renewal Coordinate' || session.pmsuser1.RoleName == 'Regional Head' || session.pmsuser1.RoleName == 'Sales User'}">
								<div id="smname" class="dash-section dropdown-box">
									<label for="ManagerMcrs">SM Name:</label> <select
										id="ManagerMcrs" class="dash-sel" name="ManagerMcrs"
										required="required">
										<option value="">SM Name</option>
										<option value="All">All</option>
										<option th:each="amountBy : ${uniqueManager}"
											th:value="${amountBy.empCode}"
											th:text="${amountBy.fullName}"></option>
									</select>
								</div>
								</th:block> -->

								</div>

								<div id="loadingIndicator">

									<div class="loading-spinner"></div>
									<span class="loading-text">Loading...</span>
								</div>
								<br>
								<div id="tab_2" class="nabvar1"></div>
								<div id="tab_3" class="col-md-12 form-group"></div>
								<div id="noDataMessage" class="col-md-12 form-group"></div>

							</div>


						</section>
					</div>

				</div>
			</div>
		</div>
	</div>
	<!-- <footer id="footer"></footer> -->
	<!-- Scripts -->
	<script th:inline="javascript">
// 	document.addEventListener("DOMContentLoaded", function () {
//         // Get the current year and month
//         var currentDate = new Date();
//         var currentYear = currentDate.getFullYear();
//         var currentMonth = currentDate.getMonth(); // January is 0, December is 11

//         // Populate the year dropdown with the current year and the next year
        
//         var yearDropdown = document.getElementById("yearMCRS");
//         if(currentMonth >= 3){
//         for (var year = currentYear; year <= currentYear + 1; year++) {
//             var option = document.createElement("option");
//             option.value = year;
//             option.textContent = year;
//             yearDropdown.appendChild(option);
//         }
//         }
//         else
//         {
//         	 for (var year = currentYear-1; year <= currentYear; year++) {
//                  var option = document.createElement("option");
//                  option.value = year;
//                  option.textContent = year;
//                  yearDropdown.appendChild(option);
//              }	
//         }

//         // Function to populate the month dropdown based on the selected year
//         function populateMonthDropdown(selectedYear) {
//             var monthDropdown = document.getElementById("month");
//             monthDropdown.innerHTML = '<option value="">Month</option>';// Clear existing options

//             var startMonth = 0; // January
//             var endMonth = 11;  // December

//             if (selectedYear === currentYear && currentMonth < 3) {
        
//                 endMonth = currentMonth+3;
//             }
//             else if(selectedYear === currentYear && currentMonth >= 3)
//             {
//             	startMonth = 3;
//             }
//             else if (selectedYear === currentYear + 1) {
//                 endMonth = currentMonth; 
//             }
//             else if (selectedYear === currentYear - 1) {
//             	startMonth = 0;
//             }

//             for (var monthIndex = startMonth; monthIndex <= endMonth; monthIndex++) {
//                 var option = document.createElement("option");
//                 option.value = monthIndex + 1; // Months are 1-based
//                 option.textContent = new Date(0, monthIndex).toLocaleString('en-US', { month: 'long' });
//                 monthDropdown.appendChild(option);
//             }
//         }

//         // Initial population of month dropdown based on the current year
//         populateMonthDropdown(currentYear);

//         // Listen for changes in the year dropdown
//         yearDropdown.addEventListener("change", function () {
//             var selectedYear = parseInt(yearDropdown.value, 10);
//             populateMonthDropdown(selectedYear);
//         });
//     });

	document.addEventListener("DOMContentLoaded", function () {
    // Get the current year
    var currentDate = new Date();
    var currentYear = currentDate.getFullYear();

    // Populate the year dropdown with 2024 and 2025
    var yearDropdown = document.getElementById("yearMCRS");
    for (var year = 2024; year <= 2025; year++) {
        var option = document.createElement("option");
        option.value = year;
        option.textContent = year;
        yearDropdown.appendChild(option);
    }

    // Function to populate the month dropdown based on the selected year
    function populateMonthDropdown(selectedYear) {
        var monthDropdown = document.getElementById("month");
        monthDropdown.innerHTML = '<option value="">Select Month</option>';

        for (var monthIndex = 0; monthIndex < 12; monthIndex++) {
            var option = document.createElement("option");
            option.value = monthIndex + 1;
            option.textContent = new Date(0, monthIndex).toLocaleString('en-US', { month: 'long' });
            monthDropdown.appendChild(option);
        }
    }

    // Initial population of month dropdown based on the current year
    populateMonthDropdown(currentYear);

    // Listen for changes in the year dropdown
    yearDropdown.addEventListener("change", function () {
        var selectedYear = parseInt(yearDropdown.value, 10);
        populateMonthDropdown(selectedYear);
    });
});



	function getValue()
	{
	var totalPolicynumber = [[${Totalpolicynumber}]];
	var totalRenewal = [[${TotalRenewal}]];    
	var totalNotRenewal = [[${TotalNotRenewal}]];	
	}
	var renewalPercentage = ((totalRenewal / totalPolicyNumber) * 100).toFixed(2);  
	var notRenewalPercentage = ((totalNotRenewal / totalPolicyNumber) * 100).toFixed(2);       
	$('#renewedCount').text(totalRenewal + ' (' + renewalPercentage + '%)');  
	$('#notRenewedCount').text(totalNotRenewal + ' (' + notRenewalPercentage + '%)');
	</script>
	<script>
	const monthDropdown = document.getElementById('month');
	const productTypeDropdown = document.getElementById('lobMcrs');
	const YearTypeDropdown = document.getElementById('yearMCRS');
	const ManagerMcrsDropdown = document.getElementById('ManagerMcrs');
	const RegionDropdown = document.getElementById('region');
	console.log(RegionDropdown);
	const CircleDropdown = document.getElementById('circle');
	console.log(CircleDropdown);
	const naviTab = document.getElementById('nav-tab');

	// Add change event listeners to both dropdowns
	monthDropdown.addEventListener('change', handleDropdownChange);
	productTypeDropdown.addEventListener('change', handleDropdownChange);
	YearTypeDropdown.addEventListener('change', handleDropdownChange);
	

	    if (ManagerMcrsDropdown) {
	        ManagerMcrsDropdown.addEventListener('change', handleDropdownChange);
	    }
	    if (RegionDropdown) {
	        RegionDropdown.addEventListener('change', handleDropdownChange);
	    }
	    if (CircleDropdown) {
	        CircleDropdown.addEventListener('change', handleDropdownChange);
	    }

	    function handleDropdownChange(event) {
	        const selectedValue = event.target.value;

	        if (!selectedValue) {
	            processDropdownChange('All');
	        } else {
	            processDropdownChange(selectedValue);
	        }
	    }

	    function processDropdownChange(value) {
	        if (value === null) {
	            console.log('No value selected');
	            // Additional handling for no value selected
	        } else {
	            console.log(`Selected value: ${value}`);
	            // Additional handling for a valid selected value
	        }
	    }
	
	 $(".nav-tabs").click(function(){
		  var tabval = $(".active").attr("data-value");
		  if(tabval == 'rSum'){
			  $('#smname').addClass('d-none');
		      $('#tab_2').addClass('d-none');
		      $('#tab_3').removeClass('d-none');
		  }
		  else{
			  $('#smname').removeClass('d-none');
			  $('#tab_2').removeClass('d-none');
		      $('#tab_3').addClass('d-none');
		  }
		  });

	function handleDropdownChange() {
	  const selectedMonth = monthDropdown.value;
	  const selectedProductType = productTypeDropdown.value;
	  const YearProductType = YearTypeDropdown.value;
	  const ManagerMcrsDropType = ManagerMcrsDropdown && ManagerMcrsDropdown.value !== undefined ? ManagerMcrsDropdown.value : 'All';
	  //const ManagerMcrsDropType = ManagerMcrsDropdown.value;
	  const RegionDropdropType = RegionDropdown && RegionDropdown.value !== undefined ? RegionDropdown.value : 'All';
	  const CircleMcrsDropType = CircleDropdown && CircleDropdown.value !== undefined ? CircleDropdown.value : 'All';
	 // const RegionDropdropType = RegionDropdown.value;
	  //const CircleMcrsDropType = CircleDropdown.value;
	  
 var tabval = $(".active").attr("data-value");
	  
	  // Check if both selections re made
	  if(tabval == "rSum"){
		  if (selectedMonth && selectedProductType && YearProductType && ManagerMcrsDropType && RegionDropdropType && CircleMcrsDropType) {
			    fetchData1(selectedMonth, selectedProductType,YearProductType,ManagerMcrsDropType,RegionDropdropType,CircleMcrsDropType);
			  }
		  }
	 // }
	  else{
		  if (selectedMonth && selectedProductType && YearProductType) {
			  fetchData1(selectedMonth, selectedProductType,YearProductType,ManagerMcrsDropType,RegionDropdropType,CircleMcrsDropType);
			  }
		  }
	}
	
	 
	 function fetchData1(month, lobMcrs,yearMCRS,ManagerMcrs,region,circle) {
		    var loadingIndicator = document.getElementById("loadingIndicator");
		   var noDataMessage = document.getElementById('noDataMessage');
		    noDataMessage.style.display = "none";
		    loadingIndicator.style.display = "block";
		    var tabval = $(".active").attr("data-value");

		    fetch(`/EMS/lobReport?month=${month}&lobMcrs=${lobMcrs}&yearMCRS=${yearMCRS}&ManagerMcrs=${ManagerMcrs}&region=${region}&circle=${circle}&tabval=${tabval}`)
		        .then(response => response.text())
		        .then(data => {
		        	console.log(data);
		            if (data.trim() === "") {
		                // Display "Policy Details Not Found" message when data is empty
		                noDataMessage.style.display = "block";
		                noDataMessage.innerHTML = data;
		                
		            } else {
		            	if(tabval == "rSum")
		                // Display the fetched data when available
		                document.getElementById('tab_2').innerHTML = data;
		            	else
		            	document.getElementById('tab_3').innerHTML = data;	
		            }
		            loadingIndicator.style.display = "none";
		            getPaiChart();
		        })
		        .catch(error => {
		            loadingIndicator.style.display = "none";
		        });
		}
	 
	 
	function displayData(data) {
		  // Clear the existing table rows
		  $("#filtertable").show();
		  $('#filtertable tbody').empty();
		 // $('#result').html('<pre>' + JSON.stringify(data, null, 2) + '</pre>');
		  // Iterate over the data and create table rows dynamically
		  //for (var i = 0; i < data.length; i++) {
			   $('#result').val(data.SecondarySmName);
		    var row = $('<tr></tr>');
		    row.append('<td>' + data.SecondarySmName + '</td>');
		    console.log(result)
		    row.append('<td>' + data.TotalPolicyNumber + '</td>');
		    row.append('<td>' + data.RenewadPolicyNumber + '</td>');
		    row.append('<td>' + data.NotRenewedPolicyNumber + '</td>');
		    $('#filtertable tbody').append(row);
		  }


	
	
	$(document).ready(function() {
			$('#filtertable').DataTable({
				lengthMenu : [ 5, 10, 50, 100, 200 ],
				scrollX : true,
				scrollY : 200,			

			});
		});
	
	var myChart; // Declare myChart globally for later use

	// Call this function to initialize the pie chart
	function getPaiChart() {
    var totalNotRenewal = document.getElementById("TotalNotRenewal").value;
    var totalRenewal = document.getElementById("TotalRenewal").value;
    var totalPolicynumber = document.getElementById("Totalpolicynumber").value;

    var ctx = document.getElementById('policyChart').getContext('2d');
    
    var data = {
        labels: ['Renewed', 'Not Renewed'],
        datasets: [{
            data: [totalRenewal, totalNotRenewal],
            backgroundColor: ['#36A2EB', '#FF6384'],
            borderColor: ['#1E90FF', '#FF1493'],
            borderWidth: 1,
            barThickness: 50,
            hoverBackgroundColor: ['#1E90FF', '#FF1493'],
            hoverBorderColor: ['#104E8B', '#8B0A50'],
            hoverBorderWidth: 2,
        }]
    };

    var options = {
        responsive: true,
        title: {
            display: true,
            text: 'Policy Renewal Status',
            fontSize: 20,
            fontColor: '#333',
        },
        tooltips: {
            callbacks: {
                label: function (tooltipItem, data) {
                    var dataset = data.datasets[tooltipItem.datasetIndex];
                    var total = dataset.data.reduce(function (previousValue, currentValue, currentIndex, array) {
                        return previousValue + currentValue;
                    });
                    var currentValue = dataset.data[tooltipItem.index];
                    var percentage = Math.floor(((currentValue / total) * 100) + 0.5);
                    return data.labels[tooltipItem.index] + ': ' + currentValue + ' (' + percentage + '%)';
                }
            }
        },
        plugins: {
            datalabels: {
                formatter: (value, ctx) => {
                    let dataset = ctx.chart.data.datasets[ctx.datasetIndex];
                    let total = dataset.data.reduce((previousValue, currentValue) => previousValue + currentValue);
                    let currentValue = dataset.data[ctx.dataIndex];
                    let percentage = Math.floor((currentValue / total) * 100 + 0.5);
                    return `${percentage}%`;
                },
                color: 'auto',
            }
        },
        animation: {
            duration: 2000,
            easing: 'easeInOutBounce',
        },
        scales: {
            xAxes: [{
                gridLines: {
                    display: false,
                },
                ticks: {
                    fontSize: 14,
                    fontColor: '#333',
                }
            }],
            yAxes: [{
                gridLines: {
                    display: true,
                    color: '#ccc',
                },
                ticks: {
                    beginAtZero: true,
                    fontSize: 14,
                    fontColor: '#333',
                }
            }]
        }
    };

    // Check if chart already exists
    if (myChart) {
        myChart.destroy();
    }

    myChart = new Chart(ctx, {
        type: 'bar',
        data: data,
        options: options
    });

    $('td.owner-account').on('click', function() {
        var $clickedRow = $(this).closest('tr');
        var totalRenewal = parseInt($clickedRow.find('.data-renewed').text());
        var totalNotRenewal = parseInt($clickedRow.find('.data-notrenewed').text());

        console.log(totalRenewal);
        console.log(totalNotRenewal);

        // Update pie chart data
        myChart.data.datasets[0].data = [totalRenewal, totalNotRenewal];
        
        // Force update with animation
        myChart.update({
            duration: 2000,
            easing: 'easeInOutBounce'
        });
    });
}


	// Example usage:
	// You can call the updatePaiChart function with new values when needed
	// updatePaiChart(newTotalRenewalValue, newTotalNotRenewalValue);
	
	
	
	
	
	      function getLineChart() {
	    	  var months = [
	    	    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
	    	    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
	    	  ];

	    	  var renewalData = new Array(12).fill(0);
	    	  var notRenewalData = new Array(12).fill(0);
	    	  var totalPoliciesData = new Array(12).fill(0);
	    	  var currentYear1=new Date().getFullYear();
	    	  var ctx = $('#policyChart')[0].getContext('2d');
	    	  var myChart = new Chart(ctx, {
	    	    type: 'line',
	    	    data: {
	    	      labels: months,
	    	      datasets: [
	    	        {
	    	          label: 'Renewed',
	    	          data: renewalData,
	    	          borderColor: 'blue',
	    	          fill: false,
	    	        },
	    	        {
	    	          label: 'Not Renewed',
	    	          data: notRenewalData,
	    	          borderColor: 'red',
	    	          fill: false,
	    	        },
	    	        {
	    	          label: 'Total Policies',
	    	          data: totalPoliciesData,
	    	          borderColor: 'green',
	    	          fill: false,
	    	        },
	    	      ],
	    	    },
	    	    options: {
	    	      responsive: true,
	    	      title: {
	    	        display: true,
	    	        text: 'Monthly Policy Renewal Status for '+currentYear1,
	    	      },
	    	    },
	    	  });
	
	    	  $('td.owner-account').on('click', function() {
	    	    var $clickedRow = $(this).closest('tr');
	    	    var manager_code = parseInt($clickedRow.find('.manager_code').text());
	    	    var lobMcrs = document.getElementById("lobMcrs").value;
	    	    var SMName = parseInt($clickedRow.find('.owner-account').text());
	    	    document.getElementById("output").textContent=SMName;
	    	    console.log(SMName);

	    	    function fetchData(manager_code, lobMcrs) {
	    	      fetch(`/EMS/lob1?manager_code=${manager_code}&lobMcrs=${lobMcrs}`)
	    	        .then(response => response.json()) // Assuming the response is in JSON format
	    	        .then(data => {
	    	        	console.log(data);
	    	  
	    	          data.forEach(function(item) {
	    	        	  console.log(item);
	    	            var monthYear = item.expirePolicyMonth;
	    	            console.log(monthYear);
	    	            var regexResult = /(\D+)(\d{2})/.exec(monthYear);
	    	            console.log(regexResult);
	    	            if (regexResult) {
	    	              var monthYear = regexResult[1] ; 
	    	              var monthAndYear=monthYear.split('-')// Combine month and year
	    	              var month=monthAndYear[0];
	    	              var year=regexResult[2];
	    	              var currentYear=new Date().getFullYear()%100;
	    	              var monthIndex = months.indexOf(month);
	    	              console.log(month);
	    	              console.log(monthIndex);
	    	              console.log(year);
	    	              console.log(currentYear);
						 if(year == currentYear)
							{ 					
	    	              if (monthIndex !== -1) {
	    	            	 console.log(renewalData);
	    	                // Update the data arrays with the retrieved data
	    	                renewalData[monthIndex] = parseInt(item.renewadPolicyNumber);
	    	                notRenewalData[monthIndex] = parseInt(item.notRenewedPolicyNumber);
	    	                totalPoliciesData[monthIndex] = parseInt(item.totalPolicyNumber);
	    	                myChart.data.datasets[0].data[monthIndex] = renewalData[monthIndex];   
	    	                myChart.data.datasets[1].data[monthIndex] = notRenewalData[monthIndex];  
	    	                myChart.data.datasets[2].data[monthIndex] = totalPoliciesData[monthIndex];
	    	               // myChart.data.datasets[0].data[monthIndex] = renewalData[monthIndex];   myChart.data.datasets[1].data[monthIndex] = notRenewalData[monthIndex];   myChart.data.datasets[2].data[monthIndex] = totalPoliciesData[monthIndex];

	    	                console.log(`Month: ${month}, Year: ${year}`);  
	    	                console.log(`Renewed: ${renewalData[monthIndex]}`); 
	    	                console.log(`Not Renewed: ${notRenewalData[monthIndex]}`);  
	    	                console.log(`Total Policies: ${totalPoliciesData[monthIndex]}`);
	    	             }
	    	            }
	    	            }
	    	          });

	    	          // Update the chart with the new data
	    	          myChart.update();
	    	          console.log(renewalData);
	    	        })
	    	        .catch(error => {
	    	          console.error("Error fetching data:", error);
	    	        });
	    	    }

	    	    fetchData(manager_code, lobMcrs);
	    	  });
	    	}

	    	// Call the function to set up the initial chart and event handling
	    	getLineChart();
	    	
	    	function FamesSearchDashboard() {
	    		console.log("Fames Home Page");
	    		$.ajax({
	    			type : "GET",
	    			url : "/EMS/FamesSearch",
	    			cache : false,
	    			timeout : 600000,
	    			dataType : 'html',
	    			success : function(msg) {
	    				/* if (msg != null) {
	    					console.log("inside success");
	    					$('#MCRSNewClaimPopUpblur').removeClass('d-none');
	    				} */
	    				if(msg != null){
	    					$("#main").html(msg);
	    				}
	    			},
	    			error : function() {
	    				/* console.log("inside error");
	    				alert("ajax failed" + policyNumber); */
	    				console.log("Error");
	    			}
	    		});

	    		/* $('#MCRSNewClaimPopUpblur').removeClass('d-none'); */
	    		// 		$('#close').css("display", "block");
	    	};

	    	

		
	</script>

</body>
</html>
so the issue was that on frontend when i logged in through addmin and change the inside role to sales employee the by below we used to hide the filters