/**
 * Attendance Reports
 */

'use strict';

$(document).ready(function() {
  // Get report data from window
  const reportData = window.attendanceReportData || {
    monthlyStats: [],
    totalPresent: 0,
    totalAbsent: 0,
    totalLate: 0
  };

  // Get translated labels
  const labels = window.pageData?.labels || {};
  const presentLabel = labels.present || 'Present';
  const absentLabel = labels.absent || 'Absent';
  const lateLabel = labels.late || 'Late';
  const daysLabel = labels.days || 'days';
  const totalLabel = labels.total || 'Total';

  // Chart Colors
  const chartColors = {
    primary: '#696cff',
    success: '#71dd37',
    warning: '#ffab00',
    danger: '#ff3e1d',
    info: '#03c3ec',
    secondary: '#8592a3'
  };

  // Initialize date range picker
  const dateRangeEl = document.getElementById('dateRange');
  if (dateRangeEl) {
    flatpickr(dateRangeEl, {
      mode: 'range',
      dateFormat: 'Y-m-d',
      maxDate: 'today'
    });
  }

  // Report period change handler
  $('#reportPeriod').on('change', function() {
    const value = $(this).val();
    if (value === 'custom') {
      $('#customDateRange').show();
    } else {
      $('#customDateRange').hide();
    }
  });

  // Initialize Attendance Trend Chart
  const attendanceTrendChartEl = document.querySelector('#attendanceTrendChart');
  if (attendanceTrendChartEl) {
    const categories = reportData.monthlyStats.map(stat => stat.month);
    const presentData = reportData.monthlyStats.map(stat => stat.present);
    const absentData = reportData.monthlyStats.map(stat => stat.absent);
    const lateData = reportData.monthlyStats.map(stat => stat.late);

    const attendanceTrendChartOptions = {
      series: [{
        name: presentLabel,
        data: presentData
      }, {
        name: absentLabel,
        data: absentData
      }, {
        name: lateLabel,
        data: lateData
      }],
      chart: {
        type: 'line',
        height: 350,
        toolbar: {
          show: true,
          tools: {
            download: true,
            selection: false,
            zoom: false,
            zoomin: false,
            zoomout: false,
            pan: false,
            reset: false
          }
        }
      },
      colors: [chartColors.success, chartColors.danger, chartColors.warning],
      dataLabels: {
        enabled: false
      },
      stroke: {
        curve: 'smooth',
        width: 3
      },
      xaxis: {
        categories: categories,
        labels: {
          style: {
            fontSize: '12px'
          }
        }
      },
      yaxis: {
        title: {
          text: daysLabel.charAt(0).toUpperCase() + daysLabel.slice(1)
        },
        min: 0
      },
      tooltip: {
        shared: true,
        intersect: false,
        y: {
          formatter: function (val) {
            return val + ' ' + daysLabel;
          }
        }
      },
      legend: {
        position: 'top',
        horizontalAlign: 'left'
      },
      grid: {
        borderColor: '#f1f1f1',
        xaxis: {
          lines: {
            show: false
          }
        },
        yaxis: {
          lines: {
            show: true
          }
        }
      },
      markers: {
        size: 5,
        colors: ['#fff'],
        strokeColors: [chartColors.success, chartColors.danger, chartColors.warning],
        strokeWidth: 2,
        hover: {
          size: 7
        }
      }
    };

    const attendanceTrendChart = new ApexCharts(attendanceTrendChartEl, attendanceTrendChartOptions);
    attendanceTrendChart.render();
  }

  // Initialize Attendance Distribution Chart
  const attendanceDistributionChartEl = document.querySelector('#attendanceDistributionChart');
  if (attendanceDistributionChartEl) {
    const attendanceDistributionChartOptions = {
      series: [
        reportData.totalPresent,
        reportData.totalAbsent,
        reportData.totalLate
      ],
      chart: {
        type: 'donut',
        height: 280
      },
      labels: [presentLabel, absentLabel, lateLabel],
      colors: [chartColors.success, chartColors.danger, chartColors.warning],
      dataLabels: {
        enabled: true,
        formatter: function (val, opts) {
          return opts.w.config.series[opts.seriesIndex] + ' ' + daysLabel;
        }
      },
      plotOptions: {
        pie: {
          donut: {
            size: '70%',
            labels: {
              show: true,
              name: {
                show: true,
                fontSize: '14px',
                fontWeight: 600,
                offsetY: -5
              },
              value: {
                show: true,
                fontSize: '16px',
                fontWeight: 400,
                color: undefined,
                offsetY: 16,
                formatter: function (val) {
                  return val + ' ' + daysLabel;
                }
              },
              total: {
                show: true,
                showAlways: false,
                label: totalLabel,
                fontSize: '12px',
                fontWeight: 400,
                color: '#8592a3',
                formatter: function (w) {
                  const total = w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                  return total + ' ' + daysLabel;
                }
              }
            }
          }
        }
      },
      legend: {
        show: false
      },
      stroke: {
        width: 3,
        colors: ['#fff']
      },
      responsive: [{
        breakpoint: 480,
        options: {
          chart: {
            height: 250
          }
        }
      }]
    };

    const attendanceDistributionChart = new ApexCharts(attendanceDistributionChartEl, attendanceDistributionChartOptions);
    attendanceDistributionChart.render();
  }

  // Apply Filter button (renamed from Generate Report)
  $('#generateReport').on('click', function() {
    const period = $('#reportPeriod').val();

    // Validate custom date range if selected
    if (period === 'custom') {
      const dateRange = $('#dateRange').val();
      if (!dateRange || !dateRange.includes(' to ')) {
        Swal.fire({
          icon: 'warning',
          title: labels.dateRangeRequired || 'Date Range Required',
          text: labels.selectDateRange || 'Please select a date range for custom period.',
          customClass: {
            confirmButton: 'btn btn-primary'
          },
          buttonsStyling: false
        });
        return;
      }
    }

    // Show loading
    Swal.fire({
      title: labels.applyingFilter || 'Applying Filter',
      text: labels.pleaseWait || 'Please wait while we load your filtered report...',
      allowOutsideClick: false,
      showConfirmButton: false,
      willOpen: () => {
        Swal.showLoading();
      }
    });

    // Build URL with query parameters
    const url = new URL(window.location.href);
    url.searchParams.set('period', period);

    // Add custom date range if selected
    if (period === 'custom') {
      const dateRange = $('#dateRange').val();
      const dates = dateRange.split(' to ');
      url.searchParams.set('start_date', dates[0]);
      url.searchParams.set('end_date', dates[1]);
    }

    // Redirect to filtered URL
    window.location.href = url.toString();
  });

  // Reset Filter button
  $('#resetFilter').on('click', function() {
    // Reset to default values
    $('#reportPeriod').val('current_month').trigger('change');
    $('#dateRange').val('');
    $('#customDateRange').hide();

    // Reload page to show default data
    location.reload();
  });

  // Export functionality removed for self-service reports
  // Export button handler and related functions have been removed

  // Auto-refresh charts on window resize
  let resizeTimer;
  $(window).on('resize', function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
      // Trigger chart resize
      window.dispatchEvent(new Event('resize'));
    }, 250);
  });
});