// FILTRO POR AÑO
const year_chrats = document.getElementById('yearCharts');

// PAGINA 1 - VENTAS MENSUALES
const nombre_cliente = document.getElementById('nombreCliente');
const direccion_cliente = document.getElementById('direccionCliente');
const area_estadocliente = document.getElementById('area_estadocliente');
const reporte_table = document.getElementById('reportetable');

/*const limite_credito = document.getElementById('limitecreditoCliente');
const dias_credito = document.getElementById('diascreditoCliente');
const saldo_cliente = document.getElementById('saldoCliente');
const vendedor_cliente = document.getElementById('vendedorCliente');
const ultimaventa_cliente=document.getElementById('ultimaventaCliente');
const ultimopago_cliente=document.getElementById('ultimopagoCliente');
const ultimavisita_cliente=document.getElementById('ultimavisitaCliente');
*/

// PAGINA 2 - VENTAS POR CATEGORIA Y PRODUCTO
const reporte_categorias = document.getElementById('tablaCategorias');
const reporte_productos = document.getElementById('tablaProductos');

// PAGINA 3 - HISTORIAL DE VISITAS
const reporte_tablevisitas = document.getElementById('reportetablevisitas');

// PAGINA 4 - VENTAS POR CATEGORIA Y PRODUCTO
const reporte_tablapagos = document.getElementById('tablaPagos');

// PAGINA 5 - VENTAS POR CATEGORIA Y PRODUCTO
const reporte_tablafacturas = document.getElementById('tablaFacturas');

let categoriaSeleccionada = '';

//OBJETOS
let ventasChartObj=false;
let ventasChartCanvas=false;
let pagosChartObj=false;
let pagosChartCanvas=false;
let ventaspagosChartObj=false;
let ventaspagosChartCanvas=false;

let visitasChartObj=false;
let visitasChartCanvas=false;

let datosCharts={};

document.addEventListener('DOMContentLoaded', function(){
    btnReporteCli(idcliente)
})

function btnReporteCli(id)
{
    if(id===false) return;

    const url = base_url + 'clientes/editar/' + id;
    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);

            nombre_cliente.innerHTML=`[${res.id}] ${res.nombre}`;
            direccion_cliente.innerHTML=`${res.direccion}`;

            let class_limite_credito=(Number(res.saldo)>Number(res.limite_credito)) ? 'danger' : 'info';
            let class_dias_credito= (Number(res.facturas_vencidas)>0) ? 'danger' : 'info';
            let class_saldo_cliente= (Number(res.saldo)>Number(res.limite_credito)) ? 'danger' : 'success';
            let class_ultimaventa_cliente = (diasDesde( res.ultimaventa ) < 30) ? 'success' : (diasDesde( res.ultimaventa ) < 60) ? 'warning' : 'danger';
            let class_ultimopago_cliente = (diasDesde( res.ultimopago ) < 30) ? 'success' : (diasDesde( res.ultimopago ) < 60) ? 'warning' : 'danger';
            let class_ultimavisita_cliente = (diasDesde( res.ultimavisita ) < 30) ? 'success' : (diasDesde( res.ultimavisita ) < 60) ? 'warning' : 'danger';

            area_estadocliente.innerHTML=`
            <div class='d-none d-md-block'>
                <button type="button" class="btn btn-${class_limite_credito} btn-sm"><strong>Límite de Crédito</strong></br>${res.limite_credito}</button>
                <button type="button" class="btn btn-info btn-${class_dias_credito} btn-sm"><strong>Dias Crédito</strong></br>${res.dias_credito}</button>
                <button type="button" class="btn btn-success btn-${class_saldo_cliente} btn-sm"><strong>Saldo</strong></br>${res.saldo}</button>
                <button type="button" class="btn btn-primary btn-sm"><strong>Vendedor</strong></br>${res.id_vendedor1}</button>
                <button type="button" class="btn btn-${class_ultimaventa_cliente} btn-sm"><strong>Última Venta</strong></br>${mostrarfecha(res.ultimaventa)}</button>
                <button type="button" class="btn btn-${class_ultimopago_cliente} btn-sm"><strong>Último Pago</strong></br>${mostrarfecha(res.ultimopago)}</button>
                <button type="button" class="btn btn-${class_ultimavisita_cliente} btn-sm"><strong>Última Visita</strong></br>${mostrarfecha(res.ultimavisita,true)}</button>
            </div>

            <ul class="list-group d-md-none">
                <li class="list-group-item d-flex justify-content-between align-items-center list-group-item-${class_limite_credito}" style='line-height:0.9em;font-size:0.9em;'><strong>Limite de Credito</strong><span class="badge badge-dark badge-pill">${res.limite_credito}</span></li>
                <li class="list-group-item d-flex justify-content-between align-items-center list-group-item-${class_dias_credito}" style='line-height:0.9em;font-size:0.9em;'><strong>Dias Crédito</strong><span class="badge badge-dark badge-pill">${res.dias_credito}</span></li>
                <li class="list-group-item d-flex justify-content-between align-items-center list-group-item-${class_saldo_cliente}" style='line-height:0.9em;font-size:0.9em;'><strong>Saldo</strong><span class="badge badge-dark badge-pill">${res.saldo}</span></li>
                <li class="list-group-item d-flex justify-content-between align-items-center list-group-item-primary" style='line-height:0.9em;font-size:0.9em;'><strong>Vendedor</strong><span class="badge badge-dark badge-pill">${res.id_vendedor1}</span></li>
                <li class="list-group-item d-flex justify-content-between align-items-center list-group-item-${class_ultimaventa_cliente}" style='line-height:0.9em;font-size:0.9em;'><strong>Última Venta</strong><span class="badge badge-dark badge-pill">${mostrarfecha(res.ultimaventa)}</span></li>
                <li class="list-group-item d-flex justify-content-between align-items-center list-group-item-${class_ultimopago_cliente}" style='line-height:0.9em;font-size:0.9em;'><strong>Último Pago</strong><span class="badge badge-dark badge-pill">${mostrarfecha(res.ultimopago)}</span></li>
                <li class="list-group-item d-flex justify-content-between align-items-center list-group-item-${class_ultimavisita_cliente}" style='line-height:0.9em;font-size:0.9em;'><strong>Última Visita</strong><span class="badge badge-dark badge-pill">${mostrarfecha(res.ultimavisita,true)}</span></li>
            </ul>`;

            iniciarReportes()
        }
    }    
}

function iniciarReportes()
{
    const anio = year_chrats.value;
    if(idcliente===false) return;
    const url = base_url + 'clientes/comparacionVentasPagosMes/' + 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);

            datosCharts.pagos=res.pagos;
            datosCharts.ventas=res.ventas;
            datosCharts.visitas=res.visitas;
            
            categoriaSeleccionada = '';

            actualizarGraficoVentasMesCliente();
            actualizarGraficoPagosMesCliente();
            actualizarGraficoVentasPagosMesCliente();   
            tableVentasPagos();
            iniciarReportesPagina2();
            iniciarReportesPagos();
            iniciarReportesFacturas();
            actualizarGraficoVisitasMesCliente();
            //actualizarGraficaVisitasMes()
        }
    }
   
}


// FUNCIONES PAGINA 1 - VENTAS Y PAGOS POR MES

function selectLinea(cod_linea)
{
    if(categoriaSeleccionada === cod_linea)
    {
        categoriaSeleccionada = '';
        document.querySelectorAll('#tablaCategorias tbody tr').forEach(row => { row.classList.remove('bg-primary','text-white'); });
        document.querySelectorAll('#tablaProductos tbody tr').forEach(row => { row.classList.remove('d-none'); });

    } else {
        categoriaSeleccionada = cod_linea;
        document.querySelectorAll('#tablaCategorias tbody tr').forEach(row => {
            if(row.getAttribute('data-codigo') === categoriaSeleccionada) { row.classList.add('bg-primary','text-white'); } else { row.classList.remove('bg-primary','text-white'); }
        });

        document.querySelectorAll('#tablaProductos tbody tr').forEach(row => {
            if(row.getAttribute('data-codigo') === categoriaSeleccionada) { row.classList.remove('d-none'); } else { row.classList.add('d-none'); }
        });
    }
}

function actualizarGraficoVentasPagosMesCliente() {

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

    ventaspagosChartCanvas = $('#comparacionVentasPagos').get(0).getContext('2d')

    var salesChartData = {
      labels: ['Enero', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
      datasets: [
        {
          label: 'Pagos',
          backgroundColor: 'rgba(220,53,69, 1)',
          borderColor: 'rgba(220,53,69, 1)',
          pointRadius: false,
          pointColor: '#3b8bba',
          pointStrokeColor: 'rgba(220,53,69, 1)',
          pointHighlightFill: '#fff',
          pointHighlightStroke: 'rgba(220,53,69, 1)',
          data: [datosCharts.pagos.ene, datosCharts.pagos.feb, datosCharts.pagos.mar, datosCharts.pagos.abr, datosCharts.pagos.may, datosCharts.pagos.jun, datosCharts.pagos.jul, datosCharts.pagos.ago, datosCharts.pagos.sep, datosCharts.pagos.oct, datosCharts.pagos.nov, datosCharts.pagos.dic],
        },
        { 
          label: 'Ventas',
          backgroundColor: 'rgba(40,167,69,0.9)',
          borderColor: 'rgba(40,167,69,0.9)',
          pointRadius: false,
          pointColor: 'rgba(40,167,69,0.9)',
          pointStrokeColor: '#c1c7d1',
          pointHighlightFill: '#fff',
          pointHighlightStroke: 'rgba(220,220,220,1)',
          data: [datosCharts.ventas.ene, datosCharts.ventas.feb, datosCharts.ventas.mar, datosCharts.ventas.abr, datosCharts.ventas.may, datosCharts.ventas.jun, datosCharts.ventas.jul, datosCharts.ventas.ago, datosCharts.ventas.sep, datosCharts.ventas.oct, datosCharts.ventas.nov, datosCharts.ventas.dic],
        }        
      ]
    }
  
    var salesChartOptions = {
      maintainAspectRatio: false,
      responsive: true,
      legend: {
        display: false
      },
      scales: {
        xAxes: [{
          gridLines: {
            display: false
          }
        }],
        yAxes: [{
          gridLines: {
            display: false
          }
        }]
      }
    }
  
    // This will get the first returned node in the jQuery collection.
    // eslint-disable-next-line no-unused-vars
    ventaspagosChartObj = new Chart(ventaspagosChartCanvas, {
      type: 'line',
      data: salesChartData,
      options: salesChartOptions
    }
    )


/*    var salesChartData = {
        labels: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        datasets: [
          {
            label: 'Pagos',
            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.pagos.ene, datosCharts.pagos.feb, datosCharts.pagos.mar, datosCharts.pagos.abr, datosCharts.pagos.may, datosCharts.pagos.jun, datosCharts.pagos.jul, datosCharts.pagos.ago, datosCharts.pagos.sep, datosCharts.pagos.oct, datosCharts.pagos.nov, datosCharts.pagos.dic],
          }
        ]
      }
    
      var salesChartOptions = {
        maintainAspectRatio: false,
        responsive: true,
        legend: {
          display: false
        },
        scales: {
          xAxes: [{
            gridLines: {
              display: false
            }
          }],
          yAxes: [{
            gridLines: {
              display: false
            }
          }]
        }
      }
    
      // This will get the first returned node in the jQuery collection.
      // eslint-disable-next-line no-unused-vars
      ventaspagosChartObj = new Chart(ventaspagosChartCanvas, {
        type: 'bar',
        data: salesChartData,
        options: salesChartOptions
      }
      )*/

}

function actualizarGraficoPagosMesCliente() {
   
    if(pagosChartObj) { pagosChartObj.destroy(); }

    pagosChartCanvas = $('#comparacionPagos').get(0).getContext('2d') 

    var salesChartData = {
        labels: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        datasets: [
          {
            label: 'Pagos',
            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.pagos.ene, datosCharts.pagos.feb, datosCharts.pagos.mar, datosCharts.pagos.abr, datosCharts.pagos.may, datosCharts.pagos.jun, datosCharts.pagos.jul, datosCharts.pagos.ago, datosCharts.pagos.sep, datosCharts.pagos.oct, datosCharts.pagos.nov, datosCharts.pagos.dic],
          }
        ]
      }
    
      var salesChartOptions = {
        maintainAspectRatio: false,
        responsive: true,
        legend: {
          display: false
        },
        scales: {
          xAxes: [{
            gridLines: {
              display: false
            }
          }],
          yAxes: [{
            gridLines: {
              display: false
            }
          }]
        }
      }
    
      // This will get the first returned node in the jQuery collection.
      // eslint-disable-next-line no-unused-vars
      pagosChartObj = new Chart(pagosChartCanvas, {
        type: 'bar',
        data: salesChartData,
        options: salesChartOptions
      }
      )

}

function actualizarGraficoVentasMesCliente() {

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

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

            datosCharts.ventas;

            var salesChartData = {
                labels: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
                datasets: [
                  {
                    label: 'Ventas',
                    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.ventas.ene, datosCharts.ventas.feb, datosCharts.ventas.mar, datosCharts.ventas.abr, datosCharts.ventas.may, datosCharts.ventas.jun, datosCharts.ventas.jul, datosCharts.ventas.ago, datosCharts.ventas.sep, datosCharts.ventas.oct, datosCharts.ventas.nov, datosCharts.ventas.dic],
                  }
                ]
              }
            
              var salesChartOptions = {
                maintainAspectRatio: false,
                responsive: true,
                legend: {
                  display: false
                },
                scales: {
                  xAxes: [{
                    gridLines: {
                      display: false
                    }
                  }],
                  yAxes: [{
                    gridLines: {
                      display: false
                    }
                  }]
                }
              }
            
              // This will get the first returned node in the jQuery collection.
              // eslint-disable-next-line no-unused-vars
              ventasChartObj = new Chart(ventasChartCanvas, {
                type: 'bar',
                data: salesChartData,
                options: salesChartOptions
              }
              )

}

function tableVentasPagos()
{
         let total_ventas=sumObj(datosCharts.ventas);
         let total_pagos=sumObj(datosCharts.pagos);

         reporte_table.innerHTML=`
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>ENERO</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.ene)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.ene)}</p>
                    </div>                    
            </td>
            <th scope="row" class='d-none d-md-table-cell'>Enero</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.ene)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.ene)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>FEBRERO</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.feb)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.feb)}</p>
                    </div>                    
            </td>         
            <th scope="row" class='d-none d-md-table-cell'>Febrero</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.feb)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.feb)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>MARZO</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.mar)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.mar)}</p>
                    </div>                    
            </td>
            <th scope="row" class='d-none d-md-table-cell'>Marzo</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.mar)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.mar)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>ABRIL</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.abr)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.abr)}</p>
                    </div>                    
            </td>         
            <th scope="row" class='d-none d-md-table-cell'>Abril</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.abr)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.abr)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>MAYO</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.may)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.may)}</p>
                    </div>                    
            </td>          
            <th scope="row" class='d-none d-md-table-cell'>Mayo</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.may)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.may)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>JUNIO</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.jun)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.jun)}</p>
                    </div>                    
            </td>            
            <th scope="row" class='d-none d-md-table-cell'>Junio</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.jun)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.jun)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>JULIO</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.jul)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.jul)}</p>
                    </div>                    
            </td>         
            <th scope="row" class='d-none d-md-table-cell'>Julio</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.jul)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.jul)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>AGOSTO</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.ago)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.ago)}</p>
                    </div>                    
            </td>         
            <th scope="row" class='d-none d-md-table-cell'>Agosto</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.ago)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.ago)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>SEPTIEMBRE</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.sep)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.sep)}</p>
                    </div>                    
            </td>         
            <th scope="row" class='d-none d-md-table-cell'>Septiembre</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.sep)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.sep)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>OCTUBRE</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.oct)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.oct)}</p>
                    </div>                    
            </td>          
            <th scope="row" class='d-none d-md-table-cell'>Octubre</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.oct)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.oct)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>NOVIEMBRE</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.nov)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.nov)}</p>
                    </div>                    
            </td>         
            <th scope="row" class='d-none d-md-table-cell'>Noviembre</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.nov)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.nov)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>DICIEMBRE</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.ventas.dic)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(datosCharts.pagos.dic)}</p>
                    </div>                    
            </td>         
            <th scope="row" class='d-none d-md-table-cell'>Diciembre</th>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.ventas.dic)}</td>
            <td class='text-right d-none d-md-table-cell'>Q.${numFormat(datosCharts.pagos.dic)}</td>
         </tr>
         <tr>
            <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small></small>
                        <p class="mb-0"><strong>TOTAL</strong></p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Ventas</strong></small>
                        <p class="mb-0">Q.${numFormat(total_ventas)}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>Pagos</strong></small>
                        <p class="mb-0">Q.${numFormat(total_pagos)}</p>
                    </div>                    
            </td>         
            <th scope="row" class='d-none d-md-table-cell'>TOTAL</th>
            <th class='text-right d-none d-md-table-cell'>Q.${numFormat(total_ventas)}</th>
            <th class='text-right d-none d-md-table-cell'>Q.${numFormat(total_pagos)}</th>
         </tr>`

}



// FUNCIONES PAGINA 2 - VENTAS POR CATEGORIA Y PRODUCTOS

function iniciarReportesPagina2()
{
    reporte_categorias.innerHTML=`<div class="spinner-grow spinner-grow-sm mr-2" role="status"></div> <span class='text-secondary'>Cargando...</span>`;
    reporte_productos.innerHTML=``;

    const anio = year_chrats.value;
    if(idcliente===false) return;
    const url = base_url + 'clientes/reporteVentasCliente/' + 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);

            actualizarTablaCategorias(res.categorias);
            actualizarTablaProductos(res.productos);
        }
    }
   
}

function iniciarReportesFacturas()
{
  reporte_tablafacturas.innerHTML=`<div class="spinner-grow spinner-grow-sm mr-2" role="status"></div> <span class='text-secondary'>Cargando...</span>`;

  const anio = year_chrats.value;
  if(idcliente===false) return;
  const url = base_url + 'clientes/reporteFacturas/' + 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 = `<div class="table-responsive">
                        <table class='table table-sm table-striped'>
                        <thead class="thead-dark">
                            <tr>
                                <th scope="col" class='d-table-cell d-md-none pl-2'>FACTURA</th>
                                <th scope="col" class='d-none d-md-table-cell'>NÚMERO</th>
                                <th scope="col" class='d-none d-md-table-cell'>FECHA</th>
                                <th scope="col" class='text-right d-none d-md-table-cell'>VALOR</th>
                                <th scope="col" class='text-right d-none d-md-table-cell'>SALDO</th>
                                <th scope="col" class='text-right d-none d-md-table-cell'>FACTURA</th>
                            </tr>
                        </thead>
                        <tbody>
                        </div>`;
        res.facturas.forEach(prod => {

          tableHTML += `
            <tr  class="${(prod.saldo>0)?'table-danger':''}" data-fecha='${dateToTimestamp(prod.fecha,0)}'>
                <td class='text-right d-table-cell d-md-none pl-2'>

                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>NÚMERO</strong></small>
                            <p class="mb-0">${prod.numero}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>FECHA</strong></small>
                            <p class="mb-0">${mostrarfecha(prod.fecha)}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>VALOR</strong></small>                        
                            <p class="mb-0">${prod.valor!== undefined ? 'Q.'+numFormat(prod.valor) : 'N/A'}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>SALDO</strong></small>                        
                            <p class="mb-0">${prod.saldo!== undefined ? 'Q.'+numFormat(prod.saldo) : 'N/A'}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between mt-1">
                            <small></small>
                            <button type='button' class="btn btn-success btn-sm" onclick="open_link(base_url +'ventas/generarPdf/${prod.numero}')"><i class="fas fa-file-pdf"></i></button>
                        </div>                        
                </td>
                <td class='text-right d-none d-md-table-cell'>${prod.numero}</td>
                <td class='d-none d-md-table-cell'>${mostrarfecha(prod.fecha)} ${prod.fecha}</td>
                <td class='text-right d-none d-md-table-cell'>${prod.valor!== undefined ? 'Q.'+numFormat(prod.valor) : 'N/A'}</td>
                <td class='text-right d-none d-md-table-cell'>${prod.saldo!== undefined ? 'Q.'+numFormat(prod.saldo) : 'N/A'}</td>
                <td class='text-right d-none d-md-table-cell'><button type='button' class="btn btn-success btn-sm" onclick="open_link(base_url +'ventas/generarPdf/${prod.numero}')"><i class="fas fa-file-pdf"></i></button></td>
            </tr>`;
        });

          tableHTML += `</tbody></table>`;
          reporte_tablafacturas.innerHTML = tableHTML;       

      }
    }
    limpiar_fechas_facturas()
}

function select_fecha_facturas()
{
    document.getElementById('fechaFacturasEnd').min=document.getElementById('fechaFacturasInit').value;
    filtrarReportesFacturas();
}

function limpiar_fechas_facturas()
{
    document.getElementById('fechaFacturasInit').value='';
    document.getElementById('fechaFacturasEnd').value='';
    select_fecha_facturas();
}

function filtrarReportesFacturas()
{
    busqueda_fecha=false;
    fechaInicio = dateToTimestamp(document.getElementById('fechaFacturasInit').value);
    fechaFinal = dateToTimestamp(document.getElementById('fechaFacturasEnd').value);
    let fechaAttr='';

    if(isNaN(fechaInicio) || isNaN(fechaFinal))
    {
        document.querySelectorAll('#tablaFacturas tbody tr').forEach(row => {
                row.classList.remove('d-none');
        });        
    } else {

        document.querySelectorAll('#tablaFacturas tbody tr').forEach(row => {
            fechaAttr=+row.getAttribute('data-fecha');
            if(fechaInicio <= fechaAttr && fechaFinal >= fechaAttr)
            {
                row.classList.remove('d-none');
            } else {
                row.classList.add('d-none');
            }
        });

    }
}

function select_fecha_pagos()
{
    document.getElementById('fechaPagosEnd').min=document.getElementById('fechaPagosInit').value;
    filtrarReportesPagos();
}

function limpiar_fechas_pagos()
{
    document.getElementById('fechaPagosInit').value='';
    document.getElementById('fechaPagosEnd').value='';
    document.getElementById('tiposPagos').value='';
    select_fecha_pagos();
}

function filtrarReportesPagos()
{
    busqueda_fecha=false;
    fechaInicio = dateToTimestamp(document.getElementById('fechaPagosInit').value);
    fechaFinal = dateToTimestamp(document.getElementById('fechaPagosEnd').value);
    tipoPago = document.getElementById('tiposPagos').value;
    let fechaAttr='';

    document.querySelectorAll('#tablaPagos tbody tr').forEach(row => {
            row.classList.remove('d-none');
    });

    if(!isNaN(fechaInicio) && !isNaN(fechaFinal))
    {
        document.querySelectorAll('#tablaPagos tbody tr').forEach(row => {
            fechaAttr=+row.getAttribute('data-fecha');
            if(fechaInicio <= fechaAttr && fechaFinal >= fechaAttr)
            {
                row.classList.remove('d-none');
            } else {
                row.classList.add('d-none');
            }
        });
    }
    
    if(tipoPago!='')
    {
        document.querySelectorAll('#tablaPagos tbody tr').forEach(row => {
            tipo=row.getAttribute('data-tipo');
            if(tipoPago!=tipo)
            {
                row.classList.add('d-none');
            }
        });
    }
}

function iniciarReportesPagos()
{
  reporte_tablapagos.innerHTML=`<div class="spinner-grow spinner-grow-sm mr-2" role="status"></div> <span class='text-secondary'>Cargando...</span>`;

  const anio = year_chrats.value;
  if(idcliente===false) return;
  const url = base_url + 'clientes/reportePagos/' + 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 = `<div class="table-responsive">
                        <table class='table table-sm table-striped'>
                        <thead class="thead-dark">
                            <tr>
                                <th scope="col" class='d-table-cell d-md-none pl-2'>PAGOS</th>
                                <th scope="col" class='text-right d-none d-md-table-cell'>NÚMERO</th>
                                <th scope="col" class='d-none d-md-table-cell'>FECHA</th>
                                <th scope="col" class='text-right d-none d-md-table-cell'>VALOR</th>
                                <th scope="col" class='d-none d-md-table-cell'>TIPO</th>
                                <th scope="col" class='d-none d-md-table-cell'>BANCO</th>
                                <th scope="col" class='d-none d-md-table-cell'>REFERENCIA</th>
                                <th scope="col" class='d-none d-md-table-cell'>OBSERVACIONES</th>
                                <th scope="col" class='text-right d-none d-md-table-cell'>RECIBO</th>
                            </tr>
                        </thead>
                        <tbody>
                        </div>`;

        let tipos_pago=[]

        res.pagos.forEach(prod => {
          tipos_pago.push(prod.tipo)
          tableHTML += `
            <tr data-fecha='${dateToTimestamp(prod.fecha,-1)}' data-tipo='${prod.tipo}'>
                <td class='text-right d-table-cell d-md-none pl-2'>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>NÚMERO</strong></small>
                            <p class="mb-0">${prod.numero}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>FECHA</strong></small>
                            <p class="mb-0">${mostrarfecha(prod.fecha)}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>VALOR</strong></small>
                            <p class="mb-0">${prod.valor!== undefined ? 'Q.'+numFormat(prod.valor) : 'N/A'}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>TIPO</strong></small>
                            <p class="mb-0">${prod.tipo}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>BANCO</strong></small>
                            <p class="mb-0">${prod.banco}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>REFERENCIA</strong></small>
                            <p class="mb-0">${prod.referencia}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong>OBSERVACIONES</strong></small>
                            <p class="mb-0">${prod.observaciones}</p>
                        </div>
                        <div class="d-flex w-100 justify-content-between border-bottom border-light">
                            <small><strong></strong></small>
                            <p class="mb-0"><button type='button' class="btn btn-success btn-sm" onclick="open_link(base_url +'creditoventas/generarPdf/${prod.id}')"><i class="fas fa-file-pdf"></i></button></p>
                        </div>                                                                                                
                </td>
                <td class='text-right d-none d-md-table-cell'>${prod.numero}</td>
                <td class='d-none d-md-table-cell'>${mostrarfecha(prod.fecha)}</td>
                <td class='text-right d-none d-md-table-cell'>${prod.valor!== undefined ? 'Q.'+numFormat(prod.valor) : 'N/A'}</td>
                <td class='d-none d-md-table-cell'>${prod.tipo}</td>
                <td class='d-none d-md-table-cell'>${prod.banco}</td>
                <td class='d-none d-md-table-cell'>${prod.referencia}</td>
                <td class='d-none d-md-table-cell'>${prod.observaciones}</td>
                <td class='text-right d-none d-md-table-cell'><button type='button' class="btn btn-success btn-sm" onclick="open_link(base_url +'creditoventas/generarPdf/${prod.id}')"><i class="fas fa-file-pdf"></i></button></td>
            </tr>
          `;
        });
        
        tableHTML += `</tbody></table>`;
        reporte_tablapagos.innerHTML = tableHTML;       

        tipos_pago = [...new Set(tipos_pago)].sort();
        const selectTiposPagos = document.getElementById('tiposPagos');
        selectTiposPagos.innerHTML = `<option value="">Todos</option>`;
        tipos_pago.forEach(tipo => {
            selectTiposPagos.innerHTML += `<option value="${tipo}">${tipo}</option>`;
        });
      }
  }  
  limpiar_fechas_pagos()
}

function actualizarTablaProductos(productos)
{
    if(productos.length==0)
    {
      reporte_productos.innerHTML=`<div class="alert alert-danger">No existen datos</div>`;
    } else {
      let tableHTML = `<table class='table table-sm table-striped'>
                    <thead class="thead-dark">
                        <tr class=''>
                            <th scope="col" class=''>CODIGO</th>
                            <th scope="col" class='text-right'>LINEA</th>
                            <th scope="col" class='text-right'>DESCRIPCION</th>
                            <th scope="col" class='text-right'>UNIDADES</th>
                            <th scope="col" class='text-right'>VENTA</th>                            
                        </tr>
                    </thead>
                    <tbody>`;

        productos.forEach(prod => {

          tableHTML += `
            <tr data-codigo='${prod.cod_linea.trim()}'>
                <td style='line-height: 1em'>${prod.codart}</td>
                <td style='line-height: 1em'>${prod.cod_linea}</td>
                <td style='line-height: 1em'>${prod.prod_descrip}</td>
                <td style='line-height: 1em' class="text-right">${prod.cantidad !== undefined ? numFormat(prod.cantidad) : 'N/A'}</td>
                <td style='line-height: 1em' class="text-right">Q.${prod.ventas!== undefined ? numFormat(prod.ventas) : 'N/A'}</td>
            </tr>
          `;
        });

      tableHTML += `</tbody></table>`;
      reporte_productos.innerHTML = tableHTML;                    
    }

}

function actualizarTablaCategorias(categorias)
{
    let comprados=[];

    if(categorias.length==0)
    {
      let tableHTML = `<table class='table table-sm table-striped table-hover user-select-none'>
                    <thead class="thead-dark">
                        <tr class=''>
                            <th scope="col" class='d-table-cell d-md-none pl-2'>CATEGORIAS</th>
                            <th scope="col d-none d-md-table-cell" >LINEA</th>
                            <th scope="col d-none d-md-table-cell" >CATEGORIA</th>
                            <th scope="col d-none d-md-table-cell" >UNIDADES</th>
                            <th scope="col d-none d-md-table-cell" >VENTAS</th>
                        </tr>
                    </thead>
                    <tbody>`;
      let nocomprados = [...categoriasGeneral]
      nocomprados.forEach(categoria => {
                tableHTML += `
                  <tr class='text-danger' onclick="selectLinea('${categoria.cod_linea}')" data-codigo='${categoria.cod_linea}' style='cursor:pointer;'>
                      <td class='text-right d-table-cell d-md-none pl-2'>
                          <div class="d-flex w-100 justify-content-between border-bottom border-light">
                              <small><strong>LINEA</strong></small>
                              <p class="mb-0">${categoria.cod_linea}</p>
                          </div>
                          <div class="d-flex w-100 justify-content-between border-bottom border-light">
                              <small><strong>CATEGORIA</strong></small>
                              <p class="mb-0">${categoria.categoria}</p>
                          </div>
                          <div class="d-flex w-100 justify-content-between border-bottom border-light">
                              <small><strong>UNIDADES</strong></small>
                              <p class="mb-0">0</p>
                          </div>
                          <div class="d-flex w-100 justify-content-between border-bottom border-light">
                              <small><strong>VENTAS</strong></small>
                              <p class="mb-0">Q.0.00</p>
                          </div>                                                                                         
                      </td>
                      <td style='line-height: 1em' class='d-none d-md-table-cell'>${categoria.cod_linea}</td>
                      <td style='line-height: 1em' class='d-none d-md-table-cell'>${categoria.categoria}</td>
                      <td style='line-height: 1em' class="text-right d-none d-md-table-cell">0</td>
                      <td style='line-height: 1em' class="text-right d-none d-md-table-cell">Q.0.00</td>
                  </tr>
                `;
      });
            
      tableHTML += `</tbody></table>`;
      reporte_categorias.innerHTML = tableHTML;
    } else {
      let tableHTML = `<table class='table table-sm table-striped table-hover user-select-none'>
                    <thead class="thead-dark">
                        <tr class=''>
                            <th scope="col" class='d-table-cell d-md-none pl-2'>CATEGORIAS</th>
                            <th scope="col" class='d-none d-md-table-cell'>LINEA</th>
                            <th scope="col" class='d-none d-md-table-cell'>CATEGORIA</th>
                            <th scope="col" class='d-none d-md-table-cell'>UNIDADES</th>
                            <th scope="col" class='d-none d-md-table-cell'>VENTAS</th>
                        </tr>
                    </thead>
                    <tbody>`;
      categorias.forEach(categoria => {
        comprados.push(categoria.cod_linea);
        tableHTML += `
          <tr onclick="selectLinea('${categoria.cod_linea}')" data-codigo='${categoria.cod_linea.trim()}' style='cursor:pointer;'>

              <td class='text-right d-table-cell d-md-none pl-2'>
                  <div class="d-flex w-100 justify-content-between border-bottom border-light">
                      <small><strong>LINEA</strong></small>
                      <p class="mb-0">${categoria.cod_linea}</p>
                  </div>
                  <div class="d-flex w-100 justify-content-between border-bottom border-light">
                      <small><strong>CATEGORIA</strong></small>
                      <p class="mb-0">${categoria.categoria}</p>
                  </div>
                  <div class="d-flex w-100 justify-content-between border-bottom border-light">
                      <small><strong>UNIDADES</strong></small>
                      <p class="mb-0">${categoria.cantidad !== undefined ? numFormat(categoria.cantidad) : 'N/A'}</p>
                  </div>
                  <div class="d-flex w-100 justify-content-between border-bottom border-light">
                      <small><strong>VENTAS</strong></small>
                      <p class="mb-0">Q.${categoria.ventas!== undefined ? numFormat(categoria.ventas) : 'N/A'}</p>
                  </div>                                                                                         
              </td>          

              <td style='line-height: 1em' class='d-none d-md-table-cell'>${categoria.cod_linea}</td>
              <td style='line-height: 1em' class='d-none d-md-table-cell'>${categoria.categoria}</td>
              <td style='line-height: 1em' class="text-right d-none d-md-table-cell">${categoria.cantidad !== undefined ? numFormat(categoria.cantidad) : 'N/A'}</td>
              <td style='line-height: 1em' class="text-right d-none d-md-table-cell">Q.${categoria.ventas!== undefined ? numFormat(categoria.ventas) : 'N/A'}</td>
          </tr>
        `;
      });
      nocomprados = categoriasGeneral.filter(categoria => !comprados.includes(categoria.cod_linea));
      
      nocomprados.forEach(categoria => {
          tableHTML += `
            <tr class='text-danger' onclick="selectLinea('${categoria.cod_linea.trim()}')" data-codigo='${categoria.cod_linea}' style='cursor:pointer;'>

                <td class='text-right d-table-cell d-md-none pl-2'>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>LINEA</strong></small>
                        <p class="mb-0">${categoria.cod_linea}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>CATEGORIA</strong></small>
                        <p class="mb-0">${categoria.categoria}</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>UNIDADES</strong></small>
                        <p class="mb-0">0</p>
                    </div>
                    <div class="d-flex w-100 justify-content-between border-bottom border-light">
                        <small><strong>VENTAS</strong></small>
                        <p class="mb-0">Q.0.00</p>
                    </div>                                                                                         
                </td> 

                <td style='line-height: 1em' class='d-none d-md-table-cell'>${categoria.cod_linea}</td>
                <td style='line-height: 1em' class='d-none d-md-table-cell'>${categoria.categoria}</td>
                <td style='line-height: 1em' class="text-right d-none d-md-table-cell">0</td>
                <td style='line-height: 1em' class="text-right d-none d-md-table-cell">Q.0.00</td>
            </tr>
          `;
      });

      tableHTML += `</tbody></table>`;
      reporte_categorias.innerHTML = tableHTML;
    }
   

}


function actualizarTablaCategorias3(categorias)
{
    let comprados=[];

    if(categorias.length==0)
    {
      //reporte_categorias.innerHTML=`<div class="alert alert-danger">No existen datos</div>`;
      let tableHTML = `<table class='table table-sm table-striped'>
                    <thead class="thead-dark">
                        <tr class=''>
                            <th scope="col" >LINEA</th>
                            <th scope="col" >CATEGORIA</th>
                            <th scope="col" >UNIDADES</th>
                            <th scope="col" >VENTAS</th>
                        </tr>
                    </thead>
                    <tbody>`;
      let nocomprados = [...categoriasGeneral]
      nocomprados.forEach(categoria => {
                tableHTML += `
                  <tr class='text-danger'>
                      <td style='line-height: 1em'>${categoria.cod_linea}</td>
                      <td style='line-height: 1em'>${categoria.categoria}</td>
                      <td style='line-height: 1em' class="text-right">0</td>
                      <td style='line-height: 1em' class="text-right">Q.0.00</td>
                  </tr>
                `;
      });
            
      tableHTML += `</tbody></table>`;
      reporte_categorias.innerHTML = tableHTML;  
    } else {
      let tableHTML = `<table class='table table-sm table-striped'>
                    <thead class="thead-dark">
                        <tr class=''>
                            <th scope="col" >LINEA</th>
                            <th scope="col" >CATEGORIA</th>
                            <th scope="col" >UNIDADES</th>
                            <th scope="col" >VENTAS</th>
                        </tr>
                    </thead>
                    <tbody>`;
      categorias.forEach(categoria => {
        comprados.push(categoria.cod_linea);
        tableHTML += `
          <tr>
              <td style='line-height: 1em'>${categoria.cod_linea}</td>
              <td style='line-height: 1em'>${categoria.categoria}</td>
              <td style='line-height: 1em' class="text-right">${categoria.cantidad !== undefined ? numFormat(categoria.cantidad) : 'N/A'}</td>
              <td style='line-height: 1em' class="text-right">Q.${categoria.ventas!== undefined ? numFormat(categoria.ventas) : 'N/A'}</td>
          </tr>
        `;
      });
      nocomprados = categoriasGeneral.filter(categoria => !comprados.includes(categoria.cod_linea));
      
      nocomprados.forEach(categoria => {
          tableHTML += `
            <tr class='text-danger'>
                <td style='line-height: 1em'>${categoria.cod_linea}</td>
                <td style='line-height: 1em'>${categoria.categoria}</td>
                <td style='line-height: 1em' class="text-right">0</td>
                <td style='line-height: 1em' class="text-right">Q.0.00</td>
            </tr>
          `;
      });

      tableHTML += `</tbody></table>`;
      reporte_categorias.innerHTML = tableHTML;

    }

}


// FUNCIONES PAGINA 3 - HISTORIAL DE VISITAS

function actualizarGraficoVisitasMesCliente() {

    if(visitasChartObj) { visitasChartObj.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>
                  </tr>`;
            });
            reportetablevisitas.innerHTML=tablehtml;
            
        }
    }

}



function numFormat(num) {
    /*return new Intl.NumberFormat("gt-GT",{
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(num)*/
    return new Intl.NumberFormat("en-US",{
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(num);
}

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

function diasDesde(fechaString) {
  const fecha = new Date(fechaString);
  const hoy = new Date();
  // Limpiar horas para comparar solo fechas
  fecha.setHours(0,0,0,0);
  hoy.setHours(0,0,0,0);
  const diferenciaMs = hoy - fecha;
  const dias = Math.floor(diferenciaMs / (1000 * 60 * 60 * 24));
  return dias;
}

function mostrarfecha(fechasinformato, hora=false)
{
   // Si la fecha viene en formato YYYY-MM-DD, agregar 'T00:00:00' para interpretarla como local
   let fechaStr = fechasinformato;
   if (typeof fechasinformato === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(fechasinformato)) {
       fechaStr = fechasinformato + 'T00:00:00';
   }
   
   const opcionesFecha =(hora===true)?{ year: 'numeric',month: '2-digit',day: '2-digit',hour: '2-digit',minute: '2-digit',second: '2-digit', hour12: false}:{ year: 'numeric',month: '2-digit',day: '2-digit'};
   const fecha = new Date(fechaStr);
   return fecha.toLocaleDateString('es-GT', opcionesFecha)
}

function dateToTimestamp(fechasinformato,sum=0)
{
   const fecha = new Date(fechasinformato);
   fecha.setDate(fecha.getDate() + sum)
   return fecha.getTime();
}