$(document).ready(function() {

    // Click handler for any link or element that shows the line chart
    $('.showLineChart').on('click', function(e) {
      e.preventDefault();
  
      // Grab userId from data attribute: either a real user ID or "all"
      let userId = $(this).data('userid');
      showLineChart(userId);
    });
  });
  
  // We'll keep a global chart instance so we can destroy it if needed
  let myLineChart = null;
  
  /**
   * Builds a line chart for the given userId (or "all").
   * Then shows the #chartModal (Bootstrap).
   */
  function showLineChart(userId) {
    // Batches in ascending order
    let labels = [];
    let dataPoints = [];
  
    // If userId == "all", we plot the overall totals
    if (userId === 'all') {
      for (let i = 0; i < window.batchesAsc.length; i++) {
        let batch = window.batchesAsc[i].payout_batch;
        let total = window.allTotals[batch] ? window.allTotals[batch] : 0;
        labels.push(batch);
        dataPoints.push(total);
      }
    } else {
      // Otherwise, a specific user's totals
      for (let i = 0; i < window.batchesAsc.length; i++) {
        let batch = window.batchesAsc[i].payout_batch;
        // Check if this user has any total in that batch
        let total = 0;
        if (window.lineTotals[userId] && window.lineTotals[userId][batch]) {
          total = window.lineTotals[userId][batch];
        }
        labels.push(batch);
        dataPoints.push(total);
      }
    }
  
    // If a previous chart exists, destroy it before creating a new one
    if (myLineChart) {
      myLineChart.destroy();
    }
  
    let ctx = document.getElementById('lineChart').getContext('2d');
    myLineChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: (userId === 'all') ? 'Total (All Users)' : 'User ' + userId,
          data: dataPoints,
          borderColor: 'rgba(75,192,192,1)',
          backgroundColor: 'rgba(75,192,192,0.2)',
          fill: true,
          tension: 0.1
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });
  
    // Show the modal (Bootstrap 4/5)
    $('#chartModal').modal('show');
  }
  