<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-sales-summary-report">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4 class="mb-0">Sales Summary Report</h4>
      <button id="sal_export" class="btn btn-sm 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">From</label><input type="date" class="form-control form-control-sm" id="sal_from"></div>
        <div class="col-md-2"><label class="form-label">To</label><input type="date" class="form-control form-control-sm" id="sal_to"></div>
        <div class="col-md-2">
          <label class="form-label">Period</label>
          <select id="sal_period" class="form-select form-select-sm">
            <option value="day">Daily</option>
            <option value="month" selected>Monthly</option>
            <option value="year">Yearly</option>
          </select>
        </div>
        <div class="col-md-2"><label class="form-label">Finish</label><select id="sal_finish" class="form-select form-select-sm"><option value="">All</option></select></div>
        <div class="col-md-2"><label class="form-label">Color</label><select id="sal_color" class="form-select form-select-sm"><option value="">All</option></select></div>
        <?php if (has_role(['admin','super_admin'])): ?>
        <div class="col-md-2"><label class="form-label">Branch</label><select id="sal_branch" class="form-select form-select-sm"><option value="">All</option></select></div>
        <?php endif; ?>
        <div class="col-md-2"><button id="sal_run" class="btn btn-sm btn-primary w-100">Run</button></div>
      </div>
    </div></div>

    <div class="table-responsive">
      <table class="table table-sm" id="sal_table">
        <thead>
          <tr>
            <th>Period</th>
            <th class="text-end">Invoices</th>
            <th class="text-end">Qty</th>
            <th class="text-end">Total SQ.FT</th>
            <th class="text-end">Total</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
  </div>
</div>

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

  const today = new Date().toISOString().slice(0,10);
  const monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0,10);
  $('#sal_from').val(monthStart);
  $('#sal_to').val(today);

  function safeFilePart(s){
    return String(s||'')
      .replace(/\s+/g,'_')
      .replace(/[^a-zA-Z0-9_\-\.]/g,'')
      .slice(0, 80);
  }

  function exportTable(tableSel, filenameBase, sheetName){
    if (typeof XLSX === 'undefined') { alert('XLSX library not loaded'); return; }
    const table = document.querySelector(tableSel);
    if (!table) { alert('No table to export'); return; }
    const thead = table.querySelector('thead');
    const tbody = table.querySelector('tbody');
    if (!thead || !tbody) { alert('No data to export'); return; }

    const headerCells = Array.from(thead.querySelectorAll('th'));
    const headers = headerCells.map(th => (th.innerText || '').trim());
    const rows = Array.from(tbody.querySelectorAll('tr'))
      .filter(tr => tr.querySelectorAll('td').length)
      .map(tr => Array.from(tr.querySelectorAll('td')).map(td => (td.innerText || '').trim()));

    if (!rows.length) { alert('No data to export'); return; }

    const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, (sheetName || 'Report').slice(0,31));
    const fname = safeFilePart(filenameBase || 'report') + '.xlsx';
    XLSX.writeFile(wb, fname);
  }

  function fillSelect($sel, items){
    $sel.empty();
    $sel.append('<option value="">All</option>');
    (items||[]).forEach(x=>{
      $sel.append(`<option value="${x.id}">${$('<div>').text(x.name||'').html()}</option>`);
    });
  }

  function loadLookups(){
    $.get('api/finishes.php', { action:'list' }, function(res){ fillSelect($('#sal_finish'), res.data||[]); });
    $.get('api/colors.php', { action:'list' }, function(res){ fillSelect($('#sal_color'), res.data||[]); });
    <?php if (has_role(['admin','super_admin'])): ?>
    $.get('api/branches.php',{ action:'list' }, function(res){
      const $b=$('#sal_branch');
      $b.empty();
      $b.append('<option value="">All</option>');
      (res.data||[]).forEach(b=> $b.append(`<option value="${b.id}">${$('<div>').text(b.name).html()}</option>`));
    });
    <?php endif; ?>
  }

  function run(){
    const p = {
      action: 'sales_summary_ext',
      from: $('#sal_from').val(),
      to: $('#sal_to').val(),
      period: $('#sal_period').val(),
      finish_id: $('#sal_finish').val(),
      color_id: $('#sal_color').val()
    };
    <?php if (has_role(['admin','super_admin'])): ?>
    const bid = $('#sal_branch').val();
    if (bid) p.branch_id = bid;
    <?php endif; ?>

    $.get('api/reports.php', p, function(res){
      const $tb = $('#sal_table tbody');
      $tb.empty();
      const rows = res.data || [];
      if (!rows.length){
        $tb.append('<tr><td colspan="5" class="text-center text-muted">No data</td></tr>');
        return;
      }
      rows.forEach(r => {
        $tb.append(
          `<tr>
            <td>${r.grp||''}</td>
            <td class="text-end">${Number(r.invoices||0).toFixed(0)}</td>
            <td class="text-end">${Number(r.qty||0).toFixed(3)}</td>
            <td class="text-end">${Number(r.total_sq_ft||0).toFixed(3)}</td>
            <td class="text-end">${Number(r.total||0).toFixed(2)}</td>
          </tr>`
        );
      });
    });
  }

  $('#sal_run').on('click', run);
  $('#sal_export').on('click', function(){
    const from=$('#sal_from').val();
    const to=$('#sal_to').val();
    exportTable('#sal_table', `Sales_Summary_${from}_to_${to}`, 'SalesSummary');
  });

  loadLookups();
  run();
})();
</script>

<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
