<?php /* Página de Bancos */ ?>
<div class="page-header">
  <h1>Bancos</h1>
  <p class="muted">Gerencie contas bancárias e movimentações</p>
</div>

<!-- Ações -->
<section class="card">
  <div style="display:flex;gap:1rem;align-items:center;flex-wrap:wrap;">
    <button id="btnNovaConta" class="btn btn-success">Nova Conta Bancária</button>
    <button id="btnNovaMovimentacao" class="btn btn-primary">Nova Movimentação</button>
  </div>
</section>

<!-- Configurações de Pagamentos (Pix/Boletos) -->
<section class="card">
  <h3 style="display:flex;align-items:center;gap:6px;">Integrações de Pagamento
            <span style="font-size:12px;color:#555;cursor:help;" title="Endpoints dos webhooks: /api/payments/webhooks/mercadopago, /api/payments/webhooks/pagbank, /api/payments/webhooks/asaas">ℹ️</span>
        </h3>
  <p class="muted">Centralize aqui as integrações de pagamento. Use as abas para configurar cada banco e seus webhooks/credenciais.</p>

  <style>
    .tabs { display:flex; gap:0.5rem; border-bottom:1px solid #ddd; margin-bottom:0.75rem; }
    .tab { padding:0.5rem 0.75rem; cursor:pointer; border:1px solid #ddd; border-bottom:none; border-radius:6px 6px 0 0; background:#f7f7f7; }
    .tab.active { background:#fff; font-weight:600; }
    .tab-content { display:none; }
    .tab-content.active { display:block; }
    .provider-list { display: grid; gap: 0.75rem; }
    .provider-row { display: grid; grid-template-columns: minmax(220px, 36%) 1fr; gap: 1rem; align-items: center; }
    .provider-left { display: flex; align-items: center; gap: 0.5rem; }
    .provider-logo { width: 28px; height: 28px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; font-weight: 700; color: #fff; font-size: 12px; }
    .provider-logo.mp { background: #1e90ff; }
    .provider-logo.pg { background: #6b46c1; }
    .provider-logo.pag { background: #00a859; }
    .provider-logo.itau { background: #ff6600; }
    .provider-logo.asaas { background: #f59e0b; }
    .provider-name { font-weight: 600; }
    .provider-actions { display: grid; grid-template-columns: 1fr auto; gap: 0.5rem; align-items: center; }
    .provider-actions .status { display: block; min-height: 1em; }
    .provider-actions .endpoint { display:block; color:#666; font-size: 12px; }
    .endpoint-actions { display:flex; gap:0.5rem; align-items:center; }
    .btn-copy { font-size: 12px; padding: 0.25rem 0.5rem; }
  </style>

  <div class="tabs">
    <div class="tab active" data-tab="mercadopago">Mercado Pago</div>
    <div class="tab" data-tab="pagbank">PagBank</div>
    <div class="tab" data-tab="pagarme">Pagar.me</div>
    <div class="tab" data-tab="asaas">Asaas</div>
    <div class="tab" data-tab="itau">Itaú</div>
  </div>
  <div id="tab-mercadopago" class="tab-content active">
    <div class="provider-list">
      <div class="provider-row" data-provider="mercadopago">
        <div class="provider-left">
          <span class="provider-logo mp">MP</span>
          <span class="provider-name">Mercado Pago — Webhook Secret</span>
        </div>
        <div class="provider-actions">
          <input id="mpWebhookSecret" class="input" type="password" placeholder="Segredo MP" />
          <button id="btnSaveMP" class="btn btn-primary">Salvar MP</button>
          <small id="mpStatus" class="muted status"></small>
          <div class="endpoint-actions">
            <small id="mpEndpoint" class="endpoint"></small>
            <button id="btnCopyMp" class="btn btn-secondary btn-copy" title="Copiar endpoint">Copiar</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div id="tab-pagarme" class="tab-content">
    <div class="provider-list">
      <div class="provider-row" data-provider="pagarme">
        <div class="provider-left">
          <span class="provider-logo pg">PG</span>
          <span class="provider-name">Pagar.me (Stone) — Webhook Secret</span>
        </div>
        <div class="provider-actions">
          <input id="pgWebhookSecret" class="input" type="password" placeholder="Segredo Pagar.me" />
          <select id="pgTargetAccountId" class="input" title="Selecione a conta destino para conciliação">
            <option value="">Conta destino (opcional)</option>
          </select>
          <small id="pgTargetHint" class="muted">Entradas conciliadas serão atribuídas a esta conta.</small>
          <button id="btnSavePg" class="btn btn-primary">Salvar Pagar.me</button>
          <button id="btnTestPg" class="btn btn-secondary" title="Enviar evento de teste">Enviar teste</button>
          <small id="pgStatus" class="muted status"></small>
          <div class="endpoint-actions">
            <small id="pgEndpoint" class="endpoint"></small>
            <button id="btnCopyPg" class="btn btn-secondary btn-copy" title="Copiar endpoint">Copiar</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div id="tab-pagbank" class="tab-content">
    <div class="provider-list">
      <div class="provider-row" data-provider="pagbank">
        <div class="provider-left">
          <span class="provider-logo pag">PB</span>
          <span class="provider-name">PagBank — Webhook Secret</span>
        </div>
        <div class="provider-actions">
          <input id="pagWebhookSecret" class="input" type="password" placeholder="Segredo PagBank" />
          <button id="btnSavePag" class="btn btn-primary">Salvar PagBank</button>
          <small id="pagStatus" class="muted status"></small>
          <div class="endpoint-actions">
            <small id="pagEndpoint" class="endpoint"></small>
            <button id="btnCopyPag" class="btn btn-secondary btn-copy" title="Copiar endpoint">Copiar</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div id="tab-asaas" class="tab-content">
    <div class="provider-list">
      <div class="provider-row" data-provider="asaas">
        <div class="provider-left">
          <span class="provider-logo asaas">AS</span>
          <span class="provider-name">Asaas — Webhook Secret</span>
        </div>
        <div class="provider-actions">
          <input id="asaasWebhookSecret" class="input" type="password" placeholder="Segredo Asaas" />
          <button id="btnSaveAsaas" class="btn btn-primary">Salvar Asaas</button>
          <small id="asaasStatus" class="muted status"></small>
          <div class="endpoint-actions">
            <small id="asaasEndpoint" class="endpoint"></small>
            <button id="btnCopyAsaas" class="btn btn-secondary btn-copy" title="Copiar endpoint">Copiar</button>
          </div>
        </div>
      </div>
    </div>
    <section class="card" style="margin-top:1rem;">
      <h2 class="card-title">Asaas — Credenciais</h2>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
        <div>
          <label>Ambiente</label>
          <select id="asaasEnv" class="input">
            <option value="production">Produção</option>
            <option value="sandbox">Sandbox</option>
          </select>
        </div>
        <div>
          <label>Base URL (opcional)</label>
          <input id="asaasBaseUrl" class="input" placeholder="https://www.asaas.com/api/v3" />
        </div>
        <div style="grid-column:1 / span 2">
          <label>API Key</label>
          <input id="asaasApiKey" class="input" type="password" placeholder="Insira sua API Key do Asaas" />
          <small class="muted">Armazenada de forma criptografada por tenant.</small>
        </div>
      </div>
      <div style="margin-top:1rem;display:flex;gap:0.5rem;">
        <button class="btn btn-primary" id="btnSaveAsaasCfg">Salvar Configuração</button>
        <span id="asaasSaveMsg" class="muted" aria-live="polite"></span>
      </div>
      <div id="asaasStatusCfg" class="muted" style="margin-top:0.5rem;"></div>
    </section>
    <section class="card" style="margin-top:1rem;">
      <h2 class="card-title">Asaas — Operações</h2>
      <div style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
        <input id="asaasSearchCustomer" class="input" placeholder="Buscar cliente (nome)" style="width:320px;" />
        <button class="btn" id="asaasBtnListCustomers">Listar Clientes</button>
        <button class="btn" id="asaasBtnListPayments">Listar Pagamentos</button>
      </div>
      <div id="asaasResults" style="margin-top:1rem;max-height:300px;overflow:auto;"></div>
      <div id="asaasObservability" class="muted" style="margin-top:0.5rem;font-size:12px;display:flex;gap:1rem;flex-wrap:wrap;">
        <span>Clientes listados: <strong id="asaasStatsCustomers">0</strong></span>
        <span>Pagamentos listados: <strong id="asaasStatsPayments">0</strong></span>
        <span>Links gerados: <strong id="asaasStatsLinks">0</strong></span>
        <span>Último erro: <strong id="asaasStatsLastErr">—</strong></span>
      </div>
    </section>
    <section class="card" style="margin-top:1rem;">
      <h2 class="card-title">Asaas — Gerar Link de Pagamento (Venda)</h2>
      <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:0.75rem;">
        <div>
          <label>ID da Venda</label>
          <input id="asaasSaleId" class="input" placeholder="Ex.: SO-2025-0001"/>
        </div>
        <div>
          <label>ID do Cliente (local)</label>
          <input id="asaasClientId" class="input" type="number" min="1" placeholder="ID na tabela clients"/>
        </div>
        <div>
          <label>Valor (centavos)</label>
          <input id="asaasAmountCents" class="input" type="number" min="100" placeholder="Ex.: 12500 para R$125,00"/>
        </div>
        <div>
          <label>Vencimento</label>
          <input id="asaasDueDate" class="input" type="date"/>
        </div>
        <div>
          <label>Tipo de Cobrança</label>
          <select id="asaasBillingType" class="input">
            <option value="BOLETO">Boleto</option>
            <option value="PIX">PIX</option>
            <option value="CREDIT_CARD">Cartão</option>
          </select>
        </div>
      </div>
      <div style="margin-top:0.75rem;display:flex;gap:0.5rem;align-items:center;">
        <button class="btn btn-primary" id="asaasBtnGenLink">Gerar Link</button>
        <span id="asaasGenMsg" class="muted" aria-live="polite"></span>
      </div>
      <div id="asaasGenResult" style="margin-top:0.5rem;"></div>
    </section>
  </div>
  <div id="tab-itau" class="tab-content">
    <div class="provider-list">
      <div class="provider-row" data-provider="itau">
        <div class="provider-left">
          <span class="provider-logo itau">IT</span>
          <span class="provider-name">Itaú — Webhook Pix Secret</span>
        </div>
        <div class="provider-actions">
          <input id="itauWebhookSecret" class="input" type="password" placeholder="Segredo Itaú" />
          <select id="itauTargetAccountId" class="input" title="Selecione a conta destino para conciliação de Pix">
            <option value="">Conta destino (opcional)</option>
          </select>
          <small id="itauTargetHint" class="muted">Recebimentos Pix serão conciliados nesta conta.</small>
          <button id="btnSaveItau" class="btn btn-primary">Salvar Itaú</button>
          <button id="btnTestItau" class="btn btn-secondary" title="Enviar evento de teste">Enviar teste</button>
          <small id="itauStatus" class="muted status"></small>
          <div class="endpoint-actions">
            <small id="itauEndpoint" class="endpoint"></small>
            <button id="btnCopyItau" class="btn btn-secondary btn-copy" title="Copiar endpoint">Copiar</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
<!-- Contas Bancárias -->
<section class="card">
  <h3>Contas Bancárias</h3>
  <div style="overflow-x:auto;">
    <table class="table">
      <thead>
        <tr>
          <th>Banco</th>
          <th>Agência</th>
          <th>Conta</th>
          <th>Tipo</th>
          <th>Saldo</th>
          <th>Status</th>
          <th>Ações</th>
        </tr>
      </thead>
      <tbody id="contasBancariasTableBody">
        <tr>
          <td colspan="7" style="text-align:center;padding:2rem;">
            <div class="loading">Carregando contas...</div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</section>

<!-- Movimentações Recentes -->
<section class="card">
  <h3>Movimentações Recentes</h3>
  <div class="form-row" style="margin-bottom:0.5rem; align-items:flex-end; gap:0.75rem; flex-wrap:wrap;">
    <div class="form-group">
      <label for="mov_conta_filter">Conta</label>
      <select id="mov_conta_filter" class="input" style="min-width:260px;">
        <option value="">Todas</option>
      </select>
    </div>
    <div class="form-group">
      <label for="mov_start_filter">Início</label>
      <input type="date" id="mov_start_filter" class="input" />
    </div>
    <div class="form-group">
      <label for="mov_end_filter">Fim</label>
      <input type="date" id="mov_end_filter" class="input" />
    </div>
    <div class="form-group" style="display:flex; gap:0.5rem;">
      <button id="btnApplyMovFilters" class="btn btn-primary">Aplicar</button>
      <button id="btnClearMovFilters" class="btn btn-secondary">Limpar</button>
    </div>
  </div>
  <div style="overflow-x:auto;">
    <table class="table">
      <thead>
        <tr>
          <th>Data</th>
          <th>Conta</th>
          <th>Descrição</th>
          <th>Tipo</th>
          <th>Valor</th>
          <th>Saldo</th>
        </tr>
      </thead>
      <tbody id="movimentacoesTableBody">
        <tr>
          <td colspan="6" style="text-align:center;padding:2rem;">
            <div class="loading">Carregando movimentações...</div>
          </td>
        </tr>
      </tbody>
    </table>
    <div id="movPagination" style="display:flex; justify-content:flex-end; align-items:center; gap:0.5rem; padding-top:0.5rem;">
      <button id="btnPrevMov" class="btn btn-secondary" disabled>Anterior</button>
      <span id="movPageInfo" class="muted">Página 1 de 1</span>
      <button id="btnNextMov" class="btn btn-secondary" disabled>Próxima</button>
    </div>
  </div>
</section>

<!-- Modal Nova Conta Bancária -->
<div id="contaBancariaModal" class="modal" style="display:none;">
  <div class="modal-content">
    <div class="modal-header">
      <h3>Nova Conta Bancária</h3>
      <button class="modal-close" onclick="closeContaBancariaModal()">&times;</button>
    </div>
    <form id="contaBancariaForm">
      <div class="form-row">
        <div class="form-group">
          <label for="banco">Banco *</label>
          <input type="text" id="banco" name="banco" class="input" required />
        </div>
        <div class="form-group">
          <label for="agencia">Agência *</label>
          <input type="text" id="agencia" name="agencia" class="input" required />
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label for="conta">Conta *</label>
          <input type="text" id="conta" name="conta" class="input" required />
        </div>
        <div class="form-group">
          <label for="tipo_conta">Tipo *</label>
          <select id="tipo_conta" name="tipo_conta" class="input" required>
            <option value="">Selecione</option>
            <option value="corrente">Conta Corrente</option>
            <option value="poupanca">Poupança</option>
            <option value="investimento">Investimento</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label for="saldo_inicial">Saldo Inicial</label>
        <input type="number" id="saldo_inicial" name="saldo_inicial" class="input" step="0.01" value="0" />
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-secondary" onclick="closeContaBancariaModal()">Cancelar</button>
        <button type="submit" class="btn btn-primary">Salvar</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Nova Movimentação -->
<div id="movimentacaoModal" class="modal" style="display:none;">
  <div class="modal-content">
    <div class="modal-header">
      <h3>Nova Movimentação</h3>
      <button class="modal-close" onclick="closeMovimentacaoModal()">&times;</button>
    </div>
    <form id="movimentacaoForm">
      <div class="form-row">
        <div class="form-group">
          <label for="conta_bancaria_id">Conta Bancária *</label>
          <select id="conta_bancaria_id" name="conta_bancaria_id" class="input" required>
            <option value="">Selecione uma conta</option>
          </select>
        </div>
        <div class="form-group">
          <label for="data_movimentacao">Data *</label>
          <input type="date" id="data_movimentacao" name="data_movimentacao" class="input" required />
        </div>
      </div>
      <div class="form-group">
        <label for="descricao_mov">Descrição *</label>
        <input type="text" id="descricao_mov" name="descricao" class="input" required />
      </div>
      <div class="form-row">
        <div class="form-group">
          <label for="tipo_movimentacao">Tipo *</label>
          <select id="tipo_movimentacao" name="tipo" class="input" required>
            <option value="">Selecione</option>
            <option value="entrada">Entrada</option>
            <option value="saida">Saída</option>
          </select>
        </div>
        <div class="form-group">
          <label for="valor_movimentacao">Valor *</label>
          <input type="number" id="valor_movimentacao" name="valor" class="input" step="0.01" min="0" required />
        </div>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-secondary" onclick="closeMovimentacaoModal()">Cancelar</button>
        <button type="submit" class="btn btn-primary">Salvar</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Editar Conta Bancária -->
<div id="editContaModal" class="modal" style="display:none;">
  <div class="modal-content">
    <div class="modal-header">
      <h3>Editar Conta Bancária</h3>
      <button class="modal-close" onclick="closeEditContaModal()">&times;</button>
    </div>
    <form id="editContaForm">
      <input type="hidden" id="edit_id" name="id" />
      <div class="form-row">
        <div class="form-group">
          <label for="edit_banco">Banco *</label>
          <input type="text" id="edit_banco" name="banco" class="input" required />
        </div>
        <div class="form-group">
          <label for="edit_agencia">Agência *</label>
          <input type="text" id="edit_agencia" name="agencia" class="input" required />
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label for="edit_conta">Conta *</label>
          <input type="text" id="edit_conta" name="conta" class="input" required />
        </div>
        <div class="form-group">
          <label for="edit_tipo_conta">Tipo *</label>
          <select id="edit_tipo_conta" name="tipo" class="input" required>
            <option value="">Selecione</option>
            <option value="corrente">Conta Corrente</option>
            <option value="poupanca">Poupança</option>
            <option value="investimento">Investimento</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label for="edit_status">Status *</label>
        <select id="edit_status" name="status" class="input" required>
          <option value="ativa">Ativa</option>
          <option value="inativa">Inativa</option>
        </select>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-secondary" onclick="closeEditContaModal()">Cancelar</button>
        <button type="submit" class="btn btn-primary">Salvar Alterações</button>
      </div>
    </form>
  </div>
  
</div>

<!-- Modal Extrato da Conta -->
<div id="extratoModal" class="modal" style="display:none;">
  <div class="modal-content" style="max-width:900px;">
    <div class="modal-header">
      <h3>Extrato da Conta</h3>
      <button class="modal-close" onclick="closeExtratoModal()">&times;</button>
    </div>
    <div class="form-row" style="padding:.5rem 0; align-items:flex-end;">
      <div class="form-group" style="min-width:280px;">
        <label>Conta</label>
        <div id="extratoHeader" class="muted">-</div>
      </div>
    </div>
    <div style="overflow-x:auto; max-height:60vh; overflow-y:auto;">
      <table class="table">
        <thead>
          <tr>
            <th>Data</th>
            <th>Descrição</th>
            <th>Tipo</th>
            <th>Valor</th>
            <th>Saldo</th>
          </tr>
        </thead>
        <tbody id="extratoTableBody">
          <tr>
            <td colspan="5" style="text-align:center;padding:2rem;">Carregando extrato...</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="modal-actions">
      <button class="btn" onclick="closeExtratoModal()">Fechar</button>
    </div>
  </div>
  
</div>

<script>
(function() {
  // Fallback de apiRequest: se não houver global, define em window e retorna JSON
  if (typeof window.apiRequest !== 'function') {
    window.apiRequest = async function(url, options = {}) {
      const headers = { 'Accept': 'application/json', ...(options.headers || {}) };
      let body = options.body;
      // Converter objetos em JSON quando não for FormData
      if (body && typeof body === 'object' && !(body instanceof FormData)) {
        headers['Content-Type'] = headers['Content-Type'] || 'application/json';
        body = JSON.stringify(body);
      }
      try {
        const lsToken = localStorage.getItem('auth_token');
        const m = document.cookie.match(/(?:^|; )auth_token=([^;]+)/);
        const token = lsToken || (m ? decodeURIComponent(m[1]) : '');
        if (token && !headers['Authorization']) headers['Authorization'] = `Bearer ${token}`;
        const mTenant = document.cookie.match(/(?:^|; )x-tenant-id=([^;]+)/);
        if (!headers['x-tenant-id']) headers['x-tenant-id'] = mTenant ? decodeURIComponent(mTenant[1]) : 'default';
      } catch(_) {}
      const resp = await fetch(url, { ...options, headers, body, credentials: 'include', cache: 'no-store' });
      if (!resp.ok) { throw new Error(`HTTP ${resp.status}`); }
      return resp.json();
    };
  }
  const apiRequest = window.apiRequest;
  // Estado de filtros/paginação para movimentações
  const movState = { page: 1, per_page: 50, conta_id: '', start: '', end: '', total_pages: 1 };

  // Carregar contas bancárias da API
  async function loadContasBancarias() {
    try {
      const json = await apiRequest('/api/financeiro/bancos/contas?per_page=100');
      const contas = Array.isArray(json.data) ? json.data : [];
      window.__contasCache = contas;
      renderContasBancarias(contas);
      populateContasSelect(contas);
      populateMovFilterContas(contas);
      if (typeof window.populatePaymentTargetSelects === 'function') {
        try { window.populatePaymentTargetSelects(contas); } catch(_) {}
      }
    } catch (e) {
      console.error('Falha ao carregar contas', e);
      const tbody = document.getElementById('contasBancariasTableBody');
      tbody.innerHTML = `<tr><td colspan="7" style="text-align:center;color:#b91c1c;">Erro ao carregar contas: ${String(e.message||e)}</td></tr>`;
    }
  }

  // Carregar movimentações da API
  async function loadMovimentacoes() {
    try {
      const params = new URLSearchParams();
      params.set('per_page', String(movState.per_page));
      params.set('page', String(movState.page));
      if (movState.conta_id) params.set('conta_id', String(movState.conta_id));
      if (movState.start) params.set('start', String(movState.start));
      if (movState.end) params.set('end', String(movState.end));
      const url = `/api/financeiro/bancos/movimentos?${params.toString()}`;
      const json = await apiRequest(url);
      const movs = Array.isArray(json.data) ? json.data : [];
      const normalized = movs.map(m => ({
        data: m.data,
        conta: m.conta_label || String(m.conta_id || ''),
        descricao: m.descricao,
        tipo: m.tipo,
        valor: parseFloat(m.valor),
        saldo: parseFloat(m.saldo)
      }));
      renderMovimentacoes(normalized);
      const pg = json.pagination || {};
      movState.total_pages = Number(pg.total_pages || 1);
      movState.page = Number(pg.page || movState.page);
      updateMovPagination();
    } catch (e) {
      console.error('Falha ao carregar movimentações', e);
      const tbody = document.getElementById('movimentacoesTableBody');
      tbody.innerHTML = `<tr><td colspan="6" style="text-align:center;color:#b91c1c;">Erro ao carregar movimentações: ${String(e.message||e)}</td></tr>`;
    }
  }

  // Renderizar contas bancárias
  function renderContasBancarias(contas) {
    const tbody = document.getElementById('contasBancariasTableBody');
    
    if (contas.length === 0) {
      tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;">Nenhuma conta encontrada</td></tr>';
      return;
    }

    tbody.innerHTML = contas.map(conta => {
      const statusClass = conta.status === 'ativa' ? 'success' : 'danger';
      
      return `
        <tr>
          <td>${conta.banco}</td>
          <td>${conta.agencia}</td>
          <td>${conta.conta}</td>
          <td>${conta.tipo}</td>
          <td>R$ ${conta.saldo.toFixed(2).replace('.', ',')}</td>
          <td><span class="badge badge-${statusClass}">${conta.status}</span></td>
          <td>
            <div style="display:flex;gap:0.25rem;">
              <button class="btn btn-sm btn-secondary" onclick="editConta(${conta.id})" title="Editar">✏️</button>
              <button class="btn btn-sm btn-info" onclick="verExtrato(${conta.id})" title="Extrato">📊</button>
            </div>
          </td>
        </tr>
      `;
    }).join('');
  }

  // Renderizar movimentações
  function renderMovimentacoes(movimentacoes) {
    const tbody = document.getElementById('movimentacoesTableBody');
    
    if (movimentacoes.length === 0) {
      tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;">Nenhuma movimentação encontrada</td></tr>';
      return;
    }

    tbody.innerHTML = movimentacoes.map(mov => {
      const tipoClass = mov.tipo === 'entrada' ? 'success' : 'danger';
      
      return `
        <tr>
          <td>${new Date(mov.data).toLocaleDateString('pt-BR')}</td>
          <td>${mov.conta}</td>
          <td>${mov.descricao}</td>
          <td><span class="badge badge-${tipoClass}">${mov.tipo}</span></td>
          <td>R$ ${mov.valor.toFixed(2).replace('.', ',')}</td>
          <td>R$ ${mov.saldo.toFixed(2).replace('.', ',')}</td>
        </tr>
      `;
    }).join('');
  }

  // Popular select de contas
  function populateContasSelect(contas) {
    const select = document.getElementById('conta_bancaria_id');
    const opts = contas.map(conta => {
      const disabled = String(conta.status) !== 'ativa' ? ' disabled' : '';
      const label = `${conta.banco} - ${conta.agencia} - ${conta.conta}` + (disabled ? ' (inativa)' : '');
      return `<option value="${conta.id}"${disabled}>${label}</option>`;
    }).join('');
    select.innerHTML = '<option value="">Selecione uma conta</option>' + opts;
    const firstActive = contas.find(c => String(c.status) === 'ativa');
    if (firstActive) { select.value = String(firstActive.id); }
  }

  // Popular filtro de contas (não desabilitar, exibir tag)
  function populateMovFilterContas(contas) {
    const select = document.getElementById('mov_conta_filter');
    if (!select) return;
    const opts = contas.map(conta => {
      const label = `${conta.banco} - ${conta.agencia} - ${conta.conta}` + (String(conta.status) !== 'ativa' ? ' (inativa)' : '');
      return `<option value="${conta.id}">${label}</option>`;
    }).join('');
    select.innerHTML = '<option value="">Todas</option>' + opts;
  }

  // Event listeners
  document.getElementById('btnNovaConta').addEventListener('click', function() {
    document.getElementById('contaBancariaForm').reset();
    document.getElementById('contaBancariaModal').style.display = 'flex';
  });

  document.getElementById('btnNovaMovimentacao').addEventListener('click', function() {
    document.getElementById('movimentacaoForm').reset();
    document.getElementById('data_movimentacao').value = new Date().toISOString().split('T')[0];
    document.getElementById('movimentacaoModal').style.display = 'flex';
    // selecionar primeira conta ativa, se disponível
    const contas = Array.isArray(window.__contasCache) ? window.__contasCache : [];
    const firstActive = contas.find(c => String(c.status) === 'ativa');
    if (firstActive) {
      const sel = document.getElementById('conta_bancaria_id');
      sel.value = String(firstActive.id);
    }
  });

  // Salvar conta bancária
  document.getElementById('contaBancariaForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const payload = {
      banco: document.getElementById('banco').value.trim(),
      agencia: document.getElementById('agencia').value.trim(),
      conta: document.getElementById('conta').value.trim(),
      tipo_conta: document.getElementById('tipo_conta').value,
      saldo_inicial: parseFloat(document.getElementById('saldo_inicial').value || '0')
    };
    apiRequest('/api/financeiro/bancos/contas', { method: 'POST', body: JSON.stringify(payload) })
      .then(() => {
        alert('Conta bancária salva com sucesso!');
        closeContaBancariaModal();
        loadContasBancarias();
        populateContasSelect([]); // será repopulado por loadContasBancarias
      })
      .catch(err => alert('Falha ao salvar conta: ' + String(err.message||err)));
  });

  // Salvar movimentação
  document.getElementById('movimentacaoForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const contas = Array.isArray(window.__contasCache) ? window.__contasCache : [];
    const contaId = parseInt(document.getElementById('conta_bancaria_id').value || '0', 10);
    const cSel = contas.find(c => Number(c.id) === contaId);
    if (!cSel) { alert('Selecione uma conta válida'); return; }
    if (String(cSel.status) !== 'ativa') { alert('Conta inativa: não é possível registrar movimentações.'); return; }
    const payload = {
      conta_bancaria_id: contaId,
      data_movimentacao: document.getElementById('data_movimentacao').value,
      descricao: document.getElementById('descricao_mov').value.trim(),
      tipo: document.getElementById('tipo_movimentacao').value,
      valor: parseFloat(document.getElementById('valor_movimentacao').value || '0')
    };
    apiRequest('/api/financeiro/bancos/movimentos', { method: 'POST', body: JSON.stringify(payload) })
      .then(res => {
        alert('Movimentação registrada com sucesso!');
        closeMovimentacaoModal();
        loadMovimentacoes();
        loadContasBancarias(); // saldo atualizado
      })
      .catch(err => alert('Falha ao registrar movimentação: ' + String(err.message||err)));
  });

  // Aplicar/Limpar filtros
  document.getElementById('btnApplyMovFilters').addEventListener('click', function(){
    const contaVal = document.getElementById('mov_conta_filter').value || '';
    const start = document.getElementById('mov_start_filter').value || '';
    const end = document.getElementById('mov_end_filter').value || '';
    movState.conta_id = contaVal ? parseInt(contaVal, 10) : '';
    movState.start = start;
    movState.end = end;
    movState.page = 1;
    loadMovimentacoes();
  });
  document.getElementById('btnClearMovFilters').addEventListener('click', function(){
    document.getElementById('mov_conta_filter').value = '';
    document.getElementById('mov_start_filter').value = '';
    document.getElementById('mov_end_filter').value = '';
    movState.conta_id = '';
    movState.start = '';
    movState.end = '';
    movState.page = 1;
    loadMovimentacoes();
  });

  // Paginação
  function updateMovPagination() {
    const prevBtn = document.getElementById('btnPrevMov');
    const nextBtn = document.getElementById('btnNextMov');
    const info = document.getElementById('movPageInfo');
    const tp = Math.max(1, Number(movState.total_pages || 1));
    const cp = Math.max(1, Math.min(tp, Number(movState.page || 1)));
    info.textContent = `Página ${cp} de ${tp}`;
    prevBtn.disabled = cp <= 1;
    nextBtn.disabled = cp >= tp;
  }
  document.getElementById('btnPrevMov').addEventListener('click', function(){
    if (movState.page > 1) { movState.page -= 1; loadMovimentacoes(); }
  });
  document.getElementById('btnNextMov').addEventListener('click', function(){
    if (movState.page < movState.total_pages) { movState.page += 1; loadMovimentacoes(); }
  });

  // Funções globais
  window.closeContaBancariaModal = function() {
    document.getElementById('contaBancariaModal').style.display = 'none';
  };

  window.closeMovimentacaoModal = function() {
    document.getElementById('movimentacaoModal').style.display = 'none';
  };

  window.editConta = function(id) {
    try {
      const contas = Array.isArray(window.__contasCache) ? window.__contasCache : [];
      const conta = contas.find(c => Number(c.id) === Number(id));
      if (!conta) { alert('Conta não encontrada'); return; }
      // preencher campos
      document.getElementById('edit_id').value = String(conta.id);
      document.getElementById('edit_banco').value = String(conta.banco || '');
      document.getElementById('edit_agencia').value = String(conta.agencia || '');
      document.getElementById('edit_conta').value = String(conta.conta || '');
      document.getElementById('edit_tipo_conta').value = String(conta.tipo || '');
      document.getElementById('edit_status').value = String(conta.status || 'ativa');
      // abrir modal
      document.getElementById('editContaModal').style.display = 'flex';
    } catch (e) {
      alert('Falha ao preparar edição: ' + String(e.message||e));
    }
  };

  window.closeEditContaModal = function() {
    document.getElementById('editContaModal').style.display = 'none';
  };

  // Salvar edição da conta
  (function bindEditForm(){
    const form = document.getElementById('editContaForm');
    if (!form) return;
    form.addEventListener('submit', function(e){
      e.preventDefault();
      const id = parseInt(document.getElementById('edit_id').value || '0', 10);
      if (!id) { alert('ID inválido'); return; }
      const payload = {
        banco: document.getElementById('edit_banco').value.trim(),
        agencia: document.getElementById('edit_agencia').value.trim(),
        conta: document.getElementById('edit_conta').value.trim(),
        tipo: document.getElementById('edit_tipo_conta').value,
        status: document.getElementById('edit_status').value
      };
      apiRequest(`/api/financeiro/bancos/contas/${id}`, { method: 'PUT', body: payload })
        .then(() => {
          alert('Conta atualizada com sucesso!');
          closeEditContaModal();
          loadContasBancarias();
        })
        .catch(err => alert('Falha ao atualizar conta: ' + String(err.message||err)));
    });
  })();

  window.verExtrato = async function(id) {
    try {
      const end = new Date();
      const start = new Date(Date.now() - 29*24*60*60*1000);
      const toISO = (d)=> `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
      const json = await apiRequest(`/api/financeiro/bancos/contas/${id}/extrato?start=${encodeURIComponent(toISO(start))}&end=${encodeURIComponent(toISO(end))}`);
      const conta = json.conta || {};
      const movs = Array.isArray(json.data) ? json.data : [];
      const tbody = document.getElementById('extratoTableBody');
      tbody.innerHTML = movs.length ? movs.map(m => {
        const tipoClass = m.tipo === 'entrada' ? 'success' : 'danger';
        const d = new Date(m.data);
        const ddmmyyyy = isNaN(d) ? String(m.data) : `${String(d.getDate()).padStart(2,'0')}-${String(d.getMonth()+1).padStart(2,'0')}-${d.getFullYear()}`;
        const fmt = (v)=> 'R$ ' + Number(v||0).toFixed(2).replace('.', ',');
        return `
          <tr>
            <td>${ddmmyyyy}</td>
            <td>${m.descricao}</td>
            <td><span class="badge badge-${tipoClass}">${m.tipo}</span></td>
            <td>${fmt(m.valor)}</td>
            <td>${fmt(m.saldo)}</td>
          </tr>
        `;
      }).join('') : '<tr><td colspan="5" style="text-align:center;">Nenhuma movimentação no período</td></tr>';
      document.getElementById('extratoHeader').textContent = `${conta.banco || ''} ${conta.agencia || ''} • ${conta.conta || ''}`.trim();
      document.getElementById('extratoModal').style.display = 'flex';
    } catch (e) {
      alert('Falha ao carregar extrato: ' + String(e.message||e));
    }
  };

  window.closeExtratoModal = function() { document.getElementById('extratoModal').style.display = 'none'; };

  // Carregar dados iniciais
  loadContasBancarias();
  loadMovimentacoes();
})();
</script>

<script>
// Integrações de Pagamento: carregar e salvar segredos de webhook
(function() {
  const qs = (sel) => document.querySelector(sel);
  const map = {
    mercadopago: { status: '#mpStatus', input: '#mpWebhookSecret', btn: '#btnSaveMP' },
    pagbank: { status: '#pagStatus', input: '#pagWebhookSecret', btn: '#btnSavePag' },
    pagarme: { status: '#pgStatus', input: '#pgWebhookSecret', btn: '#btnSavePg', target: '#pgTargetAccountId' },
    asaas: { status: '#asaasStatus', input: '#asaasWebhookSecret', btn: '#btnSaveAsaas' },
    itau: { status: '#itauStatus', input: '#itauWebhookSecret', btn: '#btnSaveItau', target: '#itauTargetAccountId' }
  };

  // Popular dropdowns de Conta destino com contas ativas
  function optionLabel(c) {
    return `${c.banco} - ${c.agencia} - ${c.conta}` + (String(c.status) !== 'ativa' ? ' (inativa)' : '');
  }
  window.populatePaymentTargetSelects = function(contas) {
    const list = Array.isArray(contas) ? contas : (Array.isArray(window.__contasCache) ? window.__contasCache : []);
    const active = list.filter(c => String(c.status) === 'ativa');
    const buildOpts = (currentVal) => {
      const base = '<option value="">Conta destino (opcional)</option>' + active.map(c => `<option value="${c.id}">${optionLabel(c)}</option>`).join('');
      return base;
    };
    const pgSel = qs('#pgTargetAccountId');
    if (pgSel) {
      const prev = pgSel.value || '';
      pgSel.innerHTML = buildOpts(prev);
      if (prev) pgSel.value = prev;
    }
    const itSel = qs('#itauTargetAccountId');
    if (itSel) {
      const prev = itSel.value || '';
      itSel.innerHTML = buildOpts(prev);
      if (prev) itSel.value = prev;
    }
  };

  async function loadProvider(provider) {
    const cfg = map[provider] || {};
    const statusEl = qs(cfg.status);
    const inputEl = qs(cfg.input);
    const targetEl = cfg.target ? qs(cfg.target) : null;
    try {
      statusEl.textContent = '';
      const res = await apiRequest(`/api/payments/settings/${provider}`, { method: 'GET' });
      const hasSecret = !!(res && res.has_webhook_secret);
      inputEl.value = '';
      statusEl.textContent = hasSecret ? 'Segredo existente' : '';
      if ((provider === 'pagarme' || provider === 'itau') && targetEl) {
        targetEl.value = res && res.target_account_id ? String(res.target_account_id) : '';
      }
      // Atualiza com último evento recebido
      try {
        const resp = await fetch(`/api/payments/events/last/${provider}`);
        if (resp.ok) {
          const data = await resp.json();
          if (data.last_received_at) {
            const human = new Date(data.last_received_at).toLocaleString();
            statusEl.textContent = statusEl.textContent ? `${statusEl.textContent} • Último evento: ${human}` : `Último evento: ${human}`;
          }
        }
      } catch (_) {}
    } catch (err) {
      console.error('Erro ao carregar config', provider, err);
      statusEl.textContent = 'Erro ao carregar';
    }
  }

  async function saveProvider(provider) {
    const cfg = map[provider] || {};
    const statusEl = qs(cfg.status);
    const inputEl = qs(cfg.input);
    const targetEl = cfg.target ? qs(cfg.target) : null;
    const secret = inputEl.value.trim();
    if (!secret) {
      statusEl.textContent = 'Informe o segredo antes de salvar';
      return;
    }
    try {
      statusEl.textContent = 'Salvando…';
      const body = { webhook_secret: secret };
      if (provider === 'pagarme' || provider === 'itau') {
        const raw = targetEl ? targetEl.value.trim() : '';
        const idNum = raw ? parseInt(raw, 10) : null;
        body.target_account_id = Number.isFinite(idNum) && idNum > 0 ? idNum : null;
      }
      await apiRequest(`/api/payments/settings/${provider}`, { method: 'POST', body });
      statusEl.textContent = 'Salvo com sucesso';
    } catch (err) {
      console.error('Erro ao salvar config', provider, err);
      statusEl.textContent = 'Erro ao salvar';
    }
  }

  // Bind eventos
  const btnSaveMP = qs(map.mercadopago.btn);
  const btnSavePag = qs(map.pagbank.btn);
  const btnSavePg = qs(map.pagarme.btn);
  const btnTestPg = qs('#btnTestPg');
  const btnSaveAsaas = qs(map.asaas.btn);
  const btnSaveItau = qs(map.itau.btn);
  if (btnSaveMP) btnSaveMP.addEventListener('click', () => saveProvider('mercadopago'));
  if (btnSavePag) btnSavePag.addEventListener('click', () => saveProvider('pagbank'));
  if (btnSavePg) btnSavePg.addEventListener('click', () => saveProvider('pagarme'));
  if (btnTestPg) btnTestPg.addEventListener('click', async () => {
    const statusEl = qs(map.pagarme.status);
    statusEl.textContent = 'Enviando teste…';
    try {
      await apiRequest('/api/payments/simulate/pagarme', { method: 'POST', body: { event: 'charge.paid', type: 'charge', charge: { id: 'ui_pg_' + Date.now(), status: 'paid', amount: 9900 } } });
      statusEl.textContent = 'Teste enviado';
      // Recarrega estado para trazer "Último evento"
      await loadProvider('pagarme');
    } catch (e) {
      console.error('Falha ao simular webhook Pagar.me', e);
      statusEl.textContent = 'Falha ao enviar teste';
    }
  });
  if (btnSaveAsaas) btnSaveAsaas.addEventListener('click', () => saveProvider('asaas'));
  if (btnSaveItau) btnSaveItau.addEventListener('click', () => saveProvider('itau'));
  const btnTestItau = qs('#btnTestItau');
  if (btnTestItau) btnTestItau.addEventListener('click', async () => {
    const statusEl = qs(map.itau.status);
    statusEl.textContent = 'Enviando teste…';
    try {
      await apiRequest('/api/payments/simulate/itau', { method: 'POST', body: { pix: [{ endToEndId: 'ui_itau_' + Date.now(), txid: 'uitx_' + Date.now(), valor: '99.90', horario: new Date().toISOString() }], status: 'received' } });
      statusEl.textContent = 'Teste enviado';
      await loadProvider('itau');
    } catch (e) {
      console.error('Falha ao simular webhook Itaú', e);
      statusEl.textContent = 'Falha ao enviar teste';
    }
  });

  // Endpoints por provedor e copiar para área de transferência
  const origin = window.location.origin || (location.protocol + '//' + location.host);
  const endpoints = {
    mercadopago: origin + '/api/payments/webhooks/mercadopago',
    pagbank: origin + '/api/payments/webhooks/pagbank',
    pagarme: origin + '/api/payments/webhooks/pagarme',
    asaas: origin + '/api/payments/webhooks/asaas',
    itau: origin + '/api/payments/webhooks/itau'
  };
  const mpEndpointEl = qs('#mpEndpoint'); if (mpEndpointEl) mpEndpointEl.textContent = endpoints.mercadopago;
  const pagEndpointEl = qs('#pagEndpoint'); if (pagEndpointEl) pagEndpointEl.textContent = endpoints.pagbank;
  const pgEndpointEl = qs('#pgEndpoint'); if (pgEndpointEl) pgEndpointEl.textContent = endpoints.pagarme;
  const asaasEndpointEl = qs('#asaasEndpoint'); if (asaasEndpointEl) asaasEndpointEl.textContent = endpoints.asaas;
  const itauEndpointEl = qs('#itauEndpoint'); if (itauEndpointEl) itauEndpointEl.textContent = endpoints.itau;
  const btnCopyMp = qs('#btnCopyMp'); if (btnCopyMp) btnCopyMp.addEventListener('click', () => navigator.clipboard.writeText(endpoints.mercadopago).then(()=>alert('Endpoint copiado')).catch(()=>alert('Falha ao copiar')));
  const btnCopyPag = qs('#btnCopyPag'); if (btnCopyPag) btnCopyPag.addEventListener('click', () => navigator.clipboard.writeText(endpoints.pagbank).then(()=>alert('Endpoint copiado')).catch(()=>alert('Falha ao copiar')));
  const btnCopyPg = qs('#btnCopyPg'); if (btnCopyPg) btnCopyPg.addEventListener('click', () => navigator.clipboard.writeText(endpoints.pagarme).then(()=>alert('Endpoint copiado')).catch(()=>alert('Falha ao copiar')));
  const btnCopyAsaas = qs('#btnCopyAsaas'); if (btnCopyAsaas) btnCopyAsaas.addEventListener('click', () => navigator.clipboard.writeText(endpoints.asaas).then(()=>alert('Endpoint copiado')).catch(()=>alert('Falha ao copiar')));
  const btnCopyItau = qs('#btnCopyItau'); if (btnCopyItau) btnCopyItau.addEventListener('click', () => navigator.clipboard.writeText(endpoints.itau).then(()=>alert('Endpoint copiado')).catch(()=>alert('Falha ao copiar')));

  // Inicializar estado
  loadProvider('mercadopago');
  loadProvider('pagbank');
  loadProvider('pagarme');
  loadProvider('asaas');
  loadProvider('itau');
  // Popular selects iniciais caso contas já estejam em cache
  try { window.populatePaymentTargetSelects(window.__contasCache || []); } catch(_) {}
})();
</script>

<script>
// Navegação por abas e lógica do painel Asaas
(function(){
  const tabs = Array.from(document.querySelectorAll('.tabs .tab'));
  const contents = Array.from(document.querySelectorAll('.tab-content'));
  function activate(name){
    tabs.forEach(t => t.classList.toggle('active', t.dataset.tab === name));
    contents.forEach(c => c.classList.toggle('active', c.id === 'tab-' + name));
    if (name === 'asaas') { loadAsaasConfigIfNeeded(); }
  }
  tabs.forEach(t => t.addEventListener('click', function(){ activate(this.dataset.tab); }));
  // Garantir estado inicial
  const params = new URLSearchParams(location.search);
  const hashTab = (location.hash||'').replace('#','');
  const urlTab = params.get('tab') || (hashTab || '');
  const initial = urlTab && tabs.find(t => t.dataset.tab === urlTab) ? tabs.find(t => t.dataset.tab === urlTab) : tabs.find(t => t.classList.contains('active'));
  if (initial) activate(initial.dataset.tab);

  let asaasCfgLoaded = false;
  let asaasCounters = { customers: 0, payments: 0, links: 0 };
  function updateAsaasStats(partial) {
    if (partial && typeof partial === 'object') {
      asaasCounters = { ...asaasCounters, ...partial };
    }
    const cEl = document.getElementById('asaasStatsCustomers');
    const pEl = document.getElementById('asaasStatsPayments');
    const lEl = document.getElementById('asaasStatsLinks');
    if (cEl) cEl.textContent = String(asaasCounters.customers || 0);
    if (pEl) pEl.textContent = String(asaasCounters.payments || 0);
    if (lEl) lEl.textContent = String(asaasCounters.links || 0);
  }
  function setAsaasLastErr(msg) {
    const eEl = document.getElementById('asaasStatsLastErr');
    if (eEl) eEl.textContent = msg ? String(msg) : '—';
  }
  async function loadAsaasConfig(){
    try {
      const res = await apiRequest('/api/addons/asaas/config');
      if (!res || !res.ok) { document.getElementById('asaasStatusCfg').textContent = 'Falha ao carregar configuração.'; return; }
      const json = await res.json();
      const cfg = json.config || {};
      document.getElementById('asaasEnv').value = cfg.environment || 'production';
      document.getElementById('asaasBaseUrl').value = cfg.base_url || '';
      document.getElementById('asaasStatusCfg').textContent = (cfg.has_api_key ? 'API Key configurada.' : 'API Key não configurada.');
      asaasCfgLoaded = true;
    } catch (e) {
      document.getElementById('asaasStatusCfg').textContent = 'Erro: ' + String(e.message||e);
    }
  }
  function loadAsaasConfigIfNeeded(){ if (!asaasCfgLoaded) loadAsaasConfig(); }

  async function saveAsaasConfig(){
    const env = document.getElementById('asaasEnv').value;
    const baseUrl = document.getElementById('asaasBaseUrl').value.trim();
    const apiKey = document.getElementById('asaasApiKey').value.trim();
    document.getElementById('asaasSaveMsg').textContent = 'Salvando...';
    try {
      const res = await apiRequest('/api/addons/asaas/config', { method: 'POST', body: JSON.stringify({ environment: env, base_url: baseUrl, api_key: apiKey }) });
      if (res && res.ok) { document.getElementById('asaasSaveMsg').textContent = 'Configuração salva.'; loadAsaasConfig(); }
      else { const j = await res.json().catch(() => ({})); document.getElementById('asaasSaveMsg').textContent = 'Erro: ' + (j.error || (res && res.status)); }
    } catch (e) {
      document.getElementById('asaasSaveMsg').textContent = 'Erro: ' + String(e.message||e);
    }
  }

  async function listAsaasCustomers(){
    const q = document.getElementById('asaasSearchCustomer').value.trim();
    const el = document.getElementById('asaasResults');
    try {
      const res = await apiRequest('/api/addons/asaas/customers?q=' + encodeURIComponent(q));
      if (!res || !res.ok) { el.textContent = 'Erro: ' + (res && res.status); return; }
      const j = await res.json();
      el.textContent = JSON.stringify(j.data, null, 2);
      updateAsaasStats({ customers: Array.isArray(j.data) ? j.data.length : 0 });
      setAsaasLastErr('');
    } catch (e) { el.textContent = 'Erro: ' + String(e.message||e); setAsaasLastErr(e.message||String(e)); }
  }

  async function listAsaasPayments(){
    const el = document.getElementById('asaasResults');
    try {
      const res = await apiRequest('/api/addons/asaas/payments');
      if (!res || !res.ok) { el.textContent = 'Erro: ' + (res && res.status); return; }
      const j = await res.json();
      el.textContent = JSON.stringify(j.data, null, 2);
      updateAsaasStats({ payments: Array.isArray(j.data) ? j.data.length : 0 });
      setAsaasLastErr('');
    } catch (e) { el.textContent = 'Erro: ' + String(e.message||e); setAsaasLastErr(e.message||String(e)); }
  }

  async function generateAsaasLink(){
    const saleId = document.getElementById('asaasSaleId').value.trim();
    const clientId = parseInt(document.getElementById('asaasClientId').value || '0', 10);
    const amountCents = parseInt(document.getElementById('asaasAmountCents').value || '0', 10);
    const dueDate = document.getElementById('asaasDueDate').value;
    const billingType = document.getElementById('asaasBillingType').value;
    const msgEl = document.getElementById('asaasGenMsg');
    const outEl = document.getElementById('asaasGenResult');
    msgEl.textContent = 'Gerando...'; outEl.textContent='';
    try {
      const res = await apiRequest('/api/addons/asaas/payment-links', { method: 'POST', body: JSON.stringify({ sale_id: saleId, client_id: clientId, amount_cents: amountCents, due_date: dueDate, billing_type: billingType }) });
      if (!res || !res.ok) { const j = await res.json().catch(()=>({})); msgEl.textContent = 'Erro: ' + (j.error || (res && res.status)); return; }
      const j = await res.json();
      msgEl.textContent = 'Link criado.';
      const d = j.data || {};
      outEl.innerHTML = '<div>URL: <a href="' + (d.link_url || '#') + '" target="_blank">' + (d.link_url || '(sem URL)') + '</a></div>' +
        '<div>Status: ' + (d.status || '-') + '</div>' +
        '<div>Pagamento Asaas: ' + (d.asaas_payment_id || '-') + '</div>';
      updateAsaasStats({ links: (asaasCounters.links || 0) + 1 });
      setAsaasLastErr('');
    } catch (e) { msgEl.textContent = 'Erro: ' + String(e.message||e); setAsaasLastErr(e.message||String(e)); }
  }

  const btnSaveCfg = document.getElementById('btnSaveAsaasCfg'); if (btnSaveCfg) btnSaveCfg.addEventListener('click', saveAsaasConfig);
  const btnListCust = document.getElementById('asaasBtnListCustomers'); if (btnListCust) btnListCust.addEventListener('click', listAsaasCustomers);
  const btnListPays = document.getElementById('asaasBtnListPayments'); if (btnListPays) btnListPays.addEventListener('click', listAsaasPayments);
  const btnGen = document.getElementById('asaasBtnGenLink'); if (btnGen) btnGen.addEventListener('click', generateAsaasLink);

  // Auto-carregar config se a aba Asaas estiver ativa
  const asaasTab = document.getElementById('tab-asaas');
  if (asaasTab && asaasTab.classList.contains('active')) { loadAsaasConfigIfNeeded(); }
})();
</script>