<?php /* Painel de Integração Asaas */ ?>
<div class="page-header">
  <h1>Integração Asaas</h1>
  <p class="muted">Configure sua conexão com a API do Asaas e execute operações básicas.</p>
  <div id="status" class="muted"></div>
</div>

<section class="card">
  <h2 class="card-title">Credenciais</h2>
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
    <div>
      <label>Ambiente</label>
      <select id="env" class="input">
        <option value="production">Produção</option>
        <option value="sandbox">Sandbox</option>
      </select>
    </div>
    <div>
      <label>Base URL (opcional)</label>
      <input id="baseUrl" class="input" placeholder="https://www.asaas.com/api/v3" />
    </div>
    <div style="grid-column:1 / span 2">
      <label>API Key</label>
      <input id="apiKey" class="input" type="password" placeholder="Insira sua API Key do Asaas" />
      <small class="muted">Armazenada de forma criptografada por tenant.</small>
    </div>
    <div style="grid-column:1 / span 2">
      <label>Webhook Secret (opcional)</label>
      <input id="webhookSecret" class="input" type="password" placeholder="Segredo para validação de webhooks" />
    </div>
  </div>
  <div style="margin-top:1rem;display:flex;gap:0.5rem;">
    <button class="btn btn-primary" id="btnSave">Salvar Configuração</button>
    <span id="saveMsg" class="muted" aria-live="polite"></span>
  </div>
</section>

<section class="card">
  <h2 class="card-title">Operações</h2>
  <div style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
    <input id="searchCustomer" class="input" placeholder="Buscar cliente (nome)" style="width:320px;" />
    <button class="btn" id="btnListCustomers">Listar Clientes</button>
    <button class="btn" id="btnListPayments">Listar Pagamentos</button>
  </div>
  <div id="results" style="margin-top:1rem;max-height:300px;overflow:auto;"></div>
</section>

<section class="card">
  <h2 class="card-title">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="saleId" class="input" placeholder="Ex.: SO-2025-0001"/>
    </div>
    <div>
      <label>ID do Cliente (local)</label>
      <input id="clientId" class="input" type="number" min="1" placeholder="ID na tabela clients"/>
    </div>
    <div>
      <label>Valor (centavos)</label>
      <input id="amountCents" class="input" type="number" min="100" placeholder="Ex.: 12500 para R$125,00"/>
    </div>
    <div>
      <label>Vencimento</label>
      <input id="dueDate" class="input" type="date"/>
    </div>
    <div>
      <label>Tipo de Cobrança</label>
      <select id="billingType" 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="btnGenLink">Gerar Link</button>
    <span id="genMsg" class="muted" aria-live="polite"></span>
  </div>
  <div id="genResult" style="margin-top:0.5rem;"></div>
</section>

<script>
async function apiRequest(path, opts = {}) {
  const headers = Object.assign({ 'Content-Type': 'application/json' }, opts.headers || {});
  const res = await fetch(path, Object.assign({}, opts, { headers }));
  return res;
}

async function loadConfig() {
  const res = await apiRequest('/api/addons/asaas/config');
  if (!res.ok) { document.getElementById('status').textContent = 'Falha ao carregar configuração.'; return; }
  const json = await res.json();
  const cfg = json.config || {};
  document.getElementById('env').value = cfg.environment || 'production';
  document.getElementById('baseUrl').value = cfg.base_url || '';
  document.getElementById('status').textContent = (cfg.has_api_key ? 'API Key configurada.' : 'API Key não configurada.');
}

async function saveConfig() {
  const env = document.getElementById('env').value;
  const baseUrl = document.getElementById('baseUrl').value.trim();
  const apiKey = document.getElementById('apiKey').value.trim();
  const webhookSecret = document.getElementById('webhookSecret').value.trim();
  document.getElementById('saveMsg').textContent = 'Salvando...';
  const res = await apiRequest('/api/addons/asaas/config', { method: 'POST', body: JSON.stringify({ environment: env, base_url: baseUrl, api_key: apiKey, webhook_secret: webhookSecret }) });
  if (res.ok) { document.getElementById('saveMsg').textContent = 'Configuração salva.'; loadConfig(); }
  else { const j = await res.json().catch(() => ({})); document.getElementById('saveMsg').textContent = 'Erro: ' + (j.error || res.status); }
}

async function listCustomers() {
  const q = document.getElementById('searchCustomer').value.trim();
  const res = await apiRequest('/api/addons/asaas/customers?q=' + encodeURIComponent(q));
  const el = document.getElementById('results');
  if (!res.ok) { el.textContent = 'Erro: ' + res.status; return; }
  const j = await res.json();
  el.textContent = JSON.stringify(j.data, null, 2);
}

async function listPayments() {
  const res = await apiRequest('/api/addons/asaas/payments');
  const el = document.getElementById('results');
  if (!res.ok) { el.textContent = 'Erro: ' + res.status; return; }
  const j = await res.json();
  el.textContent = JSON.stringify(j.data, null, 2);
}

async function generateLink() {
  const saleId = document.getElementById('saleId').value.trim();
  const clientId = parseInt(document.getElementById('clientId').value, 10);
  const amountCents = parseInt(document.getElementById('amountCents').value, 10);
  const dueDate = document.getElementById('dueDate').value;
  const billingType = document.getElementById('billingType').value;
  document.getElementById('genMsg').textContent = 'Gerando...';
  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 })
  });
  const msgEl = document.getElementById('genMsg');
  const outEl = document.getElementById('genResult');
  if (!res.ok) {
    const j = await res.json().catch(() => ({}));
    msgEl.textContent = 'Erro: ' + (j.error || res.status);
    outEl.textContent = '';
    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>';
}

document.getElementById('btnSave').addEventListener('click', saveConfig);
document.getElementById('btnListCustomers').addEventListener('click', listCustomers);
document.getElementById('btnListPayments').addEventListener('click', listPayments);
document.getElementById('btnGenLink').addEventListener('click', generateLink);

loadConfig();
</script>