<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-production-report">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Production Report</h4>
      <button id="btnExportReport" class="btn btn-outline-success"><i class="bi bi-file-earmark-excel"></i> Export XLSX</button>
    </div>

    <div class="card shadow-sm mb-3"><div class="card-body">
      <div class="row g-2 align-items-end">
        <div class="col-md-2">
          <label class="form-label">Period</label>
          <select id="reportPeriod" class="form-select">
            <option value="daily">Daily</option>
            <option value="weekly">Weekly</option>
            <option value="monthly">Monthly</option>
            <option value="yearly">Yearly</option>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">From Date</label>
          <input type="date" id="reportFrom" class="form-control">
        </div>
        <div class="col-md-3">
          <label class="form-label">To Date</label>
          <input type="date" id="reportTo" class="form-control">
        </div>
        <div class="col-md-2">
          <label class="form-label">Color</label>
          <select id="reportColor" class="form-select">
            <option value="">All Colors</option>
          </select>
        </div>
        <div class="col-md-2">
          <button id="btnGenerateReport" class="btn btn-primary w-100"><i class="bi bi-play-fill"></i> Generate Report</button>
        </div>
      </div>
    </div></div>

    <!-- Color-wise Totals -->
    <div class="card shadow-sm mb-3"><div class="card-body">
      <h6 class="mb-3">Color-wise Production Totals</h6>
      <div class="table-responsive">
        <table id="colorTotalsTable" class="table table-sm table-striped align-middle">
          <thead>
            <tr>
              <th>Color</th>
              <th class="text-end">Polish Jobs</th>
              <th class="text-end">Polish Pre SQFT</th>
              <th class="text-end">Polish Final SQFT</th>
              <th class="text-end">Cut Jobs</th>
              <th class="text-end">Cut SQFT</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div></div>

    <!-- Daily Polishing Production -->
    <div class="card shadow-sm mb-3"><div class="card-body">
      <h6 class="mb-3">Daily Polishing Production</h6>
      <div class="table-responsive">
        <table id="polishDailyTable" class="table table-sm table-striped align-middle">
          <thead>
            <tr>
              <th>Date</th>
              <th class="text-end">Jobs</th>
              <th class="text-end">Pre SQFT</th>
              <th class="text-end">Final SQFT</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div></div>

    <!-- Daily Cutting Production -->
    <div class="card shadow-sm mb-3"><div class="card-body">
      <h6 class="mb-3">Daily Cutting Production</h6>
      <div class="table-responsive">
        <table id="cutDailyTable" class="table table-sm table-striped align-middle">
          <thead>
            <tr>
              <th>Date</th>
              <th class="text-end">Jobs</th>
              <th class="text-end">SQFT</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div></div>
  </div>
</div>

<script>
(function(){
  if (!$('.page-production-report').length) return;

  function loadColors(){
    $.get('api/production_report.php', { action:'options' }, function(res){
      const opts = ['<option value="">All Colors</option>'];
      (res.colors||[]).forEach(c=>opts.push(`<option value="${c.id}">${$('<div>').text(c.name).html()}</option>`));
      $('#reportColor').html(opts.join(''));
    });
  }

  function setDateRangeForPeriod(period){
    const today = new Date();
    const now = new Date();
    let from, to;

    switch(period){
      case 'daily':
        from = to = today.toISOString().slice(0,10);
        break;
      case 'weekly':
        const dayOfWeek = today.getDay();
        const diff = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1);
        const monday = new Date(today);
        monday.setDate(diff);
        from = monday.toISOString().slice(0,10);
        to = now.toISOString().slice(0,10);
        break;
      case 'monthly':
        const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
        from = firstDay.toISOString().slice(0,10);
        to = now.toISOString().slice(0,10);
        break;
      case 'yearly':
        const firstDayYear = new Date(today.getFullYear(), 0, 1);
        from = firstDayYear.toISOString().slice(0,10);
        to = now.toISOString().slice(0,10);
        break;
    }

    $('#reportFrom').val(from);
    $('#reportTo').val(to);
  }

  function generateReport(){
    const period = $('#reportPeriod').val()||'daily';
    const from = $('#reportFrom').val()||'';
    const to = $('#reportTo').val()||'';
    const color_id = $('#reportColor').val()||'';
    const params = { action: period };
    if (from) params.from = from;
    if (to) params.to = to;
    if (color_id) params.color_id = color_id;

    $.get('api/production_report.php', params, function(res){
      // Color totals
      const $ct=$('#colorTotalsTable tbody');
      $ct.empty();
      const colorRows=res.color_totals||[];
      if(!colorRows.length){ $ct.append('<tr><td colspan="6" class="text-center text-muted">No data</td></tr>'); }
      colorRows.forEach(r=>{
        const tr=$('<tr>');
        tr.append(`<td>${$('<div>').text(r.color_name||'').html()}</td>`);
        tr.append(`<td class="text-end">${r.polish_job_count||0}</td>`);
        tr.append(`<td class="text-end">${Number(r.polish_pre_sq_ft||0).toFixed(3)}</td>`);
        tr.append(`<td class="text-end">${Number(r.polish_final_sq_ft||0).toFixed(3)}</td>`);
        tr.append(`<td class="text-end">${r.cut_job_count||0}</td>`);
        tr.append(`<td class="text-end">${Number(r.cut_sq_ft||0).toFixed(3)}</td>`);
        $ct.append(tr);
      });

      // Get the correct data array based on period
      const polishKey = `polishing_${period}` || 'polishing_daily';
      const cutKey = `cutting_${period}` || 'cutting_daily';
      const polishRows = res[polishKey] || res.polishing_daily || [];
      const cutRows = res[cutKey] || res.cutting_daily || [];

      // Update table headers based on period
      const polishDateLabel = period === 'daily' ? 'Date' : (period === 'weekly' ? 'Week' : (period === 'monthly' ? 'Month' : 'Year'));
      const cutDateLabel = period === 'daily' ? 'Date' : (period === 'weekly' ? 'Week' : (period === 'monthly' ? 'Month' : 'Year'));

      $('#polishDailyTable thead th:first').text(polishDateLabel);
      $('#cutDailyTable thead th:first').text(cutDateLabel);

      // Polishing data
      const $pd=$('#polishDailyTable tbody');
      $pd.empty();
      if(!polishRows.length){ $pd.append(`<tr><td colspan="4" class="text-center text-muted">No data</td></tr>`); }
      polishRows.forEach(r=>{
        const tr=$('<tr>');
        let dateDisplay = '';
        if (period === 'daily') {
          dateDisplay = r.production_date || '';
        } else if (period === 'weekly') {
          dateDisplay = `${r.week_start} to ${r.week_end}`;
        } else if (period === 'monthly') {
          dateDisplay = r.month_period || '';
        } else if (period === 'yearly') {
          dateDisplay = r.year_period || '';
        }
        tr.append(`<td>${dateDisplay}</td>`);
        tr.append(`<td class="text-end">${r.polish_job_count||0}</td>`);
        tr.append(`<td class="text-end">${Number(r.polish_pre_sq_ft||0).toFixed(3)}</td>`);
        tr.append(`<td class="text-end">${Number(r.polish_final_sq_ft||0).toFixed(3)}</td>`);
        $pd.append(tr);
      });

      // Cutting data
      const $cd=$('#cutDailyTable tbody');
      $cd.empty();
      if(!cutRows.length){ $cd.append(`<tr><td colspan="3" class="text-center text-muted">No data</td></tr>`); }
      cutRows.forEach(r=>{
        const tr=$('<tr>');
        let dateDisplay = '';
        if (period === 'daily') {
          dateDisplay = r.production_date || '';
        } else if (period === 'weekly') {
          dateDisplay = `${r.week_start} to ${r.week_end}`;
        } else if (period === 'monthly') {
          dateDisplay = r.month_period || '';
        } else if (period === 'yearly') {
          dateDisplay = r.year_period || '';
        }
        tr.append(`<td>${dateDisplay}</td>`);
        tr.append(`<td class="text-end">${r.cut_job_count||0}</td>`);
        tr.append(`<td class="text-end">${Number(r.cut_sq_ft||0).toFixed(3)}</td>`);
        $cd.append(tr);
      });
    }).fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error loading report'); });
  }

  function exportReport(){
    if (typeof XLSX === 'undefined') { alert('XLSX library not loaded'); return; }
    
    const period = $('#reportPeriod').val()||'daily';
    const from = $('#reportFrom').val()||'';
    const to = $('#reportTo').val()||'';
    const color_id = $('#reportColor').val()||'';
    const params = { action: period };
    if (from) params.from = from;
    if (to) params.to = to;
    if (color_id) params.color_id = color_id;

    $.get('api/production_report.php', params, function(res){
      const wb = XLSX.utils.book_new();
      const period = $('#reportPeriod').val()||'daily';

      // Color totals sheet
      const colorData = [['Color', 'Polish Jobs', 'Polish Pre SQFT', 'Polish Final SQFT', 'Cut Jobs', 'Cut SQFT']];
      (res.color_totals||[]).forEach(r=>{
        colorData.push([
          r.color_name||'',
          r.polish_job_count||0,
          Number(r.polish_pre_sq_ft||0).toFixed(3),
          Number(r.polish_final_sq_ft||0).toFixed(3),
          r.cut_job_count||0,
          Number(r.cut_sq_ft||0).toFixed(3)
        ]);
      });
      const wsColor = XLSX.utils.aoa_to_sheet(colorData);
      XLSX.utils.book_append_sheet(wb, wsColor, 'Color Totals');

      // Get the correct data array based on period
      const polishKey = `polishing_${period}` || 'polishing_daily';
      const cutKey = `cutting_${period}` || 'cutting_daily';
      const polishRows = res[polishKey] || res.polishing_daily || [];
      const cutRows = res[cutKey] || res.cutting_daily || [];

      // Polishing sheet
      const polishData = [['Period', 'Jobs', 'Pre SQFT', 'Final SQFT']];
      polishRows.forEach(r=>{
        let periodDisplay = '';
        if (period === 'daily') {
          periodDisplay = r.production_date || '';
        } else if (period === 'weekly') {
          periodDisplay = `${r.week_start} to ${r.week_end}`;
        } else if (period === 'monthly') {
          periodDisplay = r.month_period || '';
        } else if (period === 'yearly') {
          periodDisplay = r.year_period || '';
        }
        polishData.push([
          periodDisplay,
          r.polish_job_count||0,
          Number(r.polish_pre_sq_ft||0).toFixed(3),
          Number(r.polish_final_sq_ft||0).toFixed(3)
        ]);
      });
      const wsPolish = XLSX.utils.aoa_to_sheet(polishData);
      XLSX.utils.book_append_sheet(wb, wsPolish, `${period.charAt(0).toUpperCase() + period.slice(1)} Polishing`);

      // Cutting sheet
      const cutData = [['Period', 'Jobs', 'SQFT']];
      cutRows.forEach(r=>{
        let periodDisplay = '';
        if (period === 'daily') {
          periodDisplay = r.production_date || '';
        } else if (period === 'weekly') {
          periodDisplay = `${r.week_start} to ${r.week_end}`;
        } else if (period === 'monthly') {
          periodDisplay = r.month_period || '';
        } else if (period === 'yearly') {
          periodDisplay = r.year_period || '';
        }
        cutData.push([
          periodDisplay,
          r.cut_job_count||0,
          Number(r.cut_sq_ft||0).toFixed(3)
        ]);
      });
      const wsCut = XLSX.utils.aoa_to_sheet(cutData);
      XLSX.utils.book_append_sheet(wb, wsCut, `${period.charAt(0).toUpperCase() + period.slice(1)} Cutting`);

      const today = new Date().toISOString().slice(0,10);
      XLSX.writeFile(wb, 'Production_Report_' + today + '.xlsx');
    }).fail(function(xhr){ alert((xhr.responseJSON && xhr.responseJSON.message) || 'Error exporting report'); });
  }

  // Set default date range based on period
  setDateRangeForPeriod('daily');

  loadColors();
  generateReport();

  $('#btnGenerateReport').on('click', generateReport);
  $('#btnExportReport').on('click', exportReport);
  $('#reportPeriod').on('change', function(){
    setDateRangeForPeriod($(this).val());
    generateReport();
  });
})();
</script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
