<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-reports">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4 class="mb-0">Reports</h4>
      <button id="rpt_export" class="btn btn-sm btn-outline-success"><i class="bi bi-file-earmark-excel"></i> Export XLSX</button>
    </div>
    <ul class="nav nav-tabs mb-3" id="reportTabs" role="tablist">
      <li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#rpt-sales" type="button" role="tab">Sales Summary</button></li>
      <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#rpt-adv" type="button" role="tab">Advanced Sales</button></li>
      <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#rpt-out" type="button" role="tab">Outstanding</button></li>
      <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#rpt-quality" type="button" role="tab">Sales by Color</button></li>
      <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#rpt-type" type="button" role="tab">Sales by Type</button></li>
      <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#rpt-profit" type="button" role="tab">Profit Summary</button></li>
    </ul>
    <div class="tab-content">
      <!-- Sales Summary -->
      <div class="tab-pane fade show active" id="rpt-sales" role="tabpanel">
        <div class="d-flex flex-wrap gap-2 align-items-end mb-3">
          <div><label class="form-label">From</label><input type="date" class="form-control form-control-sm" id="ss_from"></div>
          <div><label class="form-label">To</label><input type="date" class="form-control form-control-sm" id="ss_to"></div>
          <div>
            <label class="form-label">Period</label>
            <select id="ss_period" class="form-select form-select-sm">
              <option value="day">Daily</option>
              <option value="week">Weekly</option>
              <option value="month" selected>Monthly</option>
            </select>
          </div>
          <button id="ss_run" class="btn btn-sm btn-primary">Run</button>
        </div>
        <div class="table-responsive">
          <table class="table table-sm" id="ss_table"><thead><tr><th>Period</th><th class="text-end">Invoices</th><th class="text-end">Total (LKR)</th></tr></thead><tbody></tbody></table>
        </div>
      </div>

      <!-- Advanced Sales -->
      <div class="tab-pane fade" id="rpt-adv" role="tabpanel">
        <div class="d-flex flex-wrap gap-2 align-items-end mb-3">
          <div><label class="form-label">From</label><input type="date" class="form-control form-control-sm" id="ad_from"></div>
          <div><label class="form-label">To</label><input type="date" class="form-control form-control-sm" id="ad_to"></div>
          <div><label class="form-label">Type</label><select id="ad_type" class="form-select form-select-sm"><option value="">All</option></select></div>
          <div><label class="form-label">Finish</label><select id="ad_finish" class="form-select form-select-sm"><option value="">All</option></select></div>
          <div><label class="form-label">Color</label><select id="ad_color" class="form-select form-select-sm"><option value="">All</option></select></div>
          <div><label class="form-label">Length From</label><input type="number" step="0.001" class="form-control form-control-sm" id="ad_len_from" placeholder="mm"></div>
          <div><label class="form-label">To</label><input type="number" step="0.001" class="form-control form-control-sm" id="ad_len_to" placeholder="mm"></div>
          <div><label class="form-label">Width From</label><input type="number" step="0.001" class="form-control form-control-sm" id="ad_wid_from" placeholder="mm"></div>
          <div><label class="form-label">To</label><input type="number" step="0.001" class="form-control form-control-sm" id="ad_wid_to" placeholder="mm"></div>
          <?php if (has_role(['admin','super_admin'])): ?>
          <div><label class="form-label">Branch</label><select id="ad_branch" class="form-select form-select-sm"><option value="">All</option></select></div>
          <?php endif; ?>
          <button id="ad_run" class="btn btn-sm btn-primary">Run</button>
          <button id="ad_print" class="btn btn-sm btn-outline-secondary">Print</button>
        </div>
        <div class="table-responsive" id="ad_wrap">
          <table class="table table-sm" id="ad_table"><thead><tr><th>Date</th><th>Invoice</th><th>Customer</th><th>Description</th><th>Finish</th><th>Color</th><th class="text-end">Len</th><th class="text-end">Wid</th><th class="text-end">Qty</th><th class="text-end">Rate</th><th class="text-end">Line (LKR)</th></tr></thead><tbody></tbody></table>
        </div>
      </div>

      <!-- Outstanding -->
      <div class="tab-pane fade" id="rpt-out" role="tabpanel">
        <div class="d-flex flex-wrap gap-2 align-items-end mb-3">
          <div><label class="form-label">From</label><input type="date" class="form-control form-control-sm" id="ou_from"></div>
          <div><label class="form-label">To</label><input type="date" class="form-control form-control-sm" id="ou_to"></div>
          <?php if (has_role(['admin','super_admin'])): ?>
          <div><label class="form-label">Branch</label><select id="ou_branch" class="form-select form-select-sm"><option value="">All</option></select></div>
          <?php endif; ?>
          <div class="form-check ms-2"><input class="form-check-input" type="checkbox" id="ou_nextweek"><label class="form-check-label" for="ou_nextweek">Due next 7 days</label></div>
          <button id="ou_run" class="btn btn-sm btn-primary">Run</button>
          <button id="ou_print" class="btn btn-sm btn-outline-secondary">Print</button>
        </div>
        <div class="table-responsive" id="ou_wrap">
          <table class="table table-sm" id="ou_table"><thead><tr><th>Due</th><th>Invoice</th><th>Date</th><th>Customer</th><th>Term</th><th class="text-end">Total</th><th class="text-end">Paid</th><th class="text-end">Balance</th></tr></thead><tbody></tbody></table>
        </div>
      </div>

      <!-- Sales by Color -->
      <div class="tab-pane fade" id="rpt-quality" role="tabpanel">
        <div class="d-flex flex-wrap gap-2 align-items-end mb-3">
          <div><label class="form-label">From</label><input type="date" class="form-control form-control-sm" id="sq_from"></div>
          <div><label class="form-label">To</label><input type="date" class="form-control form-control-sm" id="sq_to"></div>
          <button id="sq_run" class="btn btn-sm btn-primary">Run</button>
        </div>
        <div class="table-responsive">
          <table class="table table-sm" id="sq_table"><thead><tr><th>Color</th><th class="text-end">Total (LKR)</th></tr></thead><tbody></tbody></table>
        </div>
      </div>

      <!-- Sales by Type -->
      <div class="tab-pane fade" id="rpt-type" role="tabpanel">
        <div class="d-flex flex-wrap gap-2 align-items-end mb-3">
          <div><label class="form-label">From</label><input type="date" class="form-control form-control-sm" id="st_from"></div>
          <div><label class="form-label">To</label><input type="date" class="form-control form-control-sm" id="st_to"></div>
          <div><label class="form-label">Type</label><select id="st_type" class="form-select form-select-sm"><option value="">All</option></select></div>
          <?php if (has_role(['admin','super_admin'])): ?>
          <div><label class="form-label">Branch</label><select id="st_branch" class="form-select form-select-sm"><option value="">All</option></select></div>
          <?php endif; ?>
          <button id="st_run" class="btn btn-sm btn-primary">Run</button>
        </div>
        <div class="table-responsive">
          <table class="table table-sm" id="st_table"><thead><tr><th>Type</th><th class="text-end">Total (LKR)</th></tr></thead><tbody></tbody></table>
        </div>
      </div>

      <!-- Profit Summary -->
      <div class="tab-pane fade" id="rpt-profit" role="tabpanel">
        <div class="d-flex flex-wrap gap-2 align-items-end mb-3">
          <div><label class="form-label">From</label><input type="date" class="form-control form-control-sm" id="pf_from"></div>
          <div><label class="form-label">To</label><input type="date" class="form-control form-control-sm" id="pf_to"></div>
          <button id="pf_run" class="btn btn-sm btn-primary">Run</button>
        </div>
        <div class="table-responsive">
          <table class="table table-sm" id="pf_table"><thead><tr><th>Invoice No</th><th class="text-end">Sold (LKR)</th><th class="text-end">Raw Value (LKR)</th><th class="text-end">Profit (LKR)</th></tr></thead><tbody></tbody><tfoot><tr><th>Totals</th><th class="text-end" id="pf_sold">0</th><th class="text-end" id="pf_raw">0</th><th class="text-end" id="pf_profit">0</th></tr></tfoot></table>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  if (!$('.page-reports').length) return;
  const fmt = n => Number(n||0).toLocaleString('en-LK',{style:'currency',currency:'LKR'});
  const today = new Date().toISOString().slice(0,10);
  const monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0,10);
  $('#ss_from').val(monthStart); $('#ss_to').val(today);
  $('#ad_from').val(monthStart); $('#ad_to').val(today);
  $('#ou_from').val(monthStart); $('#ou_to').val(today);
  $('#sq_from').val(monthStart); $('#sq_to').val(today);
  $('#st_from').val(monthStart); $('#st_to').val(today);
  $('#pf_from').val(monthStart); $('#pf_to').val(today);

  function runSales(){
    const from=$('#ss_from').val(), to=$('#ss_to').val(), period=$('#ss_period').val();
    $.get('api/reports.php', { action:'sales_summary', from, to, period }, function(res){
      const $tb=$('#ss_table tbody'); $tb.empty();
      const rows=res.data||[]; if(!rows.length){ $tb.append('<tr><td colspan="3" class="text-center text-muted">No data</td></tr>'); return; }
      rows.forEach(r=>{ $tb.append(`<tr><td>${r.grp}</td><td class="text-end">${r.invoices}</td><td class="text-end">${fmt(r.total)}</td></tr>`); });
    });
  }

  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 activeReport(){
    const pane = document.querySelector('.tab-pane.active');
    const id = pane ? pane.id : '';
    switch (id) {
      case 'rpt-sales':
        return { table:'#ss_table', name:'Sales_Summary', sheet:'SalesSummary', from:$('#ss_from').val(), to:$('#ss_to').val() };
      case 'rpt-adv':
        return { table:'#ad_table', name:'Advanced_Sales', sheet:'AdvancedSales', from:$('#ad_from').val(), to:$('#ad_to').val() };
      case 'rpt-out':
        return { table:'#ou_table', name:'Outstanding', sheet:'Outstanding', from:$('#ou_from').val(), to:$('#ou_to').val() };
      case 'rpt-quality':
        return { table:'#sq_table', name:'Sales_By_Color', sheet:'ByColor', from:$('#sq_from').val(), to:$('#sq_to').val() };
      case 'rpt-type':
        return { table:'#st_table', name:'Sales_By_Type', sheet:'ByType', from:$('#st_from').val(), to:$('#st_to').val() };
      case 'rpt-profit':
        return { table:'#pf_table', name:'Profit_Summary', sheet:'Profit', from:$('#pf_from').val(), to:$('#pf_to').val() };
      default:
        return null;
    }
  }

  function fillSelect($sel, items, valueKey='id', textKey='name'){
    $sel.empty(); $sel.append('<option value="">All</option>');
    (items||[]).forEach(x=>{ $sel.append(`<option value="${$('<div>').text(x[valueKey]??'').html()}">${$('<div>').text(x[textKey]||'').html()}</option>`); });
  }
  function loadLookups(){
    $.get('api/finishes.php',{ action:'list' }, function(res){ fillSelect($('#ad_finish'), res.data||[], 'id', 'name'); });
    $.get('api/colors.php',{ action:'list' }, function(res){ fillSelect($('#ad_color'), res.data||[], 'id', 'name'); });
    $.get('api/types.php',{ action:'list' }, function(res){ fillSelect($('#ad_type'), res.data||[], 'id', 'name'); });
    $.get('api/types.php',{ action:'list' }, function(res){ fillSelect($('#st_type'), res.data||[], 'id', 'name'); });
    <?php if (has_role(['admin','super_admin'])): ?>
    $.get('api/branches.php',{ action:'list' }, function(res){ const $b=$('#ad_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>`)); $('#ou_branch').html($b.html()); $('#st_branch').html($b.html()); });
    <?php endif; ?>
  }

  function runAdvanced(){
    const p={ action:'sales_detail', from:$('#ad_from').val(), to:$('#ad_to').val(), type_id:$('#ad_type').val(), finish_id:$('#ad_finish').val(), color_id:$('#ad_color').val(), len_from:$('#ad_len_from').val(), len_to:$('#ad_len_to').val(), wid_from:$('#ad_wid_from').val(), wid_to:$('#ad_wid_to').val() };
    <?php if (has_role(['admin','super_admin'])): ?>
    const b=$('#ad_branch').val(); if (b) p.branch_id=b;
    <?php endif; ?>
    $.get('api/reports.php', p, function(res){
      const $tb=$('#ad_table tbody'); $tb.empty(); const rows=res.data||[];
      if(!rows.length){ $tb.append('<tr><td colspan="11" class="text-center text-muted">No data</td></tr>'); return; }
      rows.forEach(r=>{
        $tb.append(`<tr><td>${r.invoice_date||''}</td><td>${r.invoice_no||''}</td><td>${$('<div>').text(r.customer_name||'').html()}</td><td>${$('<div>').text(r.description||'').html()}</td><td>${$('<div>').text(r.finish_name||'').html()}</td><td>${$('<div>').text(r.color_name||'').html()}</td><td class="text-end">${r.length??''}</td><td class="text-end">${r.width??''}</td><td class="text-end">${r.qty??''}</td><td class="text-end">${Number(r.unit_price||0).toFixed(2)}</td><td class="text-end">${Number(r.line_total||0).toFixed(2)}</td></tr>`);
      });
    });
  }

  function runOutstanding(){
    const p={ action:'outstanding', from:$('#ou_from').val(), to:$('#ou_to').val(), next_week: ($('#ou_nextweek').is(':checked')?1:0) };
    <?php if (has_role(['admin','super_admin'])): ?>
    const b=$('#ou_branch').val(); if (b) p.branch_id=b;
    <?php endif; ?>
    $.get('api/reports.php', p, function(res){
      const $tb=$('#ou_table tbody'); $tb.empty(); const rows=res.data||[];
      if(!rows.length){ $tb.append('<tr><td colspan="8" class="text-center text-muted">No data</td></tr>'); return; }
      rows.forEach(r=>{
        $tb.append(`<tr><td>${r.due_date||''}</td><td>${r.invoice_no||''}</td><td>${r.invoice_date||''}</td><td>${$('<div>').text(r.customer_name||'').html()}</td><td>${$('<div>').text(r.payment_term||'').html()}</td><td class="text-end">${Number(r.grand_total||0).toFixed(2)}</td><td class="text-end">${Number(r.total_paid||0).toFixed(2)}</td><td class="text-end">${Number(r.balance||0).toFixed(2)}</td></tr>`);
      });
    });
  }

  function printTable(containerSel){
    const html = document.querySelector(containerSel).outerHTML;
    const w = window.open('', '_blank');
    w.document.write('<html><head><title>Print</title><style>@page{size:A4;margin:12mm;}body{font-family:Arial,sans-serif;} table{width:100%;border-collapse:collapse;} th,td{padding:6px;border-bottom:1px solid #eee;} th{background:#f8f9fa;text-align:left;}</style></head><body>'+html+'<script>window.print();<\/script></body></html>');
    w.document.close();
  }
  function runColor(){
    const from=$('#sq_from').val(), to=$('#sq_to').val();
    $.get('api/reports.php', { action:'sales_by_color', from, to }, function(res){
      const $tb=$('#sq_table tbody'); $tb.empty(); const rows=res.data||[];
      if(!rows.length){ $tb.append('<tr><td colspan="2" class="text-center text-muted">No data</td></tr>'); return; }
      rows.forEach(r=>{ $tb.append(`<tr><td>${$('<div>').text(r.color_name||'Unknown').html()}</td><td class="text-end">${fmt(r.total)}</td></tr>`); });
    });
  }
  function runSalesByType(){
    const p={ action:'sales_by_type', from:$('#st_from').val(), to:$('#st_to').val(), type_id: $('#st_type').val() };
    <?php if (has_role(['admin','super_admin'])): ?>
    const b=$('#st_branch').val(); if (b) p.branch_id=b;
    <?php endif; ?>
    $.get('api/reports.php', p, function(res){
      const $tb=$('#st_table tbody'); $tb.empty(); const rows=res.data||[];
      if(!rows.length){ $tb.append('<tr><td colspan="2" class="text-center text-muted">No data</td></tr>'); return; }
      rows.forEach(r=>{ $tb.append(`<tr><td>${$('<div>').text(r.type_name||'Unknown').html()}</td><td class="text-end">${fmt(r.total)}</td></tr>`); });
    });
  }
  function runProfit(){
    const from=$('#pf_from').val(), to=$('#pf_to').val();
    $.get('api/reports.php', { action:'profit_summary', from, to }, function(res){
      const $tb=$('#pf_table tbody'); $tb.empty(); const rows=res.data||[]; const totals=res.totals||{};
      if(!rows.length){ $tb.append('<tr><td colspan="4" class="text-center text-muted">No data</td></tr>'); }
      rows.forEach(r=>{ $tb.append(`<tr><td>${$('<div>').text(r.invoice_no||'').html()}</td><td class="text-end">${fmt(r.sold_total)}</td><td class="text-end">${fmt(r.raw_value)}</td><td class="text-end">${fmt(r.profit)}</td></tr>`); });
      $('#pf_sold').text(fmt(totals.sold_total||0)); $('#pf_raw').text(fmt(totals.raw_value||0)); $('#pf_profit').text(fmt(totals.profit||0));
    });
  }

  $('#ss_run').on('click', runSales);
  $('#sq_run').on('click', runColor);
  $('#st_run').on('click', runSalesByType);
  $('#pf_run').on('click', runProfit);
  $('#ad_run').on('click', runAdvanced);
  $('#ou_run').on('click', runOutstanding);
  $('#ad_print').on('click', function(){ printTable('#ad_wrap'); });
  $('#ou_print').on('click', function(){ printTable('#ou_wrap'); });

  $('#rpt_export').on('click', function(){
    const r = activeReport();
    if (!r) { alert('Select a report tab first'); return; }
    const base = r.name + (r.from && r.to ? ('_' + r.from + '_to_' + r.to) : '');
    exportTable(r.table, base, r.sheet);
  });

  loadLookups();
  runSales(); runAdvanced(); runOutstanding(); runColor(); runSalesByType(); runProfit();
})();
</script>

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