

Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#858796';
var config;



function number_format(number, decimals, dec_point, thousands_sep) {
  number = (number + '').replace(',', '').replace(' ', '');
  var n = !isFinite(+number) ? 0 : +number,
  prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
  sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
  dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
  s = '',
  toFixedFix = function(n, prec) {
    var k = Math.pow(10, prec);
    return '' + Math.round(n * k) / k;
  };
  // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
}

window.setInterval(function(){
  loaddatavisitor();
},60000); 

loaddatavisitor();

function loaddatavisitor(){
  dates = new Date();
  year = dates.getFullYear();
  
  $.ajax({
    type : 'POST',
    dataType : 'JSON',
    url   : baseURL + "/api/loadvisitorperyear",
    async : false,
    data : {
      year : year,
      token : validasiToken
    },
    success:function(result){
      var data = result.data;
      months = ['Jan', 'Feb', 'Mar', 'April', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
      total =[0,0,0,0,0,0,0,0,0,0,0,0];
      for (x in data){
        if(data[x]['month'] == 1 ){
          total[0] = data[x]['total'];
        }
        if(data[x]['month'] == 2 ){
          total[1] = data[x]['total'];
        }
        if(data[x]['month'] == 3 ){
          total[2] = data[x]['total'];
        }
        if(data[x]['month'] == 4 ){
          total[3] = data[x]['total'];
        }
        if(data[x]['month'] == 5 ){
          total[4] = data[x]['total'];
        }
        if(data[x]['month'] == 6 ){
          total[5] = data[x]['total'];
        }
        if(data[x]['month'] == 7 ){
          total[6] = data[x]['total'];
        }
        if(data[x]['month'] == 8 ){
          total[7] = data[x]['total'];
        }
        if(data[x]['month'] == 9 ){
          total[8] = data[x]['total'];
        }
        if(data[x]['month'] == 10 ){
          total[9] = data[x]['total'];
        }
        if(data[x]['month'] == 11 ){
          total[10] = data[x]['total'];
        }
        if(data[x]['month'] == 12 ){
          total[11] = data[x]['total'];
        }
      
      }
      $('#totVisitor').html('Total Vistor '+year);
    }
  })
  config = {
    type: 'line',
    data: {
          labels: months,
          datasets: [{
                label: "Jumlah",
                lineTension: 0,
                backgroundColor: "rgba(78, 115, 223, 0.05)",
                borderColor: "rgba(78, 115, 223, 1)",
                pointRadius: 3,
                pointBackgroundColor: "rgba(78, 115, 223, 1)",
                pointBorderColor: "rgba(78, 115, 223, 1)",
                pointHoverRadius: 3,
                pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
                pointHoverBorderColor: "rgba(78, 115, 223, 1)",
                pointHitRadius: 10,
                pointBorderWidth: 2,
                data: total,
          }],
    },
    options:{
      maintainAspectRatio: false,
      layout: {
        padding: {
          left: 10,
          right: 25,
          top: 25,
          bottom: 0
        }
      },
      scales: {
        xAxes: [{
          time: {
            unit: 'date'
          },
          gridLines: {
            display: false,
            drawBorder: false
          },
          ticks: {
            maxTicksLimit: 7
          }
        }],
        yAxes: [{
          ticks: {
            stepSize: 10,
            beginAtZero: true,
            maxTicksLimit: 5,
            padding: 10,
              // Include a dollar sign in the ticks
            callback: function(value, index, values) {
              return number_format(value);
            }
          },
          gridLines: {
            color: "rgb(234, 236, 244)",
            zeroLineColor: "rgb(234, 236, 244)",
            drawBorder: false,
            borderDash: [2],
            zeroLineBorderDash: [2]
          }
        }],
      },
      legend: {
        display: false
      },
      tooltips: {
        backgroundColor: "rgb(255,255,255)",
        bodyFontColor: "#858796",
        titleMarginBottom: 10,
        titleFontColor: '#6e707e',
        titleFontSize: 14,
        borderColor: '#dddfeb',
        borderWidth: 1,
        xPadding: 15,
        yPadding: 15,
        displayColors: false,
        intersect: false,
        mode: 'index',
        caretPadding: 10,
        callbacks: {
          label: function(tooltipItem, chart) {
            var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
            return datasetLabel + ': ' + number_format(tooltipItem.yLabel);
          }
        }
      }
    }
  }
}

  

  function changefunct(){
    var selectyear = document.getElementById("selectyear");
    var selectedyear = selectyear.options[selectyear.selectedIndex].value;
    
      bulan = [];
      jumlah = [];
      $.ajax({
        type : 'POST',
        dataType : 'JSON',
        url   : baseURL + "/api/loadvisitorperyear",
        async : false,
        data : {
          year : selectedyear,
          token : validasiToken
        },
        success:function(result){
          var data = result.data;
          months = ['Jan', 'Feb', 'Mar', 'April', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
          total =[0,0,0,0,0,0,0,0,0,0,0,0];
          for (x in data){
            if(data[x]['month'] == 1 ){
              total[0] = data[x]['total'];
            }
            if(data[x]['month'] == 2 ){
              total[1] = data[x]['total'];
            }
            if(data[x]['month'] == 3 ){
              total[2] = data[x]['total'];
            }
            if(data[x]['month'] == 4 ){
              total[3] = data[x]['total'];
            }
            if(data[x]['month'] == 5 ){
              total[4] = data[x]['total'];
            }
            if(data[x]['month'] == 6 ){
              total[5] = data[x]['total'];
            }
            if(data[x]['month'] == 7 ){
              total[6] = data[x]['total'];
            }
            if(data[x]['month'] == 8 ){
              total[7] = data[x]['total'];
            }
            if(data[x]['month'] == 9 ){
              total[8] = data[x]['total'];
            }
            if(data[x]['month'] == 10 ){
              total[9] = data[x]['total'];
            }
            if(data[x]['month'] == 11 ){
              total[10] = data[x]['total'];
            }
            if(data[x]['month'] == 12 ){
              total[11] = data[x]['total'];
            }
          
          }
          $('#totVisitor').html('Total Vistor '+selectedyear);
        }
      })
      
      var newDataObject = {
        labels: months,
          datasets: [{
                label: "Jumlah",
                lineTension: 0,
                backgroundColor: "rgba(78, 115, 223, 0.05)",
                borderColor: "rgba(78, 115, 223, 1)",
                pointRadius: 3,
                pointBackgroundColor: "rgba(78, 115, 223, 1)",
                pointBorderColor: "rgba(78, 115, 223, 1)",
                pointHoverRadius: 3,
                pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
                pointHoverBorderColor: "rgba(78, 115, 223, 1)",
                pointHitRadius: 10,
                pointBorderWidth: 2,
                data: total,
          }],
      };
    
    myLine.data = newDataObject;
    window.myLine.update();
   
  }

  function changemonthfunc(){
    var selectyear = document.getElementById("selectyear");
    var selectedyear = selectyear.options[selectyear.selectedIndex].value;

    var selectedmonth = $('#selectmonth').val();
    if(selectedmonth=='All Month'){
      changefunct();
    }else{
      $.ajax({
        type : 'POST',
        dataType : 'JSON',
        url   : baseURL + "/api/loadvisitorbymonth",
        async : false,
        data : {
          year : selectedyear,
          month : selectedmonth,
          token : validasiToken
        },
        success:function(result){
          let data = result.data;
          week = ['week 1', 'week 2', 'week 3', 'week 4'];
          total = [0,0,0,0];
          for (x in data){
            if(data[x]['week']==1){
              total[0] = data[x]['total'];
            }
            if(data[x]['week']==2){
              total[1] = data[x]['total'];
            }
            if(data[x]['week']==3){
              total[2] = data[x]['total'];
            }
            if(data[x]['week']==4){
              total[3] = data[x]['total'];
            }
            if(data[x]['week']==5){
              week.push('week 5');
              total[4] = data[x]['total'];
            }
          }

          var newDataObject = {
            labels: week,
            datasets: [{
              label: "Jumlah",
              lineTension: 0,
              backgroundColor: "rgba(78, 115, 223, 0.05)",
              borderColor: "rgba(78, 115, 223, 1)",
              pointRadius: 3,
              pointBackgroundColor: "rgba(78, 115, 223, 1)",
              pointBorderColor: "rgba(78, 115, 223, 1)",
              pointHoverRadius: 3,
              pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
              pointHoverBorderColor: "rgba(78, 115, 223, 1)",
              pointHitRadius: 10,
              pointBorderWidth: 2,
              data: total,
            }],
          };
    
          myLine.data = newDataObject;
          window.myLine.update();
          $('#totVisitor').html('Total Vistor '+selectedyear);
        }
      })
  
    }
  }

loadselectfirst(validasiToken);
function loadselectfirst(tokeni){
  $.ajax({
    type  : "post",
    dataType  : "JSON",
    url   : baseURL + "/api/loadyear",
    data : {
      token : tokeni
    },
    success:function(result){
      let data = result.data;
      
      for (x in data){
        option = '';
        option += `<option val='`+data[x]['date_part']+`'>`+data[x]['date_part']+`</option>`;
        $('#selectyear').append(option);
      }
    }
  });
  
  let dates = new Date();
  let year = dates.getFullYear();

  optionmonth = '';
  optionmonth += '<option>All Month</option>';

  $.ajax({
    type : 'POST',
    dataType : 'JSON',
    url   : baseURL + "/api/loadvisitormonth",
    async : false,
    data : {
      year : year,
      token : validasiToken
    },
    success:function(result){

      let data = result.data;
      var month = [];
      
      for(x in data){
        month[x] = data[x]['month']
        if(month[x]==1){
          month[x]='Jan';
        }else if(month[x]==2){
          month[x]='Feb';
        }else if(month[x]==3){
          month[x]='Mar';
        }else if(month[x]==4){
          month[x]='April';
        }else if(month[x]==5){
          month[x]='May';
        }else if(month[x]==6){
          month[x]='Jun';
        }else if(month[x]==7){
          month[x]='Jul';
        }else if(month[x]==8){
          month[x]='Aug';
        }else if(month[x]==9){
          month[x]='Sept';
        }else if(month[x]==10){
          month[x]='Oct';
        }else if(month[x]==11){
          month[x]='Nov';
        }else if(month[x]==12){
          month[x]='Dec';
        }
        optionmonth += `<option value='`+data[x]['month']+`'>`+month[x]+`</option>`;
        $('#selectmonth').html(optionmonth);
      }
    }
  });
}

$('#selectyear').change(function(){
  var selectyear = document.getElementById("selectyear");
  var selectedyear = selectyear.options[selectyear.selectedIndex].value;

  optionmonth = '';
  optionmonth += `<option val=''>All Month</option>`;

  $.ajax({
    type : 'POST',
    dataType : 'JSON',
    url   : baseURL + "/api/loadvisitormonth",
    async : false,
    data : {
      year : selectedyear,
      token : validasiToken
    },
    success:function(result){

      let data = result.data;
      var month = [];
      
      for(x in data){
        month[x] = data[x]['month']
        if(month[x]==1){
          month[x]='Januari';
        }else if(month[x]==2){
          month[x]='Februari';
        }else if(month[x]==3){
          month[x]='Maret';
        }else if(month[x]==4){
          month[x]='April';
        }else if(month[x]==5){
          month[x]='Mei';
        }else if(month[x]==6){
          month[x]='Juni';
        }else if(month[x]==7){
          month[x]='Juli';
        }else if(month[x]==8){
          month[x]='Agustus';
        }else if(month[x]==9){
          month[x]='September';
        }else if(month[x]==10){
          month[x]='Oktober';
        }else if(month[x]==11){
          month[x]='November';
        }else if(month[x]==12){
          month[x]='Desember';
        }
        optionmonth += `<option value='`+data[x]['month']+`'>`+month[x]+`</option>`;
        $('#selectmonth').html(optionmonth);
      }
    }
  });
});

window.onload = function() {
  var ctx = document.getElementById("myAreaChart").getContext("2d");
  window.myLine = getNewChart(ctx, config);
};

function getNewChart(canvas, config) {
  return new Chart(canvas, config);
}


