// Set new default font family and font color to mimic Bootstrap's default styling
Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#858796';
$("#websiteName").html(websitetitle);

LoadDadta(validasiToken);
function LoadDadta(token){
    $(document).ready(function(){
    /* save data */
        $.ajax({
          type: 'POST',
          dataType: 'json',
          url: baseURL + '/api/loadvisitorbytime',
          data: {
              token   : token,
              year : null,
              month : null,
              country : null,
              province : null
          },
            success: function(result){
                if(result.code == 0){
                    let data = result.data;
                            
                    var location = [];
                    let jumlah = [];
                            //let counter = 0;
                    for(x in data){
                        location[x] = data[x].location;
                        jumlah[x] = data[x].total;
                    }
                    
                    var myPieChart =  {
                        type: 'pie',
                        data: {
                            labels: location,
                            datasets: [{
                                data: jumlah,
                                backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', "#c5c5c5"],
                                hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf', '#ffd700', '#c5c5c5'],
                                hoverBorderColor: "rgba(234, 236, 244, 1)",
                            }],
                        },
                        options: {
                            maintainAspectRatio: false,
                            tooltips: {
                                backgroundColor: "rgb(255,255,255)",
                                bodyFontColor: "#858796",
                                borderColor: '#dddfeb',
                                borderWidth: 1,
                                xPadding: 15,
                                yPadding: 15,
                                displayColors: false,
                                caretPadding: 10,
                            },
                            legend: {
                                display: false
                            },
                            cutoutPercentage: 0,
                        },
                    }

                    var ctx = document.getElementById("myPieChart2").getContext("2d");
                    window.myVisitorPie = getNewChart(ctx, myPieChart);
                    
                    var colour = ['primary','success','info','warning','secondary'];
                    var cols = "";
                    for(y in location){
                      cols += '<span class="mr-2"><i class="fas fa-circle text-'+colour[y]+'"></i> '+location[y]+'</span>';
                    }
                    $('#infoChartLokasi').html(cols);
              
                    $('#visitorLocation').html('Visitor Location Country');
                    
                    }else{
                        alert(result.info);
                    }
            },
            error: function(xhr) {
                alert(xhr.status+'-'+xhr.statusText);            
            }
        });
    });
}

loadselectfirst(validasiToken);
function loadselectfirst(tokeni){
    $.ajax({
        type  : "post",
        dataType  : "JSON",
        url   : baseURL + "/api/loadyear",
        data : {
          token : tokeni
        },
        success:function(result){
          let data = result.data;
          option = '';
          option += `<option value=''>All Year</option>`
          for (x in data){
            option += `<option value='`+data[x]['date_part']+`'>`+data[x]['date_part']+`</option>`;
            
          }
          $('#selectyearvisit').html(option);
        }
      });
      
      let dates = new Date();
      let year = dates.getFullYear();
    
      optionmonth = '';
      optionmonth += '<option value="">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>`;
                $('#selectmonthvisit').html(optionmonth);
            }
        }
    });
}

$('#selectyearvisit').change(function(){
    let selectyear = $('#selectyearvisit').val();
    let selectmonth = $('#selectmonthvisit').val();
    let country = $('#selectcountryvl').val();
    let province =  $('#selectprovincevl').val();
    optionmonth = '';
    optionmonth += `<option value=''>All Month</option>`;
    $.ajax({
        type : 'POST',
        dataType : 'JSON',
        url   : baseURL + "/api/loadvisitormonth",
        async : false,
        data : {
        year : selectyear,
        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>`;
            $('#selectmonthvisit').html(optionmonth);
           
        }
        }
    });
    
     
  
    changevistorbytime(selectyear, selectmonth, country, province);
});

$('#selectmonthvisit').change(function(){
    let selectyear = $('#selectyearvisit').val();
    let selectmonth = $('#selectmonthvisit').val();
    let country = $('#selectcountryvl').val();
    let province =  $('#selectprovincevl').val();
    
    changevistorbytime(selectyear, selectmonth, country, province);
});


loadselectfirstvl(validasiToken);
function loadselectfirstvl(tokeni){
  option = '';
  $.ajax({
    type  : "post",
    dataType  : "JSON",
    url   : baseURL + "/api/loadcountry",
    data : {
      token : tokeni
    },
    success:function(result){
      let data = result.data;
      option = '';
      option += `<option value=''>All Country</option>`
      for (x in data){  
        option += `<option value = `+data[x]['country']+`>`+data[x]['country']+`</option>`
      }
      $('#selectcountryvl').html(option);
    }
    
  }); 
 
    optionprov = `<option value=''>All Province</option>`
    $('#selectprovincevl').html(optionprov);
  
}

$('#selectcountryvl').change(function(){
    let country = $('#selectcountryvl').val();
    let province =  $('#selectprovincevl').val();
    let selectyear = $('#selectyearvisit').val();
    let selectmonth = $('#selectmonthvisit').val();
    $.ajax({
      type  : "post",
      dataType  : "JSON",
      url   : baseURL + "/api/loadprovince",
      data : {
        token : validasiToken,
        country : country
      },success:function(result){
        let data = result.data;
        optionprov = '';
        optionprov = `<option value=''>All Province</option>`;
  
        for (x in data){
          optionprov += `<option value = '`+data[x]['province']+`'>`+data[x]['province']+`</option>`
        }
        $('#selectprovincevl').html(optionprov);
      }
    });
  
    optionprov = `<option value=''>All Province</option>`
    $('#selectprovincevl').html(optionprov);

    changevistorbytime(selectyear, selectmonth, country, province);
    if(country){
      $('#visitorLocation').html('Visitor Location Province');
    }else{
      $('#visitorLocation').html('Visitor Location Country');
    }    
});


$('#selectprovincevl').change(function(){
    let country = $('#selectcountryvl').val();
    let province =  $('#selectprovincevl').val();
    let selectyear = $('#selectyearvisit').val();
    let selectmonth = $('#selectmonthvisit').val();

    changevistorbytime(selectyear, selectmonth, country, province);
    if(province){
      $('#visitorLocation').html('Visitor Location City');
    }else{
      $('#visitorLocation').html('Visitor Location Province');
    }

});


function changevistorbytime(year, month, country, province){
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/api/loadvisitorbytime',
        data: {
            token   : validasiToken,
            year : year,
            month : month,
            country : country,
            province : province
        },
        success: function(result){
            // console.log(result.data);
            let data = result.data;
            // console.log(data);

            let location = [];
            let total = [];

            for (x in data){
                location[x] = data[x]['location'];
                total[x] = data[x]['total'];
            }
            myPieChartnew = {
                labels: location,
                datasets: [{
                    data: total,
                    backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', "#c5c5c5"],
                    hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf', '#ffd700', '#c5c5c5'],
                    hoverBorderColor: "rgba(234, 236, 244, 1)",
                }],
              };
              myVisitorPie.data = myPieChartnew;
              window.myVisitorPie.update();

              var colour = ['primary','success','info','warning','secondary'];
              var cols = "";
              for(y in location){
                cols += '<span class="mr-2"><i class="fas fa-circle text-'+colour[y]+'"></i> '+location[y]+'</span>';
              }
              $('#infoChartLokasi').html(cols);
        }
    });
}