appice.controller('funnelsController',async function ($scope,$rootScope,appIceService,$routeParams,$location,  $timeout) {
	
	
	async function init() {
		if(semusiCommon.ACTIVE_APP_ID == undefined || semusiCommon.ACTIVE_APP_ID==""){
		window.location =  "/dashboard";

	      	return;
	    }		
		$scope.currentPage = 1;
		$scope.startFrom = 0;
    	$scope.pageSize = 5;
	 	$scope.isError = false;
	 	$scope.errorMsg="";
	 	$scope.funnelOldName = "";
		$scope.funnel={};                     
		$scope.funnel.events = [{}];
		$scope.selectedItems=[];
		$scope.platform= [];
		$scope.customDate= {};
		$scope.mode= 'Create';
		$scope.journeysArray = [];
		$scope.eventListData = [];
		$scope.selectedJourney = '';
		$scope.journeyKey      = false;
		$scope.showJourneyDropdown = false;
		$scope.multiSelectedAttributes = {};
		$scope.currentIndex = 0; 			// Variable to keep track of the current index visible
		$scope.showPlusMinusButton = false;
		$scope.funnelSteps = 5;
		$scope.eventList = "";
		$scope.events = []
	
		//$scope.units =["Seconds","Minutes","Hours","Days","Months"];
		$scope.units =["Seconds","Minutes","Hours","Days","Weeks","Months"];
		//$scope.currentUnits =["This Hour","Last Hour","Today","Yesterday","This Week","Last Week","This Month","Last Month","Custom"];
		$scope.currentUnits =["Today","Yesterday","This Week","Last Week","This Month","Last Month","Custom"];
		/*$scope.numberOperators = [{text:"Equals",label:"eq"},{text:"Greater Than",label:"gt"},{text:"Less Than",label:"lt"}];
		$scope.stringOperators = [{text:"Equals",label:"eq"},{text:"Not Equals",label:"ne"},{text:"Contains",label:"regex"}];*/
		$scope.numberOperators = [{text:"Equals",label:"eq"},{text:"Not Equals", label:"neq"},{text:"In",label:"in"},{text:"Not in",label:"nin"},{text:"Greater Than",label:"gt"},{text:"Greater Than or Equal To",label:"gte"},{text:"Less Than",label:"lt"},{text:"Less Than or Equal To",label:"lte"}];
		$scope.stringOperators = [{text:"Equals",label:"eq"},{text:"Not Equals",label:"ne"},{text:"Contains",label:"contains"},{text:"Not Contains",label:"not_contains"},{text:"In",label:"in"},{text:"Not in",label:"nin"}];
		$scope.booleanOperators = [{text:"Equals",label:"eq"},{text:"Not Equals",label:"ne"}];
		$scope.dateOperators = [{text:"Equals",label:"eq"},{text:"Not Equals",label:"ne"},{text:"Contains",label:"contains"},{text:"Not Contains",label:"not_contains"},{text:"Between",label:"btw"},{text:"Not Between",label:"nbtw"},{text:"In",label:"in"},{text:"Not in",label:"nin"}];
		$scope.platformOpt = ['Android','iOS','Web'];

		var events = await appIceService.getEventList();
			if(events){
				var journeys = [];
				$scope.eventList = events.data;
				$scope.events = events.data;
            	$scope.eventList = _.sortBy($scope.eventList, 'event');
				var len = $scope.funnel.events.length;
				if($scope.funnel.events[len-1]?.selectedJourney == undefined || $scope.funnel.events[len-1]?.selectedJourney == '' ){
                 $scope.eventListData[len-1] = $scope.eventList;
				}	
				
									// -------------------------------jouney drop down start
									events = $scope.eventList;
									for (let i = 0; i < events.length; i++) {
									if(events[i].journey){
										// journeys.push({journey: events[i].journey, id:i+1});
										journeys.push(events[i].journey);
										$scope.journeyKey = true;
										$scope.showJourneyDropdown = true;
									}
									}
									const journeyArray = journeys.filter((elem, index, self) => {
									  return index === self.indexOf(elem);
									});
									$scope.journeysArray = journeyArray;
				
									// -------------------------------------------- JDD end
				
			}
		
		refreshFunnelList();

		$('#platformOpt').multiselect({
			columns: 1,
			includeSelectAllOption: true,
			nonSelectedText: 'Platform'
	  });

	  // this function will get the index of the event  which you are trying to manupilate 
	$scope.getMaxIndex = function(eventKey) {
	
		// Retrieve the number of keys in multiSelectedAttributes for the given eventKey
		const keys = Object.keys($scope.multiSelectedAttributes[eventKey]);
	
		// Check if keys.length is defined and is a valid number
		if (keys.length && typeof keys.length === 'number') {
			return keys.length - 1; // Return keys.length - 1
		} else {
			return 0; // Return 0 if keys.length is not defined or not a valid number
		}
	};
	

	// Get the total no. of Attributes selected
	$scope.getMaxAttributeIndex = function(parentIndex, eventKey) {

		if (!$scope.multiSelectedAttributes[parentIndex] || 
			!$scope.multiSelectedAttributes[parentIndex][eventKey] ||
			typeof $scope.multiSelectedAttributes[parentIndex][eventKey] !== 'object') {
			// Handle the case where the parentIndex or eventKey is invalid or not an object
			return -1; // or any default value indicating error or no valid keys
		}
	
		const keys = Object.keys($scope.multiSelectedAttributes[parentIndex][eventKey]);
		if (keys.length === 0) {
			// Handle the case where there are no keys in the object
			return -1; // or any default value indicating no keys found
		}
	
		return keys.length - 1; // Return the maximum index
	
	};

	$scope.updateSelection = function() {
			$scope.showPlusMinusButton = true;
	};
	

	// When plus is clicked in attributes this function will increase the index of the array to render 
	$scope.addDropdownSet = function(parentIndex,selectedEvent,index) {
		$scope.currentIndex++;
		if (Object.keys($scope.multiSelectedAttributes[parentIndex][selectedEvent][index]).length !== 0) {
			// Only assign a new object if the current one is not empty
			$scope.multiSelectedAttributes[parentIndex][selectedEvent][index + 1] = {};
		}	
	};


	// Get the List of attributes
	$scope.getList = function(list) {
		if(list){

			var repeatedList = [];
			for (var i = 0; i < 3 * list.length; i++) {
				repeatedList.push(i);
			}
			return repeatedList;
		}else{
			return []
		}
	};
	
	
	// This function will remove the selected attribute when clicked on minus button 
	$scope.removeDropdownSet = function(parentIndex, selectedEvent,index) {
		
		delete $scope.multiSelectedAttributes[parentIndex][selectedEvent][index];
		
	};
	

	 
	  $scope.onJourneySelect = function(e) {
		$scope.showJourneyDropdown = true;
		var length = $scope.funnel.events.length;
		var selectedOption = e;
		const selectedJourney = selectedOption.replace(/string:/, "");
			$scope.eventListData[length-1] = [];
		for (let i = 0, len = $scope.eventList.length; i < len; i++) {
			if (typeof $scope.eventList[i] === "object" && $scope.eventList[i].journey !== undefined) {
			  if ($scope.eventList[i].journey === selectedJourney) {
				$scope.eventListData[length-1].push($scope.eventList[i])
			  }
			}
		  }
	};

	  let isFunnel = await appIceService.isFunnel;
		if(isFunnel){
			$scope.mode = 'Edit';
			await editFunnel();
		}
		 	
					
	}
	await init();


	function refreshFunnelList(){
		promise = appIceService.getEventFunnels();
    	promise.then(function(funnels) {
			$('#overlay').hide();
			if(funnels){
				$scope.eventFunnels = funnels;    
			}   	      	
		})
		.catch(function(error){
			$('#overlay').hide();
		});
	}
	 
	$scope.getMaxLimit = function(   index ,event) {

		$scope.multiSelectedAttributes
		if($scope.multiSelectedAttributes[index]){
			const keys = Object.keys($scope.multiSelectedAttributes[index][event]);
			if (keys.length && typeof keys.length === 'number') {
			   return keys.length -1
		  }else{
			  return 0 
		  } 
		}else{
		  return 0
		}

};

	$scope.calculateAverage = function(data){ 
		var sum = 0; 
		for(var i = 0; i < data.length; i++){
			sum += parseInt(data[i], 10); //don't forget to add the base 
		}
		var avg = sum/data.length;
		return avg; 
	};

	$(document).ready(function() {
		promise = appIceService.hideDisabledFeature();
		promise.then(function(data) {
		  if (data) {
			if (data[0].features.funnelPeriod) {
			  $scope.units = ["Seconds", "Minutes", "Hours", "Days", "Weeks"];
			  $scope.currentUnits = ["Today", "Yesterday", "This Week", "Last Week", "Custom"];
			}
		  }
		});
	  });

	  $(document).ready(function () {

		$("#funnelStartDate").datepicker({
			todayHighlight: true,
			autoclose: true,
			endDate: '0d',
			startDate: '-6d',
			forceParse: false,
			datesDisabled: ['0d'],
			format: 'M d, yyyy'
		});
	
		$("#funnelEndDate").datepicker({
			todayHighlight: true,
			autoclose: true,
			endDate: '0d',
			startDate: '-6d',
			forceParse: false,
			format: 'M d, yyyy'
		});
	});
	
           //Maximum of one month data will be available for funnels.
           function validateFunnelDuration(){
           	var unit = $scope.funnel.customunit;
           	var maxVal = 0;
           	var isValid = true;
           	switch(unit){			
           		case "Minutes":{
           			maxVal = 30*24*60;
           			if($scope.funnel.duration>maxVal){
           				$scope.isError = true;
           				$scope.errorMsg = "Duration should be less than or equal to "+ maxVal + " Minutes.";	 	
           				isValid = false;
           			}
           			break;
           		}				
           		case "Hours":{
           			maxVal = 30*24;
           			if($scope.funnel.duration>maxVal){
           				$scope.isError = true;
           				$scope.errorMsg = "Duration should be less than or equal to or equal to "+maxVal + " Hours.";	 	
           				isValid = false;
           			}
           			break;
           		}			
           		case "Days":{
           			maxVal = 30;
           			if($scope.funnel.duration>maxVal){
           				$scope.isError = true;
           				$scope.errorMsg = "Duration should be less than or equal to "+maxVal + " Days.";	 	
           				isValid = false;
           			}
           			break;
           		}
           		case "Months":{
           			maxVal = 1;
           			if($scope.funnel.duration>maxVal){
           				$scope.isError = true;
           				$scope.errorMsg = "Duration should be less than or equal to "+maxVal + " Month.";	 	
           				isValid = false;
           			}
           			break;
           		}
           		case "Weeks":{
           			maxVal = 4;
           			if($scope.funnel.duration>maxVal){
           				$scope.isError = true;
           				$scope.errorMsg = "Duration should be less than or equal to "+maxVal + " Days.";	 	
           				isValid = false;
           			}
           			break;
           		}
           	}
           
           	return isValid;
           }



	function validateEvent(){
		var ctr = $scope.funnel.events.length;
		if(ctr > $scope.funnelSteps){
			$scope.isError = true;
			$scope.errorMsg = "Please Select only 4 steps";	 
			return false;
		}
	    if($scope.funnel.events[ctr-1].selectedEvent ==undefined ){
			$scope.isError = true;
			$scope.errorMsg = "Please select an event.";	 
			return false;   
	    }
			// Check the attributes and operator
		const inputObject = $scope.multiSelectedAttributes;
		for (const eventIndex in inputObject) {

			const eventSelected = inputObject[eventIndex]

			if (Object.keys(eventSelected).length > 0) {

				const eventName = Object.keys(eventSelected)[0];
				const attrList = inputObject[eventIndex][eventName]
				for (const attr in attrList) {
					const obj = attrList[attr]

					if (!obj.hasOwnProperty('name') || !obj.hasOwnProperty('operator') || !obj.hasOwnProperty('attributeValue') ||
						!obj.name || !obj.operator || !obj.attributeValue) {
						$scope.errorMsg = "Missing or empty fields: ";
						if (!obj.hasOwnProperty('name') || !obj.name) {
							$scope.isError = true;
							$scope.errorMsg += "'name' ";
							return false;
						}
						if (!obj.hasOwnProperty('operator') || !obj.operator) {
							$scope.isError = true;
							$scope.errorMsg += "'operator' ";
							return false;
						}
						if (!obj.hasOwnProperty('attributeValue') || !obj.attributeValue) {

							$scope.errorMsg += "'Attribute Value' ";
							$scope.isError = true;
							return false;
						}
					}


				}


			}

		}
	    return true;
	}

	async function parseUIObject(){
		var events = [];
		await Promise.all($scope.funnel.events.map(async (item,index) =>{
			var eventData = {
				eventName:item.selectedEvent.event,
				list : await getEventAttributes(item.selectedEvent.event)				
			};
			if ($scope.multiSelectedAttributes &&  $scope.multiSelectedAttributes[index]  && $scope.multiSelectedAttributes[index][item.selectedEvent.event]) {

				eventData.attributes = Object.values($scope.multiSelectedAttributes[index][item.selectedEvent.event])
				.filter(item => Object.keys(item).length !== 0) // Filter out empty objects
				.map(item => ({
					attributeName: item.name,
					type: item.type,
					value: item.attributeValue, // Assuming "value" should be the value of "attributeValue"
					operator: item.operator
				}));
			}else{
				eventData.attributes = []
			}

			if(item.selectedAttribute){
				eventData.attributeName = item.selectedAttribute.name;
				eventData.type=item.selectedAttribute.type;
			}
			if(item.attributeValue){
				if(item.selectedAttribute.type == 'date' &&(item.operator =='eq' || item.operator == 'ne' || item.operator =='btw' || item.operator =='nbtw')){
					eventData.value = item.attributeValue.toLocaleDateString();
				 }else{
					 eventData.value = item.attributeValue;
				 }	
			}
			if(item.attributeValue1){
				eventData.value1 = item.attributeValue1.toLocaleDateString();
			}
			if(item.selectedJourney){
				eventData.selectedJourney = item.selectedJourney;
			}
			if(item.operator){
				eventData.operator = item.operator;	
			}			
			events.push(eventData);
		}));
		if($scope.funnel.duration == undefined || $scope.funnel.unit != 'Custom'){
			$scope.funnel.duration = '';
		}
		if($scope.funnel.customunit == undefined || $scope.funnel.unit != 'Custom'){
			$scope.funnel.customunit = '';
		}
		if($scope.funnel.startDate && $scope.funnel.endDate && $scope.funnel.unit == 'Custom'){
			const convertedStartDate = moment($scope.funnel.startDate, "MMM DD, YYYY").format("MM/DD/YYYY");	
			const convertedEndDate = moment($scope.funnel.endDate, "MMM DD, YYYY").format("MM/DD/YYYY");
			$scope.customDate = {sd: convertedStartDate, ed:convertedEndDate};
		}
		//return {name:$scope.funnel.name,description:$scope.funnel.description,duration:$scope.funnel.duration,unit:$scope.funnel.unit,events:events};
		return {name:$scope.funnel.name,description:$scope.funnel.description,duration:$scope.funnel.duration,customDate:$scope.customDate,unit:$scope.funnel.unit,customunit:$scope.funnel.customunit,events:events,platform: $scope.platform};
	}

	function parseSavedObject(funnel){
	
		$scope.funnel.events=[];
		funnel.events.forEach(function(item){
			var eventname = item.eventName;
			var attributename='';
			var eventData ={};
			eventData.selectedEvent = {
				"event":item.eventName,
				"list" :getEventAttributes(item.eventName),

			};
			if(item.attributeName){
				attributename=item.attributeName;
				eventData.selectedAttribute={
					name:item.attributeName,
					type:item.type
				}
			}
			if(item.operator){
				eventData.operator = item.operator;
			}
			if(item.value){
				eventData.attributeValue = item.value;
			}

			$scope.funnel.events.push(eventData);
			//Add key to selected items array.
			var label = eventname+attributename;
			var selectedIndex = $.inArray(label, $scope.selectedItems);
			if (selectedIndex == -1) {
				$scope.selectedItems.push(label);
			}	
		});		
	}

	async function getEventAttributes(event){
		var list = [];
			$('#overlay').hide();
			$scope.eventList = $scope.events;
				$scope.eventList = _.sortBy($scope.eventList, 'event');
				$scope.eventList.forEach(function(item){
					if(item.event == event){
						list = item.list;
					}
				});
		return list;
	}

	function removeFromSelectedItems(label){
		var selectedIndex = $.inArray(label, $scope.selectedItems);
		if (selectedIndex>=0) {
			$scope.selectedItems.splice(selectedIndex, 1);
		}
	}

	$scope.validateProperty = function(index){	
		var len = $scope.funnel.events.length;	
		var eventname = $scope.funnel.events[len-1].selectedEvent.event ;
		var attributename = ($scope.funnel.events[len-1].selectedAttribute)?$scope.funnel.events[len-1].selectedAttribute.name:'';
		var label = eventname+attributename;
		$('#conditionMsg'+index).html("AND does...");
		if($.inArray(label,$scope.selectedItems)!=-1){
			$('#conditionMsg'+index).html("OR does...");
			// $scope.funnel.events[len-1].selectedEvent = undefined;
			// if($scope.funnel.events[len-1].selectedAttribute){
			// 	$scope.funnel.events[len-1].selectedAttribute = undefined;	
			// }
		}
	}

	$scope.operandChange = function(value){
		removeFromSelectedItems(value);
	}

	$scope.filterNumberValue = function($event){
        if(isNaN(String.fromCharCode(($event.which)?$event.which:$event.keyCode)) && $event.keyCode != 8){    	
            $event.preventDefault();
        }
	};

	$scope.numberOfPages=function(){
		if($scope.eventFunnels){
			var totalPages = Math.ceil($scope.eventFunnels.length/$scope.pageSize); 
			return (totalPages == 0)?1:totalPages;               	
		}        
    }

	$scope.addNewEventToFunnel = function() {	
		$scope.currentIndex = 0; // Variable to keep track of the current index visible
		var length = $scope.funnel.events.length;
		$scope.isEdit = false;
		if($scope.funnel.events[length]?.selectedJourney == undefined || $scope.funnel.events[length]?.selectedJourney == '' ){
			$scope.eventListData[length] = $scope.eventList;
		}
	    if(validateEvent()){
	    	var len = $scope.funnel.events.length;
	    	var eventname = $scope.funnel.events[len-1].selectedEvent.event ;
			var attributename = ($scope.funnel.events[len-1].selectedAttribute)?$scope.funnel.events[len-1].selectedAttribute.name:'';
			var label = eventname+attributename;
			var selectedJourney = $scope.funnel.events[len-1].selectedJourney;
			var selectedIndex = $.inArray(label, $scope.selectedItems);
			if (selectedIndex == -1) {
				$scope.selectedItems.push(label);
			}
	    	$scope.funnel.events.push({});	
	    }	    			    
  	};

  	$scope.removeEventFromFunnel = function(index) {  		
    	//Remove from selected items list.
		var eventname = ($scope.funnel.events[index].selectedEvent)?$scope.funnel.events[index].selectedEvent.event :"";
		var attributename = ($scope.funnel.events[index].selectedAttribute)?$scope.funnel.events[index].selectedAttribute.name:'';
		var label = eventname+attributename;
		removeFromSelectedItems(label);
		if($scope.funnel.events.length==1){
			$scope.funnel.events=[{}];
			return;	
		}
    	$scope.funnel.events.splice(index,1);	    	
  	};

  	$scope.resetControls = function(){
  		$scope.funnel.events = [{}];
    	$scope.funnel.name="";
    	$scope.funnel.description="";
    	$scope.funnel.duration="";
    	$scope.funnel.unit="";
    	$scope.isEdit = false;
    	$scope.isError=false;
    	$scope.selectedItems=[];
		$scope.showCustom =false;
		$scope.platform = [];
		$(".multiselect-selected-text").text('Platform');

	  }
	  
	  function validateFunnelPlatform(){
		if(!$scope.platform.length){
		  $scope.isError = true;
		  $scope.errorMsg = "Please select a platform.";
		  return false;
		}
		return true;
	}	
	
	function validateStartDate() {
		if ($scope.funnel.startDate === undefined || $scope.funnel.startDate === "") {
			$scope.isError = true;
			$scope.errorMsg = "Please enter funnel start date.";
			return false;
		}

		if (moment($scope.funnel.startDate).unix() > moment($scope.funnel.endDate).unix()) {
			$scope.isError = true;
			$scope.errorMsg = "Start date cannot be greater than end date";
			return false;
		}
	
		return true;
	}

	function validateEndDate() {
		if ($scope.funnel.endDate === undefined || $scope.funnel.endDate === "") {
			$scope.isError = true;
			$scope.errorMsg = "Please enter funnel end date.";
			return false;
		}
	
		return true;
	}

	/**
	 * Filters events based on selected journeys.
	 * @param {Array} events - Array of events to filter.
	 * @param {Array} mappedData - Array of selected journeys.
	 * @returns {Array} - Array of filtered events for each selected journey.
	*/
	function filterEventsBySelectedJourneys(events, mappedData) {
		const filteredEvents = mappedData.map(selectedJourney => {
		  return events.filter(event => event.journey === selectedJourney);
		});
		return filteredEvents;
	} 
	
	$scope.saveFunnel = function(){

	    if($scope.funnel.name==undefined || $scope.funnel.name=="") {
	    	$scope.isError = true;
			$scope.errorMsg = "Enter a valid funnel name.";	 
			return;  
		}

			//   Validating the userinput to contain only allowing letters, numbers, space?
			var regex = /^[a-zA-Z0-9 ]+$/;
			if(!regex.test($scope.funnel.name)) {
				$scope.isError = true;
				$scope.errorMsg = "Funnel name must contain only letters, numbers, spaces";	 
				return;  
			}
		
		// for decription 
		if($scope.funnel.description==undefined || $scope.funnel.description=="") {
	    	$scope.isError = true;
			$scope.errorMsg = "Enter a valid funnel description.";	 
			return;  
		}

			//   Validating the description to contain only allowing letters, numbers, space?
			var regex = /^[a-zA-Z0-9 ]+$/;
			if(!regex.test($scope.funnel.description)) {
				$scope.isError = true;
				$scope.errorMsg = "Funnel description must contain only letters, numbers, spaces";	 
				return;  
			}
	
	   
		// validate funnel name exists or not
		$scope.validateFunnelName(async function(response){
			if(!response){
				var promise;
				var funnel = await parseUIObject();
				// using isExisting in place of isEdit as that varaible is used for save and edit case also , 
				if($scope.isExisting){
				funnel.sd = funnel.customDate.sd;
				funnel.ed = funnel.customDate.ed;
					promise = appIceService.updateFunnel(funnel,$scope._id);
				}
				else{
					promise = appIceService.createFunnel(funnel);	
				}
				 
				promise.then(function(data) {
					$scope.resetControls();
					
						$("#messageboxsucess").text("Funnel Successfully Created")
						$("#messagesucess").show();

						setTimeout(() => {
							$("#messagesucess").hide();
						},3000)
				     	
		        	//Add the newly added item to the list        	        	
					refreshFunnelList();
					$scope.isEdit = false;   	
		    	});
			}
		});
	}
	function formatDate(inputDate) {
		const [month, day, year] = inputDate.split("/");
		const dateObject = new Date(year, month - 1, day);
		return dateObject.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
	  }
	

	async function editFunnel(){
		$scope.funnel = appIceService.getFunnel();
		$scope.isEdit = true;
		$scope.isExisting = true;				// to trace that we are checking existing funnel ( this varaible  shouldn't be updated in any case )
		if($scope.funnel && $scope.funnel.events && $scope.funnel.events.length > 0  && $scope.funnel.events[$scope.funnel.events.length - 1].selectedJourney){
			const mappedJournies = $scope.funnel.events.map(item => item.selectedJourney);
			$scope.eventListData = filterEventsBySelectedJourneys($scope.eventList, mappedJournies);
		}
		$scope.funnel.name = $scope.funnel.name;
		$scope.funnel.duration = $scope.funnel.duration;	
		if($scope.funnel.customDate.sd && $scope.funnel.customDate.sd){
			$scope.funnel.startDate = formatDate($scope.funnel.customDate.sd);		
			$scope.funnel.endDate = formatDate($scope.funnel.customDate.ed);	
		}			
		$scope.funnel.description = $scope.funnel.description;
		$scope.funnel.unit=$scope.funnel.unit;	
		$scope.funnel.customunit = $scope.funnel.customunit;
		$scope._id = $scope.funnel._id;	
		$scope.funnelOldName = $scope.funnel.name;
		$(".multiselect-selected-text").text($scope.funnel.platform);
		$scope.funnel.platform.forEach(function(itm){
			$('#platformOpt').multiselect('select', itm);
		})
		$scope.platform = $scope.funnel.platform;
		if($scope.funnel.duration != ''){
			$scope.showCustom = true;
		}
		 if($scope.funnel.duration == "" ){
			$scope.showCustom = false;
			$scope.showCustomWithDates = false;
		}
		if($scope.funnel.duration == "" && $scope.funnel.customunit == "Days"){
			$scope.showCustomWithDates = true;
		}
		let funnel_events = await appIceService.getFunnel().events;  
		appIceService.removeFunnel();
		$scope.funnel.events=[];
		funnel_events.forEach(async function(item, i){
			var eventname = item.eventName;
			var attributename='';
			var eventData ={};
			eventData.selectedEvent = {
				"event":item.eventName,
				"list" :await getEventAttributes(item.eventName),

			};

			if(item.attributes && item.attributes.length > 0 ){
				// $scope.multiSelectedAttributes
				const convertedData = item.attributes.reduce((acc, item, index) => {
					acc[index.toString()] = {
						name: item.attributeName,
						type: item.type,
						operator: item.operator,
						attributeValue: item.value
					};
					return acc;
				}, {});
				$scope.multiSelectedAttributes[i] ={}
				$scope.multiSelectedAttributes[i][item.eventName] = convertedData
				const newIndex = item.attributes.length - 1;

				if (newIndex > $scope.currentIndex) {
				    $scope.currentIndex = newIndex;
				}
				$scope.showPlusMinusButton = true;
			}
			if(item.attributeName){
				// Render the event attributes from the old Format
				$scope.multiSelectedAttributes[i][item.eventName] = {
					"0": {
						"name": item.attributeName,
						"type": item.type,
						"operator": item.operator,
						"attributeValue": item.value
					}
				};

				attributename=item.attributeName;
				eventData.selectedAttribute={
					name:item.attributeName,
					type:item.type
				}
			}
			if(item.operator){
				eventData.operator = item.operator;
			}
			if(item.value){
				eventData.attributeValue = item.value;
			}
			if(item.selectedJourney){
				eventData.selectedJourney = item.selectedJourney;
			}

			$scope.funnel.events.push(eventData);
			//Add key to selected items array.
			var label = eventname+attributename;
			var selectedIndex = $.inArray(label, $scope.selectedItems);
			if (selectedIndex == -1) {
				$scope.selectedItems.push(label);
			}	
		});		
	}

	$scope.deleteFunnel = function(id){
		if(confirm("Do you want to delete this funnel?")){
			var promise = appIceService.deleteFunnel(id);
			promise.then(function(data) {        	       	
	        	//Refresh the funnels list     	        	
				refreshFunnelList();	
				$scope.resetControls();			    	
	    	});
		}
	}

	$scope.validateFunnelName = function(cb){
		// validate segment name
		 
		if( $scope.funnel.name != '' && $scope.funnel.name != undefined && $scope.funnelOldName != $scope.funnel.name ){
			
			$scope.isFunnelError = false; // hide error message

			promise = appIceService.validateFunnelName($scope.funnel.name);
			promise.then(function(response) { 
	        	// show error message of segment name
	        	if(response){
	        		$scope.isFunnelError=true;
					$scope.errorFunnelMsg = "This funnel name already exists!";
					$("#modal-dialog").modal()
	        	}

	        	if(cb != undefined){
	        		cb(response);
	        	}
	    	});	
		}
		else{
			$scope.isError = false; // hide error message
			if( $scope.funnel.name != '' && $scope.funnel.name != undefined ){
				if(cb != undefined){
	        		cb(false);
	        	}
			}
		}
	}

// open data model
$scope.openModel = function() {
	$scope.isError = false;
	$scope.errorMsg = "";

	if ($scope.funnel.unit == 'Custom') {
		promise = appIceService.hideDisabledFeature();
		promise.then(function(data) {
			if (data && !data[0].features.funnelPeriod) {
				if (!validateFunnelDuration() || !validateEvent() || !validateFunnelPlatform()) {
					return;
				}

				if ($scope.funnel.unit == "" || $scope.funnel.unit == undefined) {
					$scope.isError = true;
					$scope.errorMsg = "Select duration period.";
					return;
				}

				if (($scope.funnel.duration == undefined || $scope.funnel.duration == "") || ($scope.funnel.customunit == undefined || $scope.funnel.customunit == "")) {
					$scope.isError = true;
					$scope.errorMsg = "Enter duration and select duration period.";
					return;
				}
			} else {
				$scope.funnel.customunit = "Days";
				if (!validateStartDate() ||!validateEndDate() || !validateEvent() || !validateFunnelPlatform()) {
					return;
				}
			}
			
			if ($scope.isError) {
				return;
			}

			$("#modal-dialog").modal();
		});
	} else {
		if (!validateEvent() || !validateFunnelPlatform()) {
			return;
		}

		$("#modal-dialog").modal();
	}
};


	$scope.showHideCustom = function(val){
		promise = appIceService.hideDisabledFeature();
		promise.then(function(data) {
		  if (data) {
			if(val=="Custom" && data[0].features.funnelPeriod){
				$scope.showCustomWithDates=true;
			}else if(val=="Custom" && !data[0].features.funnelPeriod){
				$scope.showCustom=true;
			}else{
				$scope.showCustom=false;
				$scope.showCustomWithDates=false;
			}
		  }
		});
	}
});
