appice.controller("campaignDetailsController",function ($scope, appIceService,$timeout, $routeParams) {

const campId = $routeParams.campId; 
let campaignData;
$scope.showRecieve = false;
$scope.campaignStatusData = [];   
$scope.campaignVariantData = [];
$scope.totalStats = {};
$scope.isVisible = false;
$scope.controlGroup = '' 
$scope.startDate = '';
$scope.endDate = '';
$scope.templateDetails;
$scope.activeAppid = semusiCommon.ACTIVE_APP_ID;    // FOR NOW 
$scope.campaignStatsData = {android: {}, ios: {}, web: {}};
$scope.previewType;

$scope.isPlatformData = false;
$scope.platformWiseData =[]
//ANDROID PUSH 
$scope.isBasicStaticImg = false;
$scope.isExpendedImg = false;
$scope.loderImg = false;
$scope.exploderImg = false;
$scope.exploderImg = false;
$scope.expImguploader = false;
$scope.isExpandedDesc = false;
$scope.isPushAction = false;
$scope.pushActionsList = [];


//ANDROID INAPP

$scope.isBasicStaticImgFull = false;
$scope.fullScreenImgIcon = true;
$scope.viewmode;
$scope.hideCta = false;
$scope.setAction = false;

//requestid search
$scope.requestId = '';
$scope.modalData = [];
$('#error-msg-req').hide();




function init() {
    getCampDetails();
    initDateRange();
}  


function getCampDetails() {
    //Getting campaign By Id
    var data = {
        d:true,
        ud:semusiCommon.getCurrentEpoch()
    };
   appIceService.getCampaignById(campId,data).then(data => {
         if(data) {
          if(Object.keys(data).length === 0){
            //set custom campaign ui 
            $scope.customAudCamp = true 
          }else{
             campaignData = data;
             $scope.controlGroup = (campaignData.controlGroup) ? campaignData.controlGroup : ''
             //Getting campaigns template data
             getTemplateDetailsById( campaignData.tid );
         }  
        }
   })
   .catch(err => {
         
   })

}
const initDateRange = function () {


  // initializing default dates
  const todaysDate = moment().format(semusiCommon.getDateFormatt())
  const daysBefore29 =  moment().subtract('days', 29).format(semusiCommon.getDateFormatt())

  // set the default value  
  $('#advance-daterange span').html(`${daysBefore29} - ${todaysDate}`);

  // constructing parameters
  const stats_params = {
    startDate : moment().subtract(29, "days").startOf('day').valueOf(),
    endDate : moment.utc().endOf("day").valueOf(),                   
    camp_id : campId
  }
  // Set the state of sd and ed
  $scope.startDate = moment().subtract(29, "days").startOf('day').valueOf();
  $scope.endDate = moment.utc().endOf("day").valueOf();

  // call the graph and split api 
  getCampaignStatsData( stats_params ) 


  const date = new Date();
  $('#advance-daterange').daterangepicker({
    format: semusiCommon.getDateFormatt(),
    startDate: moment().subtract(29, 'days'),
    endDate: moment(),
    minDate: new Date(date.getFullYear(), date.getMonth() - 3, date.getDate()),
    maxDate: new Date(),
    showDropdowns: true,
    showWeekNumbers: false,
    timePickerIncrement: 1,
    timePicker12Hour: true,
    ranges: {
      'Today': [moment(), moment()],
      'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
      'Last 7 Days': [moment().subtract(6, 'days'), moment()],
      'Last 30 Days': [moment().subtract(29, 'days'), moment()],
      'This Month': [moment().startOf('month'), moment().endOf('month')],
      'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
    },
    opens: 'left',
    drops: 'down',
    buttonClasses: ['btn', 'btn-sm'],
    applyClass: 'btn-primary',
    cancelClass: 'btn-default',
    separator: ' to ',
    locale: {
      applyLabel: 'Submit',
      cancelLabel: 'Cancel',
      fromLabel: 'From',
      toLabel: 'To',
      customRangeLabel: 'Custom',
      daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
      monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
      firstDay: 1
    }
  }, function (start, end, label) {
    
    // set the Selected date range 
    semusiCommon.setDateRange(start, end);
    $('#advance-daterange span').html(start.format(semusiCommon.getDateFormatt()) + ' - ' + end.format(semusiCommon.getDateFormatt()));

    let sd = start;
    let ed = end;
    if (label != "Custom") {
      if (label == "Today") {
        sd = moment.utc().startOf("day").valueOf();
        ed = moment.utc().endOf("day").valueOf();
      }
      if (label == "Yesterday") {
        sd = moment.utc().subtract(1, "days").startOf("day").valueOf();
        ed = moment.utc().subtract(1, "days").endOf("day").valueOf();
      }
      if (label == "This Month") {
        sd = moment.utc().startOf("month").valueOf();
        ed = moment.utc().endOf("month").valueOf();
      }
      if (label == "Last 30 Days") {
        sd = moment().subtract(29, "days").startOf('day').valueOf();
        ed = moment.utc().endOf("day").valueOf();
      }
      if (label == "Last 7 Days") {
        sd = moment.utc().subtract(6, "days").startOf('day').valueOf();
        ed = moment.utc().endOf("day").valueOf();
      }
      if (label == "Last Month") {
        sd = moment.utc().subtract(1, "month").startOf("month").valueOf();
        ed = moment.utc().subtract(1, "month").endOf("month").valueOf();
      }
    } else {
      sd = moment(sd.format(semusiCommon.getDateFormatt())).unix() * 1000;
      ed = moment(ed.format(semusiCommon.getDateFormatt())).unix() * 1000;
    }

    const stats_params = {
      startDate : sd,
      endDate   :ed,         
      camp_id   : campId
    }
    
    $scope.startDate = sd;
    $scope.endDate = ed;
    getCampaignStatsData( stats_params ) 
        
  });
}

$scope.openChild = function(){
  var element = document.getElementById("isVisible");
  if (element.style.display === "none") {
    document.getElementById('faIcon').classList.add('fa-angle-down')
    document.getElementById('faIcon').classList.remove('fa-angle-right')
    element.style.display = "block";
  } else {
    document.getElementById('faIcon').classList.add('fa-angle-right')
    document.getElementById('faIcon').classList.remove('fa-angle-down')
    element.style.display = "none";
  }
}

/**
 * ShowPlatformWiseData
 * This function toggles the visibility of platform-wise data section and changes the color of a chart icon accordingly.
 */
  $scope.ShowPlatformWiseData = function () {
    const element = document.getElementById("spilitData");
    const chartIcon = $('#chartIcon');

        // Toggle display of platform-wise data section
    if (element.style.display === "none") {
      element.style.display = "block";
      chartIcon.css('color', 'green');
    } else {
      element.style.display = "none";
      chartIcon.css('color', 'black');
    }

  };


//This function show and hides column as per the campaign configuration from the the backend
function handleColumnVisibility(campaignColumns) {
  for (var key in campaignColumns) {
      if (campaignColumns.hasOwnProperty(key)) {
          if (campaignColumns[key] === true) {
              $("." + key).show();
          } else {
              $("." + key).hide();
          }
      }
  }
}

//Download Campaign CSV Data
$scope.downloadCSV = function() {
  window.location.href = appiceEncode.encodePayload(semusiCommon.API_PARTS.templates.r + '/downloadCampaignDataById?api_key='+semusiCommon.getActiveUser.api_key+'&app_id='+semusiCommon.ACTIVE_APP_ID+ '&uniqueNumber=' +semusiCommon.randomNumber()+'&cid='+campId+'&sd='+$scope.startDate +'&ed='+$scope.endDate+'&filename=campaign.csv');
}
//// Function to search for Request ID
$scope.searchRequestId = function(searchQuery) {
  // Validate input
  if (!searchQuery) {
      alert("Please enter RequestID");
      return; 
  }
  // Trim the searchQuery
  searchQuery = searchQuery.trim();
  // Show loading modal
  $scope.loading = true;
  const loadingModal = document.getElementById("loadingModal");
  loadingModal.style.display = "block";

  appIceService.getRequestId(searchQuery).then(function(response) {
    const close = document.getElementById("closemModal");

      close.addEventListener("click", function() {
          modal.style.display = "none";
      });

      // Hide loading modal
      loadingModal.style.display = "none";

      const modal = document.getElementById("reqIdModal");
      modal.style.display = "block";

      let res = response.data;

      res.forEach(item => {
          item.CampaignID = campId; 
      });

      $scope.modalData = res;

  }).catch(function(error) {
      // Hide loading modal
      loadingModal.style.display = "none";

      // Show error modal
      const errorModal = document.getElementById("errorModal");
      errorModal.style.display = "block";

      const modal = document.getElementById("reqIdModal");
      modal.style.display = "none";

      const closeError = document.getElementById("closemModalError");

      closeError.addEventListener("click", function() {
        errorModal.style.display = "none";
      });

  }).finally(function() {
      // Always hide loading modal in case of success or error
      loadingModal.style.display = "none";
  });
};


$scope.showVariantPushData = function (index, type) { 
  if(type == 'webpush'){
    $scope.web_push_obj.title = $scope.savevariantdata[index].title
    $scope.web_push_obj.message = $scope.savevariantdata[index].message
    $scope.web_push_obj.url = $scope.savevariantdata[index].url
    if($scope.savevariantdata[index].icon){
      if(isValidUrl($scope.savevariantdata[index].icon)){
        $scope.web_push_obj.icon = $scope.savevariantdata[index].icon
      } else {
        $scope.web_push_obj.icon = $scope.templateDetails.blobContainerCDN + $scope.savevariantdata[index].icon
      }
    }

    if($scope.savevariantdata[index].extendedImage != '' || $scope.savevariantdata[index].extendedImage != undefined){
      $('#WebIsExpanded').show()
      if(isValidUrl($scope.savevariantdata[index].icon)){
        $scope.expandedNotificationImageFile = $scope.savevariantdata[index].extendedImage
      } else {
        $scope.web_push_obj.icon = $scope.templateDetails.blobContainerCDN + $scope.savevariantdata[index].extendedImage
      }

    }
    setTimeout(function(){
        document.querySelectorAll(".downSlide")[index].classList.add('active')
    }, 200)
  }
     
}

function getTemplateDetailsById( tempId ) {
    appIceService.getAppTemplatesById(tempId) 
    .then( data => {
        if( data ){
            $scope.templateDetails = data;
            if($scope.previewType == 'WEB_PUSH'){
              $scope.web_push_obj = {}
              if($scope.templateDetails.template.length>0){
                  $scope.savevariantdata = $scope.templateDetails.template
                  $scope.showVariantPushData(0, 'webpush')
              }else{
                $scope.web_push_obj.title = $scope.templateDetails.template.title
                $scope.web_push_obj.message = $scope.templateDetails.template.message
                $scope.web_push_obj.url = $scope.templateDetails.template.externalUrl
                if($scope.templateDetails.template.icon){
                  if(isValidUrl($scope.templateDetails.template.icon)){
                    $scope.web_push_obj.icon = $scope.templateDetails.template.icon
                  } else{
                    $scope.web_push_obj.icon = $scope.templateDetails.blobContainerCDN + $scope.templateDetails.template.icon
                  }
                }

                if($scope.templateDetails.template.extendedImage != '' && $scope.templateDetails.template.extendedImage != undefined){
                  $('#WebIsExpanded').show()
                  if(isValidUrl($scope.templateDetails.template.extendedImage)){
                    $scope.expandedNotificationImageFile=  $scope.templateDetails.template.extendedImage
                }else{
                  $scope.expandedNotificationImageFile = $scope.templateDetails.blobContainerCDN +$scope.templateDetails.template.extendedImage
                }
                  
                }
              }

            }
            if($scope.previewType == 'WEB_POPUP'){
              $scope.web_pop_obj = {}
                $scope.web_pop_obj.title = $scope.templateDetails.template.title
                $scope.web_pop_obj.message = $scope.templateDetails.template.message
                $scope.web_pop_obj.url = $scope.templateDetails.template.externalUrl


                if($scope.templateDetails.template.icon){
                  if(isValidUrl($scope.templateDetails.template.icon)){
                    $scope.web_pop_obj.icon = $scope.templateDetails.template.icon
                  } else{
                    $scope.web_pop_obj.icon = $scope.templateDetails.blobContainerCDN + $scope.templateDetails.template.icon
                  }
                }
                if($scope.templateDetails.template.iconB){
                  if(isValidUrl($scope.templateDetails.template.iconB)){
                    $scope.web_pop_obj.iconB = $scope.templateDetails.template.iconB
                  } else{
                    $scope.web_pop_obj.iconB = $scope.templateDetails.blobContainerCDN + $scope.templateDetails.template.iconB
                  }
                }


            }
            if($scope.previewType == 'PUSH') {
                //Push config check
                $scope.isBasicStaticImg =  $scope.templateDetails.blobContainerCDN + $scope.templateDetails.template.notificationImage?true:false; 
                $scope.loderImg = true;
                $scope.exploderImg = true
                $scope.templateDetails.template.pushType === "expanded" ? $("#isExpanded").show(): $scope.templateDetails.template && $scope.templateDetails.template.length > 0 && $scope.templateDetails.template[0].pushType == 'expanded' ?  $("#isExpanded").show() : $("#isExpanded").hide() ;
                $scope.isExpendedImg = $scope.templateDetails.blobContainerCDN + $scope.templateDetails.template.expandedNotificationImage?true:false;
                $scope.exploderImg = $scope.isExpendedImg?true:false;
                $scope.expImguploader = $scope.isExpendedImg?true:false;
                $scope.isExpandedDesc = $scope.templateDetails.template.expandedNotificationDescription?true:false;
                $scope.isPushAction = $scope.templateDetails.template.actions.length?true:false;
                $scope.pushActionsList = $scope.isPushAction?$scope.templateDetails.template.actions:[];
            
          }
            //Inapp  config check
          if($scope.previewType == 'IN-APP') {
                $scope.viewmode = $scope.templateDetails.template.view_mode;
                if($scope.viewmode == 'Fullscreen') {
                  $scope.inAppFull = true;
                  // $scope.isBasicStaticImgFull = $scope.templateDetails.template.notificationImage?false:true;
                  $scope.isBasicStaticImgFull = false;
                  // $scope.fullScreenImgIconfull = $scope.isBasicStaticImgFull?true:false;
                  $scope.fullScreenImgIconfull = false;
                  $scope.loderImgfull = $scope.isBasicStaticImgFull?false:true;
                  $scope.hideCta = $scope.templateDetails.template.showAction?true:false;
                  $scope.setAction = $scope.templateDetails.template.showAction?true:false;
                }
                if($scope.viewmode == 'Mini') {
                  $scope.inAppMini = true;
                  // $scope.inAppBasicS3Img = $scope.templateDetails.template.notificationImage?false:true;
                  $scope.inAppBasicS3Img = false;
                  // $scope.miniScreenImgIconmini = $scope.inAppBasicS3Img?true:false;
                  $scope.miniScreenImgIconmini = false;
                  $scope.loderImgmini = true;
                }
                if($scope.viewmode == 'Header') {
                  $scope.header = true;
                  // $scope.inAppBasicS3ImgHeader = $scope.templateDetails.template.notificationImage?false:true;
                  $scope.inAppBasicS3ImgHeader = false;
                  // $scope.headerScreenImgIconheader =  $scope.inAppBasicS3ImgHeader?true:false;
                  $scope.headerScreenImgIconheader =  false;
                  $scope.loderImgheader = true;
                  if($scope.templateDetails.template.iconImage != ''){
                    $scope.inAppBasicS3ImgHeader = false;
                    $scope.inAppBasicS3Img = true;
                    $scope.isBasicStaticImgFull  = true;
                    $scope.inAppBasicS3ImgFooter = true;
                    $scope.headerScreenImgIcon   = false;
                    if(isValidUrl($scope.templateDetails.template.iconImage)){
                        $scope.iconInAppImageFileHeader =  $scope.templateDetails.template.iconImage
                    }else{
                        $scope.iconInAppImageFileHeader = $scope.templateDetails.blobContainerCDN + $scope.templateDetails.template.iconImage;
                    }
                    
                }

                }
                if($scope.viewmode == 'Footer') {
                  $scope.footer = true;
                  // $scope.inAppBasicS3ImgFooter = $scope.templateDetails.template.notificationImage?false:true;
                  $scope.inAppBasicS3ImgFooter = false;
                  $scope.footerScreenImgIcon =  $scope.inAppBasicS3ImgHeader?true:false;
                  $scope.loderImgfooter = true;
                  if($scope.templateDetails.template.iconImage != ''){
                    $scope.inAppBasicS3ImgHeader = true;
                    $scope.inAppBasicS3Img = true;
                    $scope.isBasicStaticImgFull  = true;
                    $scope.inAppBasicS3ImgFooter = false;
                    $scope.headerScreenImgIcon   = false;
                    if(isValidUrl($scope.templateDetails.template.iconImage)){
                        $scope.iconInAppImageFileHeader =  $scope.templateDetails.template.iconImage
                    }else{
                        $scope.iconInAppImageFileHeader = $scope.templateDetails.blobContainerCDN + $scope.templateDetails.template.iconImage;
                    }
                    
                }

                }
          }

          //iNAPP RATING CONFIG
          if($scope.previewType == 'RATING') {
            fillRatingScreen($scope.templateDetails);
          }

          if($scope.previewType == 'SURVEY') {
            $("#AndroidInappSurvey").show();
            fillSurveyScreen($scope.templateDetails)
          }



        }
    })
    .catch( err => {
         
    })
}

//Rating screen configuration
function fillRatingScreen(data) {
  $("#inAppAndroidRating").show();
  $scope.setRatingVariables();
  $scope.template_id  = data._id;
  $scope.ratingButton = "Update";
  $scope.activeImage  = data.template.activeImage;
  $scope.disabledImage = data.template.disabledImage;
  $scope.appRating.templateName = data.template_name;
  $scope.appRating.question = data.template.question;
  $scope.appRating.action = data.template.title;
  $scope.appRating.message = data.template.message;
  $scope.appRating.starCount = data.template.starCount;
  $scope.appRating.starColour = data.template.starColour;
  //Rating Text Screen 
  $scope.starItems=[];
  for(var i=0; i<data.template.starRatingText.length;i++){
      $scope.starItems.push({'value' : data.template.starRatingText[i], 'name' : 'star' + parseInt(i+1)});
  }
  $scope.appRating.bgColour = data.template.bgColour;
  $scope.appRating.sbBtnText = data.template.sbBtnText;
  $scope.appRating.sbBtnClr = data.template.sbBtnClr;
  $scope.showRatingImg = ratingImg();

   
}

var ratingImg = function() {
  var tmp = [];
  for(var i=0; i<5; i++) {
     tmp.push({id:i, img:$scope.disabledImage});
  }
  return tmp; 
}

$scope.showRatingImg = ratingImg();
$scope.setRatingVariables = function() {
  // defining rating variables
  $scope.starItems = [];
  $scope.ratingButton = 'Submit';
  $scope.appRating = {};
  $scope.appRating.action = 'Submit';
  $scope.activeImage = '', //'/images/dashboard/star-hover.png';
  $scope.disabledImage = '', //'/images/dashboard/star-empty.png';
  $scope.showRatingImg = ratingImg();
}


//Survey Confiuration 
function fillSurveyScreen(data){
  $scope.setSurveyVariables();
  $scope.survey.surveyName = data.template_name;
  $scope.survey.nt = data.template.nt;
  $scope.survey.st = data.template.st;
  $scope.survey.bgclr = data.template.bgclr;
  $scope.survey.selectedBorder = data.template.isSurvey;
  $scope.survey.txclr = data.template.txclr;
  $scope.survey.bobgclr = data.template.bobgclr;
  $scope.template_id  = data._id;
  $scope.surveyButton  = "Update";
  var ststus = false;

  data.template.q.forEach(function(elem, index){
      $scope.surveyCounter = index;
      surveyQuestionsInit();
      $scope.surveyQuestions[$scope.surveyCounter]['question'] = elem.questionText;
      $scope.surveyQuestions[$scope.surveyCounter].showQues = true;
      $scope.surveyQuestions[$scope.surveyCounter].questionType = elem.questionType;
      $scope.surveyQuestions[$scope.surveyCounter].otherOption = elem.otherOption;

      if(elem.questionType == "radiobuttonchoice"){
          ststus = false;
          $scope.surveyQuestions[$scope.surveyCounter].ischoice = true;
          $scope.surveyQuestions[$scope.surveyCounter].isTextField = false;
      }
      else{
          ststus = true;
          $scope.surveyQuestions[$scope.surveyCounter].ischoice = false;
          $scope.surveyQuestions[$scope.surveyCounter].isTextField = true; 
      }

      $scope.surveyQuestions[$scope.surveyCounter].options = setOptionsOfQues(elem.questionOptions);
      
      $scope.isBack = true;
      //$scope.survey.otherOption = elem.otherOption;
  });

  $scope.survey.state = ststus;
}

$scope.setSurveyVariables = function() {
  $scope.surveyCounter    = 0;
  $scope.survey           = {};
  $scope.survey.state     = false;
  $scope.survey.surveyName= '';
  $scope.surveyQuestions  = [];
  $scope.isBack           = false;
  $scope.isNext           = false;
  $scope.surveyName_error = false;
  $scope.question_error   = false;
  $scope.isErrorMessage   = false;
  $scope.survey.otherOption = false;
  $scope.template_id      = '';
  $scope.surveyButton     = "Submit"; 
  surveyQuestionsInit();
}

function surveyQuestionsInit (){
  $scope.surveyQuestions[$scope.surveyCounter] = {
                                            question : '',
                                            showQues : true,
                                            ischoice : true,
                                            isTextField : false,
                                            options:[],
                                            questionType : "radiobuttonchoice",
                                            otherOption: false
                                          }
}

var setOptionsOfQues = function(options){
  var tmp = [];
  options.forEach(function(value){
      tmp.push(value.optionText);
  });

  return tmp;
}


//Get campaign stats data 
function getCampaignStatsData( params ) { 
   let platform;
   appIceService.getCampaignStatsDateWise( params )
   .then( data  => {
    if(data.data) {
      renderCampaignTable(data.data.campaign)
      if(data.data.platformWiseData){
      renderSplitData(data.data.platformWiseData)
      }
      if(data.data.daywiseData){
      const daywiseData = data.data.daywiseData
      $scope.campaignStatsData.android = daywiseData.android ? daywiseData.android : {};
      $scope.campaignStatsData.ios = daywiseData.ios ? daywiseData.ios : {};
      $scope.campaignStatsData.web = daywiseData.web ? daywiseData.web : {};

      if(Object.keys($scope.campaignStatsData.android).length) {
        platform = 'android';
      }
      if(Object.keys($scope.campaignStatsData.ios).length) {
        platform = 'ios';
      }
       if(Object.keys($scope.campaignStatsData.web).length) {
        platform = 'web';
      }
      renderCampaignChart(platform);
     }
    }

   })
   .catch( err => {
     
   })
}

  function renderCampaignTable(campaign) {
    $scope.campaignStatusData = []

    if (campaign) {
      $scope.campaignStatusData.push(campaign);
      //render columns
      // updating evalAsync to applyAsync ( better way ) to ensure DOM manipulation is happening after the elements are fully rendered.
      $scope.$applyAsync(() => {
        handleColumnVisibility(campaign.columnStatus);
      });
      //check to not to show appInbox Reports in case of Webpush
      // show only if dlvy is of inbox or both 
      if (campaign.type != "WEB_PUSH" && campaign.appInboxreports == true) {
        $scope.IsappInboxReports = true;
      }
      if (campaign.appinbox_et) {
        $scope.appinbox_et = true;
      }
      const type = campaign.type;
      if (type == 'WEB_PUSH') {
        $scope.previewType = 'WEB_PUSH';
        $("#campWebPreview").show();
      }
      if (type === 'PUSH') {
        $scope.previewType = 'PUSH';
        $("#campAndroidPreview").show();
      }
      if (type === 'IN-APP') {
        $scope.previewType = 'IN-APP';
        $("#inAppAndroidPreview").show();
      }
      if (type === 'RATING') {
        $scope.previewType = 'RATING';
        $("#inAppAndroidRating").show();
      }
      if (type === 'SURVEY') {
        $scope.previewType = 'SURVEY';
        $("#AndroidInappSurvey").show();
      }
      if (type === 'WEB_POPUP') {
        $scope.previewType = 'WEB_POPUP';
        $("#web_popup_preview").show();
      }
      if (campaign.variance && campaign.variance.length > 0) {
        $scope.campaignVariantData = campaign.variance && campaign.variance.length > 0 ? campaign.variance : []
        $scope.totalStats = $scope.campaignVariantData.reduce(function (previousValue, currentValue) {
          return {
            pushedTo: previousValue.pushedTo + currentValue.pushedTo,
            receivedTo: previousValue.receivedTo + currentValue.receivedTo,
            ctr: previousValue.ctr + currentValue.ctr,
            clickedTo: previousValue.clickedTo + currentValue.clickedTo,
            conversion: previousValue.conversion + currentValue.conversion
          }
        });
      }

    } else {
      $scope.campaignStatusData = [];
    }
  }
//Render Column chart

function renderCampaignChart(platform) {
	$timeout(function(){
  let pushedArr = [];
  let clickedArr = [];
  let reachArr   = []
  let receivedArr =[]
  let ctrArr = [];
  let dateArr = [];

  let campaignStartDate = moment.utc($scope.campaignStatusData[0].sd).format('YYYY_MM_DD');

  //Extract values for chart
  const newStats = $scope.campaignStatsData;
//sort dateArray
 let unSortedArray = sumCampaignDateWise(newStats)
// Convert keys to Date objects and sort
const sortedArray = sortByDate(unSortedArray)

  Object.keys(sortedArray).forEach(date => {
    dateArr.push(date);
    let ctr;
    let pushed = sortedArray[date].Campaign_PushedTo? sortedArray[date].Campaign_PushedTo:0;
  
    let reach =   sortedArray[date].Campaign_Reach ?  sortedArray[date].Campaign_Reach:0;
    reachArr.push(parseInt(reach))
    let recieved =   sortedArray[date].Campaign_ReceivedTo ?  sortedArray[date].Campaign_ReceivedTo:0;
    receivedArr.push(parseInt(recieved))
    let clicked =   sortedArray[date].Campaign_ClickedTo?  sortedArray[date].Campaign_ClickedTo:0;
    pushedArr.push( parseInt(pushed));
    clickedArr.push( parseInt(clicked))
    if(clicked && pushed) {
      ctr = parseFloat(((clicked / pushed) * 100).toFixed(2));
      
    } else {
      ctr = 0;   
    }
    ctrArr.push(ctr);
});

  function datesToEpoch(dateStrings) {
    return dateStrings.map(dateString => {
        const [year, month, day] = dateString.split("_").map(Number);
        const date = new Date(year, month - 1, day); // Months are 0-based in JavaScript
        return date.getTime() / 1000; // Convert to seconds since epoch
    });
  }
  const epochDates = datesToEpoch(dateArr);
  const formattedDates = semusiCommon.getDateArrayFromEpochArray(epochDates)
  //this setoption will remove the space in the numbers 
    Highcharts.setOptions({
        lang: {
            thousandsSep: ""
        }
    });
    Highcharts.chart('container', {
        chart: {
          zoomType: 'xy'
        },
        title: {
          text: ''
        },
        subtitle: {
          text: ''
        },
         credits: {
          enabled: false
       },
        xAxis: [{

          categories: formattedDates,
          title: {
            text: 'Date' // Setting  the first column heading here
          },
          crosshair: true
        }],
        yAxis: [{ // Primary yAxis
          labels: {
            format: '{value}',
            style: {
              color: Highcharts.getOptions().colors[1]
            }
          },
          title: {
            text: 'CTR %',
            style: {
              color: Highcharts.getOptions().colors[4]
            }
          }
        }, { // Secondary yAxis
          title: {
            text: 'Reach',
            style: {
              color: Highcharts.getOptions().colors[3]
            }
          },
          labels: {
            format: '{value}',
            style: {
              color: Highcharts.getOptions().colors[0]
            }
          },
          opposite: true
        }],
        tooltip: {
          shared: true
        },
      
        series: [
           {
            name: 'Reach',
            type: 'column',
            yAxis: 1,
            data: reachArr,
  
            tooltip: {
              valueSuffix: ' '
            }
        
          },
          {
          name: 'Sent',
          type: 'column',
          yAxis: 1,
          data: pushedArr,

          tooltip: {
            valueSuffix: ' '
          }
      
        },{
          name: 'Received',
          type: 'column',
          yAxis: 1,
          data: receivedArr,

          tooltip: {
            valueSuffix: ' '
          }
      
        },{
          name: 'Clicked',
          type: 'column',
          yAxis: 1,
          data: clickedArr,

          tooltip: {
            valueSuffix: ' '
          }
      
        },
          {
          name: 'CTR',
          type: 'spline',
          data: ctrArr,
          tooltip: {
            valueSuffix: '%'
          }
        }]
      });
   }, 500);
}

/**
 * renderSplitData
 * This function takes an array of data objects, renames certain keys, calculates CTR and Impression Rate,
 * and then injects the modified data into the UI.
 * @param {Array} data - An array of objects containing raw data.
 */
  function renderSplitData(data) {

    // When data is present 
    $scope.isPlatformData = true;

    // Function  which will calculate CTR
    function calculateCTR(clickedTo, pushedTo) {
      if (clickedTo && pushedTo) {
        return parseFloat(((clickedTo / pushedTo) * 100).toFixed(2));
      } else {
        return 0;
      }
    }

    // Function which will calculate Impression Rate
    function calculateImpressionRate(receivedTo, pushedTo) {
      if (receivedTo && pushedTo) {
        return parseFloat((receivedTo / pushedTo) * 100).toFixed(2) + "%";
      } else {
        return 0;
      }
    }

    // Loop through each object in the data array
    data.forEach(obj => {
      // Perform the required renames
      obj.reach = obj.Campaign_Reach;
      obj.pushedTo = obj.Campaign_PushedTo;
      obj.receivedTo = obj.Campaign_ReceivedTo;
      obj.clickedTo = obj.Campaign_ClickedTo;

      // Rename platformName
      switch (obj.platformName.toLowerCase()) {
        case 'ios':
          obj.platformName = 'iOS';
          break;
        case 'android':
          obj.platformName = 'Android';
          break;
        case 'web':
          obj.platformName = 'Web';
          break;
      }
      // Calculate CTR
      obj.ctr = calculateCTR(obj.clickedTo, obj.pushedTo);

      // Calculate Impression Rate
      obj.impressionRate = calculateImpressionRate(obj.receivedTo, obj.pushedTo);
    });

    // inject data to the UI
    $scope.$applyAsync(() => {
      $scope.platformWiseData = data
    });
  }
function sortByDate(obj) {
  const sortedKeys = Object.keys(obj).sort((a, b) => {
      const dateA = new Date(a.replace(/_/g, '-'));
      const dateB = new Date(b.replace(/_/g, '-'));
      return dateA - dateB;
  });

  const sortedData = {};
  sortedKeys.forEach(key => {
      sortedData[key] = obj[key];
  });

  return sortedData;
}

/*******Sort Campaigns stats obj datewise********* */
function sumCampaignDateWise(data) {
  const result = {};

  // Iterate over the platforms (android, ios, web)
  for (const platform in data) {
    const platformData = data[platform];

    // Iterate over the dates in each platform
    for (const date in platformData) {
      if (!result[date]) {
        result[date] = {};
      }

      // Iterate over the keys (Campaign_ClickedTo, Campaign_Failed, etc.)
      for (const key in platformData[date]) {
        if (!result[date][key]) {
          result[date][key] = 0;
        }

        // Check if the key exists in the platform's data
        if (platformData[date].hasOwnProperty(key) && platformData[date][key] !== null) {
          result[date][key] += platformData[date][key];
        }
      }
    }
  }
  return result;
}

 /*  number format function  like 10K, 5M etc ... */
 function nFormatter(num) {
  if (num >= 1000000000) {
     return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
  }
  if (num >= 1000000) {
     return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
  }
  if (num >= 1000) {
     return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
  }
  if (num == 0) {
      return 'NA';
  }
  return num;
}


   init();
});
function isValidUrl(string){
  let url;
  try {
    url = new URL(string);
  } catch (_) {
    return false;  
  }
  return url.protocol === "http:" || url.protocol === "https:";   
}
