const year_chrats = document.getElementById('yearCharts');

const reporte_table = document.getElementById('reportetablevisitas');

let ventasChartObj=false;
let ventasChartCanvas=false;


let datosCharts=[];

document.addEventListener('DOMContentLoaded', function(){

  actualizarGraficoVisitasMesCliente()
})


function actualizarGraficoVisitasMesCliente() {

    if(ventasChartObj) { ventasChartObj.destroy(); }

    const anio = year_chrats.value;
    if(idcliente===false) return;
    
    const url = base_url + 'clientes/comparacionVisitasMes/' + anio +'/'+ idcliente;

    const http = new XMLHttpRequest();
    http.open("GET", url, true);
    http.send();
    http.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            const res = JSON.parse(this.responseText);
            let tablehtml='';

            datosCharts=res.visitasGroup.map(function(number) {
              return number.contador;
            });

            res.visitas.forEach(element => {

                  let parsedDate1 = new Date(element.fecha);

                  let [zoom, lat, lng] = element.coordenadas.split('|');

                  if (!lat || lat.trim() === '') lat = 0;
                  if (!lng || lng.trim() === '') lng = 0;
                 
                tablehtml+=`
                  <tr>
                    <td>${parsedDate1.toLocaleDateString('es-ES')}</td>
                    <td><button class="btn btn-link" type="button" onclick="ActualizarPin(${Number(lat)},${Number(lng)});"><i class="fas fa-map-marker-alt"></i></button>Lat: ${Number(lat)}°, Lng: ${Number(lng)}°</td>
                    <td class='text-right'>Q. ${numFormat(element.venta)}</td>
                    <td class='text-right'>Q. ${numFormat(element.pago)}</td>
                  </tr>`;
            });
            reportetablevisitas.innerHTML=tablehtml;
            
            actualizarGraficaVisitasMes();
        }
    }

}

function actualizarGraficaVisitasMes()
{
  ventasChartCanvas = $('#comparacionVentas').get(0).getContext('2d') 

  var salesChartData = {
      labels: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
      datasets: [
        {
          label: 'Visitas',
          backgroundColor: 'rgba(247,222,97,0.9)',
          borderColor: 'rgba(247,222,97,0.8)',
          pointRadius: false,
          pointColor: '#3b8bba',
          pointStrokeColor: 'rgba(247,222,97,1)',
          pointHighlightFill: '#fff',
          pointHighlightStroke: 'rgba(247,222,97,1)',
          data: datosCharts,
        }
      ]
    }
  
    var salesChartOptions = {
      maintainAspectRatio: false,
      responsive: true,
      legend: {
        display: false
      },
      scales: {
        xAxes: [{
          gridLines: {
            display: false
          }
        }],
        yAxes: [{
          gridLines: {
            display: false
          }
        }]
      }
    }
  
    ventasChartObj = new Chart(ventasChartCanvas, {
      type: 'bar',
      data: salesChartData,
      options: salesChartOptions
    }
    )
}


function numFormat(num) {
    return new Intl.NumberFormat("gt-GT").format(num)
}

function sumObj(obj) {
    return Object.keys(obj).reduce((acc, key) => acc + parseFloat(obj[key] || 0), 0);
}