<% /* Reportes - Asistencias, Tickets y Gastos */ %>
<div class="container-fluid py-3">

  <div class="d-flex align-items-center mb-2">
    <h3 class="mb-0">Reportes</h3>
    <span class="ms-auto small text-muted" id="repStatus">—</span>
  </div>

  <!-- Filtros -->
  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <div class="row g-3 align-items-end">
        <div class="col-12 col-lg-6">
          <label class="form-label mb-1">Asistencias · Rango</label>
          <div class="row g-2">
            <div class="col-6 col-md-4"><input id="asistDesde" type="date" class="form-control"></div>
            <div class="col-6 col-md-4"><input id="asistHasta" type="date" class="form-control"></div>
            <div class="col-12 col-md-4 d-grid d-md-block">
              <button id="btnAsistCargar" class="btn btn-primary me-2">Cargar</button>
              <button id="btnAsistExcel"  class="btn btn-outline-success me-2">Excel</button>
              <button id="btnAsistPDF"    class="btn btn-outline-secondary">PDF</button>
            </div>
          </div>
        </div>

        <div class="col-12 col-lg-6">
          <label class="form-label mb-1">Año (Tickets / Gastos)</label>
          <div class="row g-2">
            <div class="col-6 col-md-4"><input id="anualYear" type="number" min="2000" step="1" class="form-control"></div>
            <div class="col-6 col-md-8 d-grid d-md-block">
              <button id="btnAnualCargar" class="btn btn-primary me-2">Cargar</button>
              <button id="btnAnualExcel"  class="btn btn-outline-success me-2">Excel (Comparativo)</button>
              <button id="btnAnualPDF"    class="btn btn-outline-secondary">PDF (Comparativo)</button>
            </div>
          </div>
        </div>
      </div>

      <div class="small text-muted mt-2">
        Los Excel se generan como CSV. Los PDF se generan con “Imprimir área” del navegador.
      </div>
    </div>
  </div>

  <!-- Asistencias -->
  <div class="card shadow-sm mb-3" id="PRINT_ASIST">
    <div class="card-header d-flex align-items-center">
      <strong>Asistencias</strong>
      <span class="ms-auto small text-muted" id="asistInfo">—</span>
    </div>
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <thead class="table-light">
          <tr>
            <th>Documento</th><th>Nombre</th><th>Apellido</th><th>Fecha</th>
            <th class="text-end">Desde</th><th class="text-end">Hasta</th><th class="text-end">Duración</th>
          </tr>
          </thead>
          <tbody id="tbAsist"><tr><td colspan="7" class="p-3 text-muted">Sin datos</td></tr></tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Tickets -->
  <div class="card shadow-sm mb-3" id="PRINT_TICKETS">
    <div class="card-header d-flex align-items-center">
      <strong>Ventas (Tickets)</strong>
      <span class="ms-auto small text-muted" id="ticketsInfo">—</span>
    </div>
    <div class="card-body">
      <div class="row g-3">
        <div class="col-12 col-lg-6">
          <div class="emp-card p-3 border rounded">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <div class="fw-semibold">Resumen del año</div>
              <div class="small text-muted" id="ticketsYearTitle">—</div>
            </div>
            <div class="row text-center">
              <div class="col-4"><div class="small text-muted">Tickets YTD</div><div class="fs-5 fw-semibold" id="tYtd">—</div></div>
              <div class="col-4"><div class="small text-muted">Promedio</div><div class="fs-5 fw-semibold" id="tAvg">—</div></div>
              <div class="col-4"><div class="small text-muted">Ingresos YTD</div><div class="fs-5 fw-semibold" id="tToDate">—</div></div>
            </div>
          </div>
        </div>
        <div class="col-12 col-lg-6">
          <div class="emp-card p-3 border rounded">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <div class="fw-semibold">Tickets por mes</div>
              <div class="small text-muted">Cantidad</div>
            </div>
            <div id="ticketsChart" style="height:140px;"></div>
          </div>
        </div>

        <div class="col-12">
          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead class="table-light">
              <tr><th>Mes</th><th class="text-end">Tickets</th><th class="text-end">Importe</th><th class="text-end">Ticket promedio</th></tr>
              </thead>
              <tbody id="tbTickets"><tr><td colspan="4" class="p-3 text-muted">Sin datos</td></tr></tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Gastos -->
  <!-- Gastos detallados (mes anterior completo) -->
    <div class="card shadow-sm mb-3" id="PRINT_GASTOS_DET">
    <div class="card-header d-flex align-items-center">
        <strong>Gastos detallados — <span id="gdetTitle">mes anterior</span></strong>
        <span class="ms-auto small text-muted" id="gdetInfo">—</span>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-2">
        <div class="col-12 col-lg-8">
            <div class="d-flex gap-2">
            <span class="badge bg-primary-subtle border text-primary">Total: <span id="gdetTotal">—</span></span>
            <span class="badge bg-secondary-subtle border text-secondary">Compras: <span id="gdetCompras">—</span></span>
            <span class="badge bg-info-subtle border text-info">Renglones: <span id="gdetRows">—</span></span>
            </div>
        </div>
        <div class="col-12 col-lg-4 d-grid d-md-block text-lg-end">
            <button id="btnGdetExcel" class="btn btn-outline-success btn-sm me-2">Excel</button>
            <button id="btnGdetPDF"   class="btn btn-outline-secondary btn-sm">PDF</button>
        </div>
        </div>

        <div class="table-responsive">
        <table class="table table-sm align-middle">
            <thead class="table-light">
            <tr>
                <th>Fecha</th>
                <th>Proveedor</th>
                <th>Tipo</th>
                <th>Ítem</th>
                <th class="text-end">Cantidad</th>
                <th class="text-end">Precio</th>
                <th class="text-end">Subtotal</th>
            </tr>
            </thead>
            <tbody id="tbGdet">
            <tr><td colspan="7" class="p-3 text-muted">Sin datos</td></tr>
            </tbody>
        </table>
        </div>
    </div>
    </div>


  <!-- Comparativo Ventas vs Gastos -->
  <div class="card shadow-sm" id="PRINT_COMP">
    <div class="card-header d-flex align-items-center">
      <strong>Comparativo: Ventas vs Gastos</strong>
      <span class="ms-auto small text-muted" id="compInfo">—</span>
    </div>
    <div class="card-body">
      <div class="row g-3">
        <div class="col-12 col-lg-6">
          <div class="emp-card p-3 border rounded">
            <div class="row text-center">
              <div class="col-4"><div class="small text-muted">Ingresos YTD</div><div class="fs-5 fw-semibold" id="cmpSales">—</div></div>
              <div class="col-4"><div class="small text-muted">Gastos YTD</div><div class="fs-5 fw-semibold" id="cmpCost">—</div></div>
              <div class="col-4"><div class="small text-muted">Resultado</div><div class="fs-5 fw-semibold" id="cmpDiff">—</div></div>
            </div>
          </div>
        </div>
        <div class="col-12 col-lg-6">
          <div class="emp-card p-3 border rounded">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <div class="fw-semibold">Mensual (UYU)</div>
              <div class="small text-muted" id="compYearTitle">—</div>
            </div>
            <div id="compChart" style="height:160px;"></div>
          </div>
        </div>

        <div class="col-12">
          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead class="table-light">
                <tr><th>Mes</th><th class="text-end">Ingresos</th><th class="text-end">Gastos</th><th class="text-end">Resultado</th></tr>
              </thead>
              <tbody id="tbComp"><tr><td colspan="4" class="p-3 text-muted">Sin datos</td></tr></tbody>
            </table>
          </div>
        </div>
      </div>
      <div class="d-flex gap-2 mt-2">
        <button id="btnCompExcel" class="btn btn-outline-success btn-sm">Excel</button>
        <button id="btnCompPDF"   class="btn btn-outline-secondary btn-sm">PDF</button>
      </div>
    </div>
  </div>

</div>

<style>
  .spark rect:hover { filter: brightness(0.9); }
  @media print {
    body * { visibility: hidden !important; }
    #PRINT_ASIST, #PRINT_ASIST *,
    #PRINT_TICKETS, #PRINT_TICKETS *,
    #PRINT_GASTOS, #PRINT_GASTOS *,
    #PRINT_COMP,   #PRINT_COMP * { visibility: visible !important; }
    #PRINT_ASIST, #PRINT_TICKETS, #PRINT_GASTOS, #PRINT_COMP { position:absolute; left:0; top:0; width:100%; }
  }
</style>

<script>
/* ===== Helpers ===== */
const $ = s => document.querySelector(s);
const z2 = n => String(n).padStart(2,'0');
const fmtMoney = v => (v==null? '—' : new Intl.NumberFormat('es-UY',{style:'currency',currency:'UYU'}).format(Number(v)));
const fmtInt = v => Math.round(Number(v||0));
const monthNames = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];

async function jget(url){ const r=await fetch(url); const j=await r.json().catch(()=>null); if(!r.ok) throw new Error(j?.error||`${r.status}`); return j; }
async function jpost(url, body){ const r=await fetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body||{})}); const j=await r.json().catch(()=>null); if(!r.ok) throw new Error(j?.error||`${r.status}`); return j; }

function toCSV(rows, headers){
  const esc = v => v==null? '' : (typeof v==='number'? String(v) : /[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g,'""')}"` : String(v));
  const cols = headers && headers.length? headers : Object.keys(rows?.[0]||{});
  const out = []; if(headers) out.push(cols.join(','));
  for(const r of (rows||[])) out.push(cols.map(c=>esc(r[c])).join(','));
  return out.join('\r\n');
}
function downloadText(name, text){ const blob=new Blob([text],{type:'text/csv;charset=utf-8;'}); const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download=name; a.click(); URL.revokeObjectURL(a.href); }
function printArea(){ window.print(); }

/* === Mini SVGs === */
function barsSVG(series){ // [{label, value}]
  const W=560,H=120,P=10,G=6;
  const n=series.length||1, max=Math.max(1,...series.map(d=>Number(d.value||0)));
  const bw=Math.max(6,Math.floor((W-P*2-G*(n-1))/n)); let x=P, bars='';
  series.forEach(d=>{ const vh=Math.round((Number(d.value||0)/max)*(H-P-26)); const y=H-20-vh;
    bars+=`<g><rect x="${x}" y="${y}" width="${bw}" height="${vh}" rx="3" ry="3" fill="#0d6efd"><title>${d.label} · ${fmtMoney(d.value)}</title></rect><text x="${x+bw/2}" y="${H-6}" text-anchor="middle">${d.label}</text></g>`; x+=bw+G; });
  return `<svg viewBox="0 0 ${W} ${H}" class="spark" preserveAspectRatio="none"><line x1="${P}" y1="${H-20}" x2="${W-P}" y2="${H-20}" stroke="#adb5bd"/></svg>` .replace('</svg>', bars+'</svg>');
}
function barsCompareSVG(a,b){ // a=ventas, b=gastos: arrays [{label,value}]
  const W=560,H=160,P=10,G=8,PAIR=2,INNER=3;
  const n=a.length, max=Math.max(1,...a.map(d=>Number(d.value||0)),...b.map(d=>Number(d.value||0)));
  const bw=Math.max(5,Math.floor((W-P*2-G*(n-1))/(n*PAIR)));
  let x=P, g=''; for(let i=0;i<n;i++){
    const av=Number(a[i].value||0), bv=Number(b[i].value||0);
    const ah=Math.round((av/max)*(H-P-26)), bh=Math.round((bv/max)*(H-P-26));
    const ay=H-20-ah, by=H-20-bh;
    g+=`<g><rect x="${x}" y="${ay}" width="${bw}" height="${ah}" rx="3" ry="3" fill="#198754"><title>${a[i].label} · Ventas ${fmtMoney(av)}</title></rect></g>`;
    x+=bw+INNER;
    g+=`<g><rect x="${x}" y="${by}" width="${bw}" height="${bh}" rx="3" ry="3" fill="#dc3545"><title>${b[i].label} · Gastos ${fmtMoney(bv)}</title></rect><text x="${x-bw/2}" y="${H-6}" text-anchor="middle">${a[i].label}</text></g>`;
    x+=bw+G;
  }
  return `<svg viewBox="0 0 ${W} ${H}" class="spark" preserveAspectRatio="none"><line x1="${P}" y1="${H-20}" x2="${W-P}" y2="${H-20}" stroke="#adb5bd"/></svg>` .replace('</svg>', g+'</svg>');
}

/* ===== Asistencias ===== */
const fmtHM = mins => { const h=Math.floor(mins/60); const m=Math.round(mins%60); return `${z2(h)}:${z2(m)}`; };
let cacheAsist=[];

async function fetchAsistencias(desde,hasta){
  try { return await jpost('/api/rpc/report_asistencia', { desde, hasta }); }
  catch { const url=`/api/table/asistencia_detalle?desde=${encodeURIComponent(desde)}&hasta=${encodeURIComponent(hasta)}&limit=10000`; return await jget(url); }
}
function renderAsistTabla(rows){
  const tb=$('#tbAsist'); if(!rows?.length){ tb.innerHTML='<tr><td colspan="7" class="p-3 text-muted">Sin datos</td></tr>'; return; }
  tb.innerHTML=''; rows.forEach(r=>{ const tr=document.createElement('tr'); tr.innerHTML=`
    <td>${r.documento||'—'}</td><td>${r.nombre||'—'}</td><td>${r.apellido||'—'}</td><td>${r.fecha||'—'}</td>
    <td class="text-end">${r.desde_hora||'—'}</td><td class="text-end">${r.hasta_hora||'—'}</td>
    <td class="text-end">${fmtHM(Number(r.dur_min||0))}</td>`; tb.appendChild(tr); });
}
async function loadAsist(){ const d=$('#asistDesde').value, h=$('#asistHasta').value; $('#repStatus').textContent='Cargando asistencias…';
  cacheAsist=await fetchAsistencias(d,h)||[]; renderAsistTabla(cacheAsist);
  const minsTot=cacheAsist.reduce((s,r)=>s+Number(r.dur_min||0),0); $('#asistInfo').textContent=`${cacheAsist.length} registros · ${fmtHM(minsTot)}`; $('#repStatus').textContent='Listo'; }

/* ===== Tickets (ventas) ===== */
let cacheTickets=null;
async function fetchTickets(year){ return await jpost('/api/rpc/report_tickets', { year }); }
function renderTickets(data){
  const months=data?.months||[]; $('#ticketsYearTitle').textContent=data?.year||'—';
  $('#tYtd').textContent=months.reduce((s,m)=>s+Number(m.cant||0),0);
  $('#tAvg').textContent=fmtMoney(data?.avg||data?.avg_ticket||0);
  $('#tToDate').textContent=fmtMoney(data?.to_date||0);
  $('#ticketsChart').innerHTML=barsSVG(months.map(m=>({label:m.nombre||m.mes,value:Number(m.cant||0)})));
  const tb=$('#tbTickets'); if(!months.length){ tb.innerHTML='<tr><td colspan="4" class="p-3 text-muted">Sin datos</td></tr>'; } else {
    tb.innerHTML=''; months.forEach(m=>{ const tr=document.createElement('tr'); tr.innerHTML=`
      <td>${m.nombre||m.mes}</td><td class="text-end">${m.cant||0}</td>
      <td class="text-end">${fmtMoney(m.importe||0)}</td><td class="text-end">${fmtMoney(m.avg||0)}</td>`; tb.appendChild(tr); });
  }
  $('#ticketsInfo').textContent=`${months.length} meses`;
}

/* ===== Gastos ===== */
let cacheGastos=null; // {year, months:[{mes,nombre,importe}], total, avg}
async function fetchGastos(year){
  // 1) Intentar RPC
  try { return await jpost('/api/rpc/report_gastos', { year }); } catch {}
  // 2) Fallback: traer compras y agrupar en el cliente
  const rows = await jget('/api/table/compras?limit=10000&order_by=fec_compra%20asc').catch(()=>[]);
  const months = Array.from({length:12},(_,i)=>({mes:i+1,nombre:monthNames[i],importe:0}));
  let total=0;
  (rows||[]).forEach(r=>{
    const d=new Date(r.fec_compra||r.fec||r.fecha); if(!d.getFullYear) return;
    if (d.getFullYear() !== Number(year)) return;
    const m=d.getMonth(); const t=Number(r.total||0);
    months[m].importe += t; total += t;
  });
  const avg = months.reduce((s,m)=>s+m.importe,0)/12;
  return { year, months, total, avg };
}
function renderGastos(data){
  const months=data?.months||[]; $('#gastosYearTitle').textContent=data?.year||'—';
  $('#gToDate').textContent=fmtMoney(data?.total||0);
  $('#gAvg').textContent=fmtMoney(data?.avg||0);
  $('#gastosChart').innerHTML=barsSVG(months.map(m=>({label:m.nombre,value:Number(m.importe||0)})));
  const tb=$('#tbGastos'); if(!months.length){ tb.innerHTML='<tr><td colspan="2" class="p-3 text-muted">Sin datos</td></tr>'; } else {
    tb.innerHTML=''; months.forEach(m=>{ const tr=document.createElement('tr'); tr.innerHTML=`
      <td>${m.nombre}</td><td class="text-end">${fmtMoney(m.importe||0)}</td>`; tb.appendChild(tr); });
  }
  $('#gastosInfo').textContent=`${months.length} meses`;
}

/* ===== Comparativo ===== */
function renderComparativo(){
  if(!cacheTickets?.months || !cacheGastos?.months) return;
  const y = cacheTickets.year || cacheGastos.year; $('#compYearTitle').textContent=y;
  const ventas = Array.from({length:12},(_,i)=>Number(cacheTickets.months.find(m=>(m.mes||monthNames.indexOf(m.nombre)+1)===i+1)?.importe||0));
  const gastos = Array.from({length:12},(_,i)=>Number(cacheGastos.months[i]?.importe||0));
  const seriesA = ventas.map((v,i)=>({label:monthNames[i], value:v}));
  const seriesB = gastos.map((v,i)=>({label:monthNames[i], value:v}));
  $('#compChart').innerHTML = barsCompareSVG(seriesA, seriesB);

  const tb=$('#tbComp'); tb.innerHTML='';
  let ySales=0,yCost=0;
  for(let i=0;i<12;i++){
    const s=ventas[i]||0, g=gastos[i]||0, d=s-g; ySales+=s; yCost+=g;
    const tr=document.createElement('tr'); tr.innerHTML=`
      <td>${monthNames[i]}</td>
      <td class="text-end">${fmtMoney(s)}</td>
      <td class="text-end">${fmtMoney(g)}</td>
      <td class="text-end ${d>=0?'text-success':'text-danger'}">${fmtMoney(d)}</td>`;
    tb.appendChild(tr);
  }
  $('#cmpSales').textContent = fmtMoney(ySales);
  $('#cmpCost').textContent  = fmtMoney(yCost);
  $('#cmpDiff').textContent  = fmtMoney(ySales - yCost);
  $('#compInfo').textContent = '12 meses';
}

/* ===== Exportaciones ===== */
function exportAsistCSV(){
  if(!cacheAsist?.length) return;
  const headers=['Documento','Nombre','Apellido','Fecha','Desde','Hasta','Duración(min)'];
  const rows = cacheAsist.map(r=>({Documento:r.documento||'',Nombre:r.nombre||'',Apellido:r.apellido||'',Fecha:r.fecha||'',Desde:r.desde_hora||'',Hasta:r.hasta_hora||'','Duración(min)':Number(r.dur_min||0)}));
  downloadText(`asistencias_${$('#asistDesde').value}_${$('#asistHasta').value}.csv`, toCSV(rows,headers));
}
function exportTicketsCSV(){
  if(!cacheTickets?.months?.length) return;
  const toInt=v=>fmtInt(v);
  const headers=['Año','Mes','Tickets','Importe','Ticket promedio'];
  const rows=cacheTickets.months.map(m=>({'Año':cacheTickets.year,'Mes':m.nombre||m.mes,'Tickets':Number(m.cant||0),'Importe':toInt(m.importe),'Ticket promedio':toInt(m.avg)}));
  downloadText(`tickets_${cacheTickets.year}.csv`, toCSV(rows,headers));
}
function exportGastosCSV(){
  if(!cacheGastos?.months?.length) return;
  const toInt=v=>fmtInt(v);
  const headers=['Año','Mes','Gasto'];
  const rows=cacheGastos.months.map(m=>({'Año':cacheGastos.year,'Mes':m.nombre,'Gasto':toInt(m.importe)}));
  downloadText(`gastos_${cacheGastos.year}.csv`, toCSV(rows,headers));
}
function exportCompCSV(){
  if(!cacheGastos?.months || !cacheTickets?.months) return;
  const headers=['Mes','Ingresos','Gastos','Resultado'];
  const rows=monthNames.map((nm,i)=>{ const s=Number(cacheTickets.months[i]?.importe||0), g=Number(cacheGastos.months[i]?.importe||0); return {Mes:nm,Ingresos:fmtInt(s),Gastos:fmtInt(g),Resultado:fmtInt(s-g)}; });
  downloadText(`comparativo_${cacheTickets.year||cacheGastos.year}.csv`, toCSV(rows,headers));
}

/* ===== Gastos detallados (mes anterior) ===== */
let cacheGastosDet = [];   // filas detalladas del último mes
let cacheGdetMeta  = null; // {desde,hasta}

function rangoMesAnterior() {
  const today = new Date();
  const y = today.getFullYear(), m = today.getMonth(); // m: 0=ene
  const first = new Date(y, m-1, 1, 0,0,0);                   // 1er día mes anterior
  const last  = new Date(y, m,   0, 23,59,59,999);            // último día mes anterior
  return {
    desdeISO: first.toISOString(),
    hastaISO: last.toISOString(),
    titulo:  `${first.toLocaleDateString('es-UY', { month:'long', year:'numeric' })}`
  };
}

async function loadGastosDetallado(){
  const {desdeISO, hastaISO, titulo} = rangoMesAnterior();
  cacheGdetMeta = { desdeISO, hastaISO };

  // 1) Traigo tablas base (se filtra en cliente)
  const [compras, provs, detMats, detProds, mates, prods] = await Promise.all([
    jget('/api/table/compras?limit=10000&order_by=fec_compra%20desc').catch(()=>[]),
    jget('/api/table/proveedores?limit=10000').catch(()=>[]),
    jget('/api/table/deta_comp_materias?limit=100000').catch(()=>[]),
    jget('/api/table/deta_comp_producto?limit=100000').catch(()=>[]),
    jget('/api/table/mate_primas?limit=10000').catch(()=>[]),
    jget('/api/table/productos?limit=10000').catch(()=>[]),
  ]);

  // 2) Filtro compras del mes anterior
  const d0 = new Date(desdeISO), d1 = new Date(hastaISO);
  const comprasMes = (compras||[]).filter(c=>{
    const d = new Date(c.fec_compra || c.fecha || c.fec);
    return d >= d0 && d <= d1;
  });
  const ids = new Set(comprasMes.map(c=>c.id_compra));
  const provById  = Object.fromEntries((provs||[]).map(p=>[p.id_proveedor, p.raz_social||p.rut||`#${p.id_proveedor}`]));
  const matName   = Object.fromEntries((mates||[]).map(x=>[x.id_mat_prima, x.nombre]));
  const prodName  = Object.fromEntries((prods||[]).map(x=>[x.id_producto,  x.nombre]));

  // 3) Armo filas detalladas
  const mapCompra = Object.fromEntries(comprasMes.map(c=>[c.id_compra, c]));
  const filas = [];

  (detMats||[]).forEach(d=>{
    if(!ids.has(d.id_compra)) return;
    const c = mapCompra[d.id_compra]; const fecha = new Date(c.fec_compra||c.fecha||c.fec);
    const prov = provById[c.id_proveedor] || '—';
    const item = matName[d.id_mat_prima] || `#${d.id_mat_prima}`;
    const qty  = Number(d.cantidad||0);
    const pu   = Number(d.pre_unitario||0);
    filas.push({
      fecha, fecha_txt: fecha.toLocaleDateString('es-UY'),
      proveedor: prov, tipo: 'Materia', item,
      cantidad: qty, precio: pu, subtotal: qty*pu
    });
  });

  (detProds||[]).forEach(d=>{
    if(!ids.has(d.id_compra)) return;
    const c = mapCompra[d.id_compra]; const fecha = new Date(c.fec_compra||c.fecha||c.fec);
    const prov = provById[c.id_proveedor] || '—';
    const item = prodName[d.id_producto] || `#${d.id_producto}`;
    const qty  = Number(d.cantidad||0);
    const pu   = Number(d.pre_unitario||0);
    filas.push({
      fecha, fecha_txt: fecha.toLocaleDateString('es-UY'),
      proveedor: prov, tipo: 'Producto', item,
      cantidad: qty, precio: pu, subtotal: qty*pu
    });
  });

  // 4) Render
  filas.sort((a,b)=>b.fecha - a.fecha);
  cacheGastosDet = filas;

  $('#gdetTitle').textContent = titulo.charAt(0).toUpperCase() + titulo.slice(1);
  const tb = $('#tbGdet');
  if(!filas.length){ tb.innerHTML = '<tr><td colspan="7" class="p-3 text-muted">Sin datos</td></tr>'; }
  else{
    tb.innerHTML = '';
    filas.forEach(r=>{
      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td>${r.fecha_txt}</td>
        <td>${r.proveedor}</td>
        <td>${r.tipo}</td>
        <td>${r.item}</td>
        <td class="text-end">${r.cantidad.toLocaleString('es-UY')}</td>
        <td class="text-end">${fmtMoney(r.precio)}</td>
        <td class="text-end">${fmtMoney(r.subtotal)}</td>`;
      tb.appendChild(tr);
    });
  }

  const total = filas.reduce((s,r)=>s + r.subtotal, 0);
  $('#gdetTotal').textContent   = fmtMoney(total);
  $('#gdetCompras').textContent = comprasMes.length.toLocaleString('es-UY');
  $('#gdetRows').textContent    = filas.length.toLocaleString('es-UY');
  $('#gdetInfo').textContent    = `${new Date(d0).toLocaleDateString('es-UY')} - ${new Date(d1).toLocaleDateString('es-UY')}`;
}

function exportGdetCSV(){
  if(!cacheGastosDet?.length) return;
  const headers = ['Fecha','Proveedor','Tipo','Ítem','Cantidad','Precio','Subtotal'];
  const rows = cacheGastosDet.map(r=>({
    'Fecha': r.fecha_txt,
    'Proveedor': r.proveedor,
    'Tipo': r.tipo,
    'Ítem': r.item,
    'Cantidad': r.cantidad,
    'Precio': Math.round(r.precio),      // entero como pediste
    'Subtotal': Math.round(r.subtotal)
  }));
  downloadText(`gastos_detalle_${$('#gdetTitle').textContent.replace(/\s+/g,'_')}.csv`, toCSV(rows, headers));
}
const onPDFGdet = ()=>printArea('PRINT_GASTOS_DET');
const onPDFAsist=()=>printArea('PRINT_ASIST');
const onPDFTicket=()=>printArea('PRINT_TICKETS');
const onPDFGastos=()=>printArea('PRINT_GASTOS');
const onPDFComp=()=>printArea('PRINT_COMP');

/* ===== Eventos ===== */
$('#btnAsistCargar').addEventListener('click', loadAsist);
$('#btnAsistExcel'). addEventListener('click', exportAsistCSV);
$('#btnAsistPDF').   addEventListener('click', onPDFAsist);

$('#btnAnualExcel').addEventListener('click', exportCompCSV);
$('#btnAnualPDF').  addEventListener('click', onPDFComp);

/* ✅ Enlaza los botones de la sección comparativo */
$('#btnCompExcel').addEventListener('click', exportCompCSV);
$('#btnCompPDF').  addEventListener('click', onPDFComp);

/* ✅ Botones de la nueva sección de gastos detallados */
$('#btnGdetExcel').addEventListener('click', exportGdetCSV);
$('#btnGdetPDF').  addEventListener('click', onPDFGdet);


$('#btnAnualCargar').addEventListener('click', async ()=>{
  const y=Number($('#anualYear').value);
  $('#repStatus').textContent='Cargando ventas y gastos…';
  cacheTickets = await fetchTickets(y).catch(()=>null);
  if (cacheTickets) renderTickets(cacheTickets);
  cacheGastos  = await fetchGastos(y).catch(()=>null);
  if (cacheGastos) renderGastos(cacheGastos);
  if (cacheTickets && cacheGastos) renderComparativo();
  $('#repStatus').textContent='Listo';
});
$('#btnAnualExcel').addEventListener('click', exportCompCSV);
$('#btnAnualPDF').  addEventListener('click', onPDFComp);

$('#btnGastosExcel').addEventListener('click', exportGastosCSV);
$('#btnGastosPDF').  addEventListener('click', onPDFGastos);

/* ===== Defaults al cargar ===== */
loadAsist().catch(()=>{});
(async ()=>{
  const y = Number($('#anualYear').value);
  cacheTickets = await fetchTickets(y).catch(()=>null); if(cacheTickets) renderTickets(cacheTickets);
  cacheGastos  = await fetchGastos(y).catch(()=>null);  if(cacheGastos)  renderGastos(cacheGastos);
  if(cacheTickets && cacheGastos) renderComparativo();
  /* ✅ detalle del último mes */
  await loadGastosDetallado().catch(()=>{});
})();

</script>