<?php /** @var string $title */ ?>
<main class="container">
  <header class="page-header">
    <h1><?= htmlspecialchars($title ?? 'Títulos a Vencer') ?></h1>
    <p class="muted">Acompanhe contas a receber e a pagar próximas do vencimento.</p>
  </header>

  <section class="card" style="margin-bottom: .75rem;">
    <div class="form-grid" style="display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .5rem; align-items: end;">
      <div class="form-group">
        <label for="horizonte">Horizonte</label>
        <select id="horizonte">
          <option value="7">Próximos 7 dias</option>
          <option value="15">Próximos 15 dias</option>
          <option value="30">Próximos 30 dias</option>
        </select>
      </div>
      <div class="form-group">
        <label for="incluirVencidos">Incluir vencidos</label>
        <select id="incluirVencidos">
          <option value="nao">Não</option>
          <option value="sim">Sim</option>
        </select>
      </div>
      <div class="form-group">
        <label for="tipoListagem">Tipo</label>
        <select id="tipoListagem">
          <option value="ambos">Receber e Pagar</option>
          <option value="receber">Somente Receber</option>
          <option value="pagar">Somente Pagar</option>
        </select>
      </div>
      <div class="form-group" style="display: flex; gap: .5rem;">
        <button id="btnAplicar" class="btn">Aplicar</button>
        <button id="btnLimpar" class="btn btn-secondary">Limpar filtros</button>
      </div>
    </div>
    <div id="periodoInfo" class="muted" style="margin-top: .25rem;">Período: <span id="periodoSpan">-</span></div>
  </section>

  <section class="card" style="margin-bottom: .75rem;">
    <h2>Resumo</h2>
    <div id="resumoGrid" class="grid" style="grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .5rem;">
      <div class="chip" id="chipReceber">A Receber: carregando…</div>
      <div class="chip" id="chipPagar">A Pagar: carregando…</div>
      <div class="chip" id="chipHoje">Vencem hoje: carregando…</div>
      <div class="chip" id="chipVencidos">Vencidos: carregando…</div>
    </div>
  </section>

  <section class="card" id="secReceber" style="margin-bottom: .75rem;">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:.5rem;">
      <h2 style="margin:0;">Contas a Receber</h2>
      <div style="display:flex;gap:.5rem;">
        <a id="exportReceberCsv" class="btn btn-secondary" href="#" download>Exportar CSV</a>
        <button id="exportReceberXls" class="btn btn-secondary" type="button">Exportar Excel</button>
      </div>
    </div>
    <div class="table-responsive">
      <table id="tblReceber" class="table">
        <thead>
          <tr>
            <th>Vencimento</th>
            <th>Cliente</th>
            <th>Documento</th>
            <th>Descrição</th>
            <th style="text-align:right;">Valor</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <tr><td colspan="6" class="muted">Carregando…</td></tr>
        </tbody>
      </table>
    </div>
  </section>

  <section class="card" id="secPagar">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:.5rem;">
      <h2 style="margin:0;">Contas a Pagar</h2>
      <div style="display:flex;gap:.5rem;">
        <a id="exportPagarCsv" class="btn btn-secondary" href="#" download>Exportar CSV</a>
        <button id="exportPagarXls" class="btn btn-secondary" type="button">Exportar Excel</button>
      </div>
    </div>
    <div class="table-responsive">
      <table id="tblPagar" class="table">
        <thead>
          <tr>
            <th>Vencimento</th>
            <th>Fornecedor</th>
            <th>Documento</th>
            <th>Descrição</th>
            <th style="text-align:right;">Valor</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <tr><td colspan="6" class="muted">Carregando…</td></tr>
        </tbody>
      </table>
    </div>
  </section>
</main>

<script>
// Helpers
async function apiRequest(url, options){ const base='/api'; const opts=options||{}; const headers=opts.headers||{}; if(!(opts.body instanceof FormData)) headers['Content-Type']=headers['Content-Type']||'application/json'; return fetch(base+url,{...opts, headers, credentials:'include'}); }
function fmtBRL(v){ try { return (new Intl.NumberFormat('pt-BR',{style:'currency',currency:'BRL'})).format(Number(v||0)); } catch(e){ return 'R$ '+Number(v||0).toFixed(2); } }
function pad(n){ return (n<10?'0':'')+n; }
function toISO(d){ return d.getFullYear()+'-'+pad(d.getMonth()+1)+'-'+pad(d.getDate()); }
function parseDate(s){ const t = Date.parse(s); return isNaN(t)?null:new Date(t); }
function fmtDateBR(s){ const d=parseDate(s); if(!d) return s||'-'; return pad(d.getDate())+'/'+pad(d.getMonth()+1)+'/'+d.getFullYear(); }
function daysUntil(dateStr){ const d=parseDate(dateStr); if(!d) return null; const today=new Date(); const start=new Date(today.getFullYear(),today.getMonth(),today.getDate()); const due=new Date(d.getFullYear(),d.getMonth(),d.getDate()); return Math.floor((due - start)/(1000*60*60*24)); }

// Estado
const stateKey = 'titulosAVencerState';
let state = { horizonte: 7, incluirVencidos: false, tipo: 'ambos' };
try { const saved = JSON.parse(localStorage.getItem(stateKey)||'{}'); state = { ...state, ...saved }; } catch(e){}

// Inicializa controles
document.getElementById('horizonte').value = String(state.horizonte);
document.getElementById('incluirVencidos').value = state.incluirVencidos? 'sim' : 'nao';
document.getElementById('tipoListagem').value = state.tipo;

document.getElementById('btnAplicar').addEventListener('click', () => { applyFilters(); });
document.getElementById('btnLimpar').addEventListener('click', () => { resetFilters(); });
document.getElementById('exportReceberXls').addEventListener('click', () => { exportTableToExcel('tblReceber', 'contas_a_receber.xlsx'); });
document.getElementById('exportPagarXls').addEventListener('click', () => { exportTableToExcel('tblPagar', 'contas_a_pagar.xlsx'); });

function resetFilters(){ state = { horizonte: 7, incluirVencidos: false, tipo: 'ambos' }; persistState(); applyFilters(true); }
function persistState(){ localStorage.setItem(stateKey, JSON.stringify(state)); }

function getPeriod(){ const today = new Date(); const end = new Date(today); end.setDate(end.getDate() + Number(state.horizonte)); return { start: toISO(today), end: toISO(end) }; }

function updatePeriodInfo(){ const p = getPeriod(); const span = document.getElementById('periodoSpan'); span.textContent = p.start+' a '+p.end; }

async function loadResumo(){ const p = getPeriod(); try {
  const [recResp, pagResp] = await Promise.all([
    apiRequest(`/financeiro/relatorios/receber/resumo?start=${encodeURIComponent(p.start)}&end=${encodeURIComponent(p.end)}`),
    apiRequest(`/financeiro/relatorios/pagar/resumo?start=${encodeURIComponent(p.start)}&end=${encodeURIComponent(p.end)}`)
  ]);
  const rec = await recResp.json(); const pag = await pagResp.json();
  const rTot = (rec.totais && rec.totais.total_geral) ? Number(rec.totais.total_geral) : 0;
  const pTot = (pag.totais && pag.totais.total_geral) ? Number(pag.totais.total_geral) : 0;
  document.getElementById('chipReceber').textContent = `A Receber (${state.horizonte}d): ${fmtBRL(rTot)}`;
  document.getElementById('chipPagar').textContent   = `A Pagar (${state.horizonte}d): ${fmtBRL(pTot)}`;
  const dueToday = ((rec.counts&&rec.counts.due_today_count)||0) + ((pag.counts&&pag.counts.due_today_count)||0);
  document.getElementById('chipHoje').textContent    = `Vencem hoje: ${dueToday}`;
  const overdue = ((rec.counts&&rec.counts.overdue_count)||0) + ((pag.counts&&pag.counts.overdue_count)||0);
  document.getElementById('chipVencidos').textContent = `Vencidos: ${overdue}`;
} catch(e){ console.error(e); }
}

function situationBadge(status, dateStr){ const todayISO = toISO(new Date()); const d = parseDate(dateStr); const today = new Date(); const daysDiff = d? Math.floor((d - today) / (1000*60*60*24)) : null; let label = status||'-'; let bg=''; let color='#000';
  if(status==='vencido'){ label='Vencido'; bg='rgba(255,72,66,.15)'; color='rgb(180,38,33)'; }
  else if(status==='pendente'){
    if(dateStr===todayISO){ label='Hoje'; bg='rgba(254,197,49,.18)'; color='rgb(152,100,9)'; }
    else if(daysDiff!==null && daysDiff<=3){ label='Próximo'; bg='rgba(255,159,64,.18)'; color='rgb(180,88,8)'; }
    else { label='Pendente'; bg='rgba(63,81,181,.14)'; color='rgb(63,81,181)'; }
  } else if(status==='recebido' || status==='pago'){ label = status==='recebido' ? 'Recebido' : 'Pago'; bg='rgba(46,204,113,.18)'; color='rgb(30,160,80)'; }
  return `<span class="badge" style="background:${bg}; color:${color};">${label}</span>`;
}

function rowStyle(status, dateStr){ if(status==='vencido'){ return 'background: rgba(255,72,66,.08);'; }
  const todayISO = toISO(new Date()); if(status==='pendente' && dateStr===todayISO){ return 'background: rgba(254,197,49,.08);'; }
  const d = parseDate(dateStr); const today = new Date(); const daysDiff = d? Math.floor((d - today) / (1000*60*60*24)) : null;
  if(status==='pendente' && daysDiff!==null && daysDiff<=3){ return 'background: rgba(255,159,64,.08);'; }
  return '';
}

function buildReceberExportLink(){ const p=getPeriod(); const base = `/api/financeiro/contas-receber/export.csv`; const params = new URLSearchParams(); params.set('status','pendente'); params.set('start',p.start); params.set('end',p.end); document.getElementById('exportReceberCsv').href = base + '?' + params.toString(); }
function buildPagarExportLink(){ const p=getPeriod(); const base = `/api/financeiro/contas-pagar/export.csv`; const params = new URLSearchParams(); params.set('status','pendente'); params.set('start',p.start); params.set('end',p.end); document.getElementById('exportPagarCsv').href = base + '?' + params.toString(); }

async function loadReceber(){ const p=getPeriod(); const incV = state.incluirVencidos; const params = new URLSearchParams(); params.set('per_page','100'); params.set('page','1'); params.set('start', p.start); params.set('end', p.end); if(!incV) params.set('status','pendente');
  const resp = await apiRequest(`/financeiro/contas-receber?${params.toString()}`); const json = await resp.json(); const rows = Array.isArray(json.data)? json.data:[];
  const tbody = document.querySelector('#tblReceber tbody'); if(rows.length===0){ tbody.innerHTML = `<tr><td colspan="6" class="muted">Nenhum título encontrado</td></tr>`; return; }
  tbody.innerHTML = rows.map(r=>{
    const st = (r.status||'').toLowerCase(); const d = r.data_vencimento||'-'; const style=rowStyle(st, d);
    return `<tr style="${style}">
      <td>${fmtDateBR(d)}</td>
      <td>${r.cliente||'-'}</td>
      <td>${r.documento||'-'}</td>
      <td>${r.descricao||'-'}</td>
      <td style="text-align:right;">${fmtBRL(r.valor||0)}</td>
      <td>${situationBadge(st, d)}</td>
    </tr>`;
  }).join('');
}

async function loadPagar(){ const p=getPeriod(); const incV = state.incluirVencidos; const params = new URLSearchParams(); params.set('per_page','100'); params.set('page','1'); params.set('start', p.start); params.set('end', p.end); if(!incV) params.set('status','pendente');
  const resp = await apiRequest(`/financeiro/contas-pagar?${params.toString()}`); const json = await resp.json(); const rows = Array.isArray(json.data)? json.data:[];
  const tbody = document.querySelector('#tblPagar tbody'); if(rows.length===0){ tbody.innerHTML = `<tr><td colspan="6" class="muted">Nenhum título encontrado</td></tr>`; return; }
  tbody.innerHTML = rows.map(r=>{
    const st = (r.status||'').toLowerCase(); const d = r.data_vencimento||'-'; const style=rowStyle(st, d);
    return `<tr style="${style}">
      <td>${fmtDateBR(d)}</td>
      <td>${r.fornecedor||'-'}</td>
      <td>${r.documento||'-'}</td>
      <td>${r.descricao||'-'}</td>
      <td style="text-align:right;">${fmtBRL(r.valor||0)}</td>
      <td>${situationBadge(st, d)}</td>
    </tr>`;
  }).join('');
}

async function applyFilters(skipPersist){ const hSel = document.getElementById('horizonte'); const incSel = document.getElementById('incluirVencidos'); const tipoSel = document.getElementById('tipoListagem');
  state.horizonte = Number(hSel.value||7); state.incluirVencidos = (incSel.value==='sim'); state.tipo = tipoSel.value||'ambos'; if(!skipPersist) persistState();
  updatePeriodInfo(); buildReceberExportLink(); buildPagarExportLink();
  // Mostrar/ocultar seções
  document.getElementById('secReceber').style.display = (state.tipo==='ambos' || state.tipo==='receber') ? '' : 'none';
  document.getElementById('secPagar').style.display   = (state.tipo==='ambos' || state.tipo==='pagar') ? '' : 'none';
  await loadResumo();
  if(state.tipo==='ambos' || state.tipo==='receber') await loadReceber();
  if(state.tipo==='ambos' || state.tipo==='pagar') await loadPagar();
  updateAging();
}

setTimeout(()=>{ updatePeriodInfo(); applyFilters(true); }, 50);

// Exportar Excel a partir da tabela visível
function exportTableToExcel(tableId, filename){ const table=document.getElementById(tableId); if(!table){ return; }
  const html = `\n<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">\n<head><meta charset=\"utf-8\" /></head><body>${table.outerHTML}</body></html>`;
  const blob = new Blob([html], { type: 'application/vnd.ms-excel' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href=url; a.download=filename||'export.xlsx'; document.body.appendChild(a); a.click(); setTimeout(()=>{ URL.revokeObjectURL(url); a.remove(); }, 100);
}

// Aging resumido com buckets: 0–7, 8–15, 16–30, >30 dias
function computeAgingFromTable(tableId){ const rows = Array.from(document.querySelectorAll(`#${tableId} tbody tr`));
  const buckets = { '0–7': {count:0,total:0}, '8–15': {count:0,total:0}, '16–30': {count:0,total:0}, '>30': {count:0,total:0} };
  rows.forEach(tr=>{
    const tds = tr.querySelectorAll('td'); if(tds.length<6) return; // ignora linhas de vazio
    const dateText = tds[0].textContent.trim();
    const valueText = tds[4].textContent.trim().replace(/[^0-9,-]/g,'').replace('.', '').replace(',', '.');
    const value = parseFloat(valueText||'0') || 0;
    const d = parseDate(dateText.replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$3-$2-$1'));
    const du = d? daysUntil(d.toISOString().slice(0,10)) : null;
    if(du===null){ return; }
    let key='';
    if(du<=7) key='0–7'; else if(du<=15) key='8–15'; else if(du<=30) key='16–30'; else key='>30';
    buckets[key].count += 1; buckets[key].total += value;
  });
  return buckets;
}

function renderAgingTable(elId, buckets){ const el=document.getElementById(elId); if(!el) return; const rows = Object.entries(buckets).map(([label,info])=>{
  return `<tr><td>${label}</td><td style="text-align:right;">${info.count}</td><td style="text-align:right;">${fmtBRL(info.total)}</td></tr>`;
}).join('');
  el.querySelector('tbody').innerHTML = rows || `<tr><td colspan="3" class="muted">Sem dados visíveis</td></tr>`;
}

function updateAging(){ const r = computeAgingFromTable('tblReceber'); const p = computeAgingFromTable('tblPagar');
  renderAgingTable('agingReceber', r); renderAgingTable('agingPagar', p);
}
</script>

<section class="card" id="secAging" style="margin:.75rem auto; max-width: 1000px;">
  <h2 style="margin-top:0;">Resumo por Faixa de Vencimento</h2>
  <p class="muted" style="margin:.25rem 0 .75rem 0;">Agrupa títulos por intervalos de dias até o vencimento: 0–7, 8–15, 16–30 e mais de 30 dias.</p>
  <div class="grid" style="grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .75rem;">
    <div>
      <h3 style="margin:.25rem 0;">Receber</h3>
      <div class="table-responsive">
        <table id="agingReceber" class="table">
          <thead>
            <tr>
              <th>Faixa de Vencimento</th>
              <th style="text-align:right;">Qtd</th>
              <th style="text-align:right;">Total</th>
            </tr>
          </thead>
          <tbody>
            <tr><td colspan="3" class="muted">Carregando…</td></tr>
          </tbody>
        </table>
      </div>
    </div>
    <div>
      <h3 style="margin:.25rem 0;">Pagar</h3>
      <div class="table-responsive">
        <table id="agingPagar" class="table">
          <thead>
            <tr>
              <th>Faixa de Vencimento</th>
              <th style="text-align:right;">Qtd</th>
              <th style="text-align:right;">Total</th>
            </tr>
          </thead>
          <tbody>
            <tr><td colspan="3" class="muted">Carregando…</td></tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</section>