<div class="container-fluid py-3">
  <div class="card shadow-sm"><div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2"><div><strong><?=e($report['title'])?></strong><div class="small text-muted">Report data viewer</div></div><form class="d-flex gap-2"><input type="date" class="form-control form-control-sm" name="from" value="<?=e($from)?>"><input type="date" class="form-control form-control-sm" name="to" value="<?=e($to)?>"><button class="btn btn-primary btn-sm">Load</button><button type="button" onclick="window.print()" class="btn btn-outline-secondary btn-sm">Print</button></form></div>
  <div class="card-body"><div id="reportStatus" class="text-muted">Loading report...</div><div id="reportOutput"></div></div></div>
</div>
<script>
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function table(rows){if(!Array.isArray(rows)||!rows.length)return '<div class="text-muted">No records.</div>';const cols=Object.keys(rows[0]);return '<div class="table-responsive"><table class="table table-sm table-striped"><thead><tr>'+cols.map(c=>'<th>'+esc(c.replaceAll('_',' '))+'</th>').join('')+'</tr></thead><tbody>'+rows.map(r=>'<tr>'+cols.map(c=>'<td>'+esc(typeof r[c]==='object'?JSON.stringify(r[c]):r[c])+'</td>').join('')+'</tr>').join('')+'</tbody></table></div>'}
function render(obj){let html='';for(const [k,v] of Object.entries(obj||{})){html+='<h5 class="mt-4 text-capitalize">'+esc(k.replaceAll('_',' '))+'</h5>';if(Array.isArray(v))html+=table(v);else if(v&&typeof v==='object')html+=table([v]);else html+='<p>'+esc(v)+'</p>';}return html;}
fetch('<?=APP_URL?>/sti-reports/data/<?=e($type)?>?from=<?=urlencode($from)?>&to=<?=urlencode($to)?>',{headers:{'Accept':'application/json'}}).then(r=>{if(!r.ok)throw new Error('HTTP '+r.status);return r.json()}).then(j=>{document.getElementById('reportStatus').remove();document.getElementById('reportOutput').innerHTML='<div class="mb-3"><strong>'+esc(j.meta?.shop_name||'')+'</strong><div class="small text-muted">'+esc(j.meta?.from||'')+' to '+esc(j.meta?.to||'')+'</div></div>'+render(j.data)}).catch(e=>document.getElementById('reportStatus').innerHTML='<div class="alert alert-danger">Could not load report: '+esc(e.message)+'</div>');
</script>
