<?php
declare(strict_types=1);

require_once __DIR__ . "/../../includes/session_staff.php";
require_staff('balcao'); // usa seu login oficial

$PIX_API = APP_BASE . "/balcao/pix_api.php";
$contaId = (int)($_GET['conta_id'] ?? 0);
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Balcão • Receber via PIX</title>
<style>
  :root{
    --bg:#0f0f10; --card:rgba(32,32,34,.72); --line:rgba(255,255,255,.12);
    --text:#f3f3f3; --muted:rgba(243,243,243,.70);
    --accent:#60cdff; --ok:#22c55e; --warn:#f59e0b; --danger:#ff5a5f;
    --radius:18px; --shadow:0 18px 50px rgba(0,0,0,.45);
    --btn:rgba(255,255,255,.08);
  }
  body{ margin:0; font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial; background:var(--bg); color:var(--text); }
  .wrap{ max-width:980px; margin:0 auto; padding:18px; }
  .card{ background:var(--card); border:1px solid var(--line); border-radius:var(--radius); box-shadow:var(--shadow); padding:16px; }
  .row{ display:grid; grid-template-columns: 1fr 1fr; gap:14px; }
  @media (max-width:860px){ .row{ grid-template-columns:1fr; } }
  h1{ font-size:18px; margin:0 0 12px; }
  label{ font-size:12px; color:var(--muted); display:block; margin-bottom:6px; }
  input{ width:100%; padding:12px 12px; border-radius:14px; border:1px solid var(--line); background:rgba(18,18,20,.78); color:var(--text); outline:none; }
  .btn{ padding:12px 14px; border-radius:14px; border:1px solid var(--line); background:var(--btn); color:var(--text); cursor:pointer; font-weight:600; }
  .btnPrimary{ border-color: rgba(96,205,255,.45); }
  .btnOk{ border-color: rgba(34,197,94,.5); }
  .pill{ display:inline-block; padding:6px 10px; border-radius:999px; border:1px solid var(--line); background:rgba(255,255,255,.04); font-size:12px; }
  .big{ font-size:28px; font-weight:800; letter-spacing:.2px; }
  .qr{ display:flex; align-items:center; justify-content:center; min-height:280px; border-radius:16px; border:1px dashed rgba(255,255,255,.2); background:rgba(0,0,0,.18); }
  textarea{ width:100%; min-height:110px; padding:12px; border-radius:14px; border:1px solid var(--line); background:rgba(18,18,20,.78); color:var(--text); resize:vertical; }
  .actions{ display:flex; gap:10px; flex-wrap:wrap; margin-top:10px; }
  .hr{ height:1px; background:var(--line); margin:12px 0; }
  .toast{ position:fixed; left:50%; transform:translateX(-50%); bottom:18px; background:rgba(20,20,22,.92); border:1px solid var(--line); padding:12px 14px; border-radius:14px; box-shadow:var(--shadow); display:none; max-width:90vw; }
  .muted{ color:var(--muted); font-size:12px; }
  .mono{ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; }
</style>
</head>
<body>
<div class="wrap">
  <div class="card">
    <h1>Receber fatura via PIX</h1>

    <div class="row">
      <div>
        <label>Conta ID</label>
        <input id="conta_id" type="number" min="1" value="<?= (int)$contaId ?>">

        <div class="actions">
          <button class="btn btnPrimary" id="btnResumo">Carregar saldo</button>
          <button class="btn" id="btnGerar" disabled>Gerar PIX</button>
        </div>

        <div class="hr"></div>

        <div class="muted">Status</div>
        <div id="status" class="pill">Aguardando</div>

        <div style="margin-top:14px;">
          <div class="muted">Saldo a pagar</div>
          <div class="big">R$ <span id="saldo">0,00</span></div>
        </div>

        <div style="margin-top:14px;">
          <div class="muted">TXID</div>
          <div class="mono" id="txid">—</div>
        </div>

        <div style="margin-top:14px;">
          <label>Copia e cola</label>
          <textarea id="copia" class="mono" readonly placeholder="Gere o PIX para aparecer aqui..."></textarea>

          <div class="actions">
            <button class="btn" id="btnCopiar" disabled>Copiar</button>
            <button class="btn btnOk" id="btnConfirmar" disabled>Confirmar recebimento</button>
          </div>
        </div>
      </div>

      <div>
        <label>QR Code</label>
        <div class="qr" id="qrBox">
          <div class="muted">Gere o PIX para exibir o QR Code.</div>
        </div>

        <div class="muted" style="margin-top:10px;">
          Dica: cliente pode escanear com o app do banco. Se preferir, use o “copia e cola”.
        </div>
      </div>
    </div>
  </div>
</div>

<div class="toast" id="toast"></div>

<script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>

<script>
const PIX_API = "<?= $PIX_API ?>";
const el = (id)=>document.getElementById(id);
const fmtBR = (n)=> (Number(n)||0).toFixed(2).replace('.',',');

let pixAtual = null;

function toast(msg){
  const t = el('toast');
  t.textContent = msg;
  t.style.display = 'block';
  clearTimeout(window.__tto);
  window.__tto = setTimeout(()=> t.style.display='none', 2800);
}
function setStatus(txt){ el('status').textContent = txt; }

/**
 * ✅ Nunca trava: lê texto, tenta JSON; se vier HTML/erro mostra no console e na tela.
 */
async function fetchJSON(url, opts={}){
  const r = await fetch(url, { credentials:'same-origin', ...opts });
  const txt = await r.text();

  let j = null;
  try { j = JSON.parse(txt); }
  catch(e){
    console.log("Resposta NÃO-JSON da API:", txt);
    throw new Error("API não retornou JSON (veja o console).");
  }

  // Se a API devolver ok:false, repassa a msg
  return j;
}

function resetUI(){
  pixAtual = null;
  el('txid').textContent = '—';
  el('copia').value = '';
  el('btnCopiar').disabled = true;
  el('btnConfirmar').disabled = true;
  el('btnGerar').disabled = true;
  el('qrBox').innerHTML = '<div class="muted">Gere o PIX para exibir o QR Code.</div>';
}

async function carregarResumo(){
  const contaId = Number(el('conta_id').value||0);
  if (!contaId){ toast('Informe a Conta ID'); return; }

  setStatus('Carregando...');
  resetUI();

  try{
    const j = await fetchJSON(`${PIX_API}?action=conta_resumo&conta_id=${encodeURIComponent(contaId)}`);

    if (!j.ok){
      setStatus('Erro');
      toast(j.error || 'Falha');
      return;
    }

    el('saldo').textContent = fmtBR(j.saldo);

    if (Number(j.saldo) > 0){
      el('btnGerar').disabled = false;
      setStatus('Pronto para gerar PIX');
    } else {
      setStatus('Sem saldo a pagar');
    }
  }catch(err){
    console.error(err);
    setStatus('Erro');
    toast(err.message || 'Falha ao carregar');
  }
}

async function gerarPix(){
  const contaId = Number(el('conta_id').value||0);
  if (!contaId){ toast('Informe a Conta ID'); return; }

  setStatus('Gerando PIX...');

  try{
    const j = await fetchJSON(`${PIX_API}?action=pix_gerar`, {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ conta_id: contaId })
    });

    if (!j.ok){
      setStatus('Erro');
      toast(j.error || 'Falha');
      return;
    }

    pixAtual = j.pix;

    el('txid').textContent = pixAtual.txid;
    el('copia').value = pixAtual.copia_cola;
    el('btnCopiar').disabled = false;
    el('btnConfirmar').disabled = false;

    el('qrBox').innerHTML = `
  <img 
    src="https://api.qrserver.com/v1/create-qr-code/?size=260x260&data=${encodeURIComponent(pixAtual.copia_cola)}" 
    alt="QR Code PIX"
    style="max-width:260px;width:100%;border-radius:12px;background:#fff;padding:8px"
  >
`;



    setStatus('PIX pendente (aguardando pagamento)');
  }catch(err){
    console.error(err);
    setStatus('Erro');
    toast(err.message || 'Falha ao gerar PIX');
  }
}

async function copiar(){
  const txt = el('copia').value || '';
  if (!txt) return;
  try{
    await navigator.clipboard.writeText(txt);
    toast('Copiado!');
  }catch(e){
    el('copia').focus();
    el('copia').select();
    document.execCommand('copy');
    toast('Copiado!');
  }
}

async function confirmar(){
  if (!pixAtual?.id){
    toast('Gere o PIX primeiro');
    return;
  }
  if (!confirm('Confirmar que o PIX foi recebido?')) return;

  setStatus('Confirmando...');

  try{
    const j = await fetchJSON(`${PIX_API}?action=pix_confirmar`, {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ pix_id: pixAtual.id })
    });

    if (!j.ok){
      setStatus('Erro');
      toast(j.error || 'Falha');
      return;
    }

    toast('Pagamento confirmado!');
    await carregarResumo();
  }catch(err){
    console.error(err);
    setStatus('Erro');
    toast(err.message || 'Falha ao confirmar');
  }
}

el('btnResumo').addEventListener('click', carregarResumo);
el('btnGerar').addEventListener('click', gerarPix);
el('btnCopiar').addEventListener('click', copiar);
el('btnConfirmar').addEventListener('click', confirmar);

if (Number(el('conta_id').value||0) > 0) carregarResumo();
</script>
</body>
</html>
