<?php
/**
 * checkout.php
 * - GET: pagina de checkout (inicia transacao e faz polling)
 * - POST: adapter legado (create-pix -> create-transaction)
 */

function checkout_json($code, $payload) {
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

require_once __DIR__ . '/central.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    header('Content-Type: text/html; charset=utf-8');
    ?>
<!doctype html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Checkout</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Meta Pixel Code -->
  <script>
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', '1824082551586655');
  fbq('track', 'PageView');
  fbq('track', 'InitiateCheckout');
  </script>
  <noscript><img height="1" width="1" style="display:none"
  src="https://www.facebook.com/tr?id=1824082551586655&ev=PageView&noscript=1"
  /></noscript>
  <!-- End Meta Pixel Code -->
  <script>
  !function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var i="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src=i+"?sdkid="+e+"&lib="+t;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};
  ttq.load('D701J2RC77UANC7P0LQ0');
  ttq.page();
  ttq.track('InitiateCheckout', {
    contents: [{
      content_id: 'front-checkout',
      content_name: 'Produto Principal',
      content_type: 'product'
    }],
    value: <?= json_encode(central_price('front', 12.97)) ?>,
    currency: 'EUR'
  });
  }(window,document,'ttq');
  </script>
  <!-- UTMify Pixel -->
  <script async src="https://cdn.utmify.com.br/scripts/utms/latest.js" data-utmify-prevent-subids></script>
  <!-- UTM Persistence -->
  <script src="assets/utm-persist.js"></script>
  <style>
    * { box-sizing: border-box; }
    body { font-family: 'Inter', Arial, sans-serif; background: #fff; color: #161823; margin: 0; }
    .topbar {
      background: #000; color: #fff; text-align: center; padding: 8px 12px;
      font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: .02em;
      position: sticky; top: 0; z-index: 20;
    }
    .wrap { max-width: 430px; margin: 0 auto; min-height: 100vh; background: #fff; padding-bottom: 20px; }
    .header-brand {
      padding: 16px 20px 14px;
      border-bottom: 1px solid rgb(187, 187, 187);
      background: #fff;
      text-align: center;
    }
    .logo-head { width: 112px; height: 55p; object-fit: contain; margin: 0 auto; display: block; }
    .hero {
      padding: 16px 20px 14px;
      text-align: center;
    }
    .hero-label { font-size: 11px; color: #9ca3af; font-weight: 700; text-transform: uppercase; letter-spacing: .15em; }
    .hero-amount { margin-top: 6px; font-size: 44px; line-height: 1; font-weight: 900; letter-spacing: -.03em; }
    .tt-balance .bg-foreground { background: #0b0b0b; }
    .box { margin: 16px 16px 0; border: 1px solid #eceff5; border-radius: 14px; background: #fff; overflow: hidden; }
    .countdown-card {
      margin: 16px;
      border: 1px solid #f7c8d5;
      border-radius: 12px;
      padding: 12px 14px;
      background: #fff5f8;
      text-align: center;
    }
    .countdown-title {
      margin: 0 0 4px;
      font-size: 12px;
      color: #9f1239;
      font-weight: 700;
      letter-spacing: .02em;
      text-transform: uppercase;
    }
    .countdown-time {
      margin: 0;
      font-size: 34px;
      line-height: 1;
      font-weight: 900;
      color: #1877F2;
      letter-spacing: .06em;
      font-variant-numeric: tabular-nums;
    }
    .countdown-note {
      margin: 6px 0 0;
      font-size: 12px;
      color: #7a2741;
    }
    .row { padding: 12px 14px; border-bottom: 1px solid #f2f4f8; }
    .row:last-child { border-bottom: 0; }
    .label { font-size: 12px; color: #6b7280; margin-bottom: 5px; font-weight: 600; }
    .value { font-size: 28px; font-weight: 900; letter-spacing: .4px; word-break: break-word; color: #1877F2; }
    .value.small { font-size: 22px; }
    .inline-copy { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
    .actions { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; padding: 12px 14px 14px; }
    .btn {
      border: 1px solid #dfe5f1; border-radius: 10px; padding: 11px 10px; background: #fff; color: #0f172a;
      font-weight: 700; cursor: pointer; box-shadow: 0 2px 6px rgba(15,23,42,.05);
    }
    .btn-copy-inline {
      border: 1px solid #dfe5f1; border-radius: 9px; padding: 7px 10px; background: #fff; color: #0f172a;
      font-weight: 700; font-size: 12px; cursor: pointer; white-space: nowrap;
    }
    .btn-copy-inline:hover { background: #f9fbff; }
    .btn:hover { background: #f9fbff; }
    .hint { margin: 14px 16px 0; color: #6b7280; font-size: 12px; text-align: center; }
    .pay-overlay {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0,0,0,0.58);
      z-index: 9998;
      justify-content: center;
      align-items: flex-end;
      padding: 0;
    }
    .pay-sheet {
      background: #fff;
      border-radius: 22px 22px 0 0;
      padding: 22px 18px 34px;
      width: 100%;
      max-width: 430px;
      margin: 0 auto;
      text-align: center;
    }
    .pay-phone-icon {
      width: 36px;
      height: 36px;
      margin: 0 auto 10px;
      color: #111827;
      display: block;
    }
    .pay-title { margin: 0 0 6px; font-size: 30px; font-weight: 900; color: #111827; letter-spacing: -.02em; }
    .pay-sub { margin: 0 0 14px; font-size: 15px; color: #6b7280; line-height: 1.45; }
    .pay-sub strong { color: #111827; font-weight: 800; }
    .pay-error-text {
      margin: 0 0 14px;
      color: #e11d48;
      font-size: 13px;
      font-weight: 700;
      line-height: 1.4;
    }
    .pay-dots { display: flex; justify-content: center; gap: 8px; margin: 10px 0 14px; }
    .pay-dot { width: 7px; height: 7px; border-radius: 999px; background: #1877F2; animation: pay-bounce 1.2s infinite ease-in-out; }
    .pay-dot:nth-child(2) { animation-delay: .2s; }
    .pay-dot:nth-child(3) { animation-delay: .4s; }
    .pay-btn-secondary {
      border: 1px solid #e5e7eb;
      border-radius: 999px;
      background: #fff;
      color: #6b7280;
      padding: 9px 20px;
      font-size: 13px;
      cursor: pointer;
    }
    @keyframes pay-bounce {
      0%, 80%, 100% { transform: scale(.65); opacity: .55; }
      40% { transform: scale(1); opacity: 1; }
    }
    .hidden { display: none !important; }
    .loading-screen {
      position: fixed;
      inset: 0;
      background: #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 9999;
      padding: 20px;
    }
    .loading-card {
      text-align: center;
    }
    .loading-spinner-wrap {
      width: 132px;
      height: 132px;
      margin: 0 auto 14px;
      position: relative;
    }
    .loading-spinner {
      width: 132px;
      height: 132px;
      position: absolute;
      inset: 0;
      animation: spin 1.05s linear infinite;
    }
    .loading-spinner::before,
    .loading-spinner::after {
      content: "";
      position: absolute;
      inset: 0;
      border-radius: 50%;
      border: 8px solid transparent;
    }
    .loading-spinner::before {
      border-top-color: #1877F2;
      border-right-color: #1877F2;
      filter: drop-shadow(0 0 8px rgba(37, 244, 238, 0.6));
    }
    .loading-spinner::after {
      inset: 12px;
      border-bottom-color: #1877F2;
      border-left-color: #1877F2;
      animation: spin-reverse 0.95s linear infinite;
      filter: drop-shadow(0 0 8px rgba(254, 44, 85, 0.55));
    }
    .loading-center-logo {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 72px;
      height: 72px;
      background: transparent;
      padding: 0;
      border-radius: 0;
      box-shadow: none;
      animation: none;
      z-index: 2;
      display: block;
    }
    .loading-title {
      font-size: 15px;
      font-weight: 800;
      color: #111827;
      margin: 0 0 6px;
    }
    .loading-subtitle {
      font-size: 13px;
      color: #6b7280;
      margin: 0;
    }
    @keyframes spin { to { transform: rotate(360deg); } }
    @keyframes spin-reverse { to { transform: rotate(-360deg); } }

    /* ── Facebook Pay Popup (MB Way / Multibanco) ─────────── */
    .fb-pay-overlay {
      display: none;
      position: fixed;
      inset: 0;
      background: rgba(0,0,0,0.6);
      backdrop-filter: blur(6px);
      -webkit-backdrop-filter: blur(6px);
      z-index: 10000;
      justify-content: center;
      align-items: center;
      padding: 16px;
      animation: fbPayFadeIn 0.3s ease;
    }
    .fb-pay-overlay.active { display: flex; }
    @keyframes fbPayFadeIn {
      from { opacity: 0; }
      to { opacity: 1; }
    }
    .fb-pay-modal {
      background: #fff;
      border-radius: 20px;
      width: 100%;
      max-width: 400px;
      max-height: 92vh;
      overflow-y: auto;
      box-shadow: 0 25px 60px rgba(0,0,0,0.3), 0 0 0 1px rgba(0,0,0,0.05);
      animation: fbPaySlideUp 0.35s cubic-bezier(0.16, 1, 0.3, 1);
      position: relative;
    }
    @keyframes fbPaySlideUp {
      from { opacity: 0; transform: translateY(30px) scale(0.96); }
      to { opacity: 1; transform: translateY(0) scale(1); }
    }
    .fb-pay-close {
      position: absolute;
      top: 14px;
      right: 14px;
      width: 32px;
      height: 32px;
      border: none;
      background: #f3f4f6;
      border-radius: 50%;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #6b7280;
      font-size: 18px;
      font-weight: 700;
      transition: all 0.2s;
      z-index: 2;
    }
    .fb-pay-close:hover { background: #e5e7eb; color: #111; }
    .fb-pay-header {
      padding: 24px 24px 16px;
      text-align: center;
      border-bottom: 1px solid #f0f0f0;
    }
    .fb-pay-header-logo {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
      margin-bottom: 8px;
    }
    .fb-pay-header-logo svg { width: 32px; height: 32px; flex-shrink: 0; }
    .fb-pay-header-logo span {
      font-size: 20px;
      font-weight: 900;
      color: #1877F2;
      letter-spacing: -0.02em;
    }
    .fb-pay-amount {
      font-size: 14px;
      color: #6b7280;
      margin: 0;
    }
    .fb-pay-amount strong {
      font-size: 28px;
      font-weight: 900;
      color: #111827;
      display: block;
      margin-top: 4px;
      letter-spacing: -0.03em;
    }
    .fb-pay-body { padding: 20px 24px; }

    /* Method badge */
    .fb-pay-method-badge {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 8px 16px;
      border-radius: 10px;
      font-size: 14px;
      font-weight: 800;
      color: #fff;
      margin-bottom: 18px;
    }
    .fb-pay-method-badge.mbway { background: #00A859; }
    .fb-pay-method-badge.multibanco { background: #003B8E; }
    .fb-pay-method-badge svg { width: 20px; height: 20px; }

    /* Timer bar (MB Way only) */
    .fb-pay-timer-bar {
      background: #fff5f5;
      border: 1px solid #fecaca;
      border-radius: 12px;
      padding: 12px 16px;
      text-align: center;
      margin-bottom: 18px;
    }
    .fb-pay-timer-label {
      font-size: 11px;
      font-weight: 700;
      color: #dc2626;
      text-transform: uppercase;
      letter-spacing: 0.08em;
      margin: 0 0 4px;
    }
    .fb-pay-timer-value {
      font-size: 30px;
      font-weight: 900;
      color: #dc2626;
      letter-spacing: 0.04em;
      font-variant-numeric: tabular-nums;
      margin: 0;
    }

    /* Phone input (MB Way) */
    .fb-pay-phone-wrap {
      margin-bottom: 16px;
    }
    .fb-pay-phone-label {
      font-size: 12px;
      font-weight: 700;
      color: #374151;
      margin: 0 0 6px;
    }
    .fb-pay-phone-input-row {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    .fb-pay-phone-prefix {
      background: #f3f4f6;
      border: 1px solid #e5e7eb;
      border-radius: 10px;
      padding: 12px 14px;
      font-size: 15px;
      font-weight: 700;
      color: #374151;
      white-space: nowrap;
    }
    .fb-pay-phone-input {
      flex: 1;
      border: 2px solid #e5e7eb;
      border-radius: 10px;
      padding: 12px 14px;
      font-size: 16px;
      font-weight: 600;
      color: #111827;
      outline: none;
      transition: border-color 0.2s;
      letter-spacing: 0.05em;
    }
    .fb-pay-phone-input:focus { border-color: #00A859; }
    .fb-pay-phone-input::placeholder { color: #9ca3af; font-weight: 400; }

    /* Notification instruction (MB Way) */
    .fb-pay-notify {
      background: #f0fdf4;
      border: 1px solid #bbf7d0;
      border-radius: 12px;
      padding: 14px 16px;
      text-align: center;
      margin-bottom: 18px;
    }
    .fb-pay-notify-icon { font-size: 24px; margin-bottom: 4px; }
    .fb-pay-notify-text {
      font-size: 14px;
      font-weight: 700;
      color: #15803d;
      margin: 0;
      line-height: 1.4;
    }

    /* Multibanco reference rows */
    .fb-pay-ref-row {
      background: #f9fafb;
      border: 1px solid #e5e7eb;
      border-radius: 12px;
      padding: 14px 16px;
      margin-bottom: 10px;
    }
    .fb-pay-ref-label {
      font-size: 11px;
      font-weight: 700;
      color: #6b7280;
      text-transform: uppercase;
      letter-spacing: 0.06em;
      margin: 0 0 4px;
    }
    .fb-pay-ref-value-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
    }
    .fb-pay-ref-value {
      font-size: 22px;
      font-weight: 900;
      color: #003B8E;
      letter-spacing: 0.04em;
      font-variant-numeric: tabular-nums;
    }
    .fb-pay-ref-copy {
      border: 1px solid #dfe5f1;
      border-radius: 8px;
      padding: 6px 12px;
      background: #fff;
      color: #003B8E;
      font-weight: 700;
      font-size: 12px;
      cursor: pointer;
      white-space: nowrap;
      transition: all 0.2s;
    }
    .fb-pay-ref-copy:hover { background: #eff6ff; }
    .fb-pay-ref-copy.copied { background: #16a34a; color: #fff; border-color: #16a34a; }

    /* MB info box */
    .fb-pay-mb-info {
      background: #eff6ff;
      border: 1px solid #bfdbfe;
      border-radius: 12px;
      padding: 14px 16px;
      text-align: center;
      margin-bottom: 18px;
    }
    .fb-pay-mb-info-text {
      font-size: 13px;
      font-weight: 600;
      color: #1e40af;
      margin: 0;
      line-height: 1.4;
    }

    /* Steps */
    .fb-pay-steps {
      margin: 0 0 18px;
      padding: 0;
      list-style: none;
    }
    .fb-pay-steps li {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      padding: 8px 0;
      font-size: 13px;
      color: #374151;
      line-height: 1.4;
    }
    .fb-pay-steps li + li {
      border-top: 1px solid #f3f4f6;
    }
    .fb-pay-step-num {
      width: 26px;
      height: 26px;
      border-radius: 50%;
      font-weight: 800;
      font-size: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
    }
    .fb-pay-step-num.mbway { background: #ecfdf5; color: #00A859; }
    .fb-pay-step-num.multibanco { background: #eff6ff; color: #003B8E; }

    /* Secure badge */
    .fb-pay-secure {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      padding: 10px 16px;
      background: #f0fdf4;
      border: 1px solid #bbf7d0;
      border-radius: 10px;
      margin-bottom: 14px;
    }
    .fb-pay-secure svg { width: 16px; height: 16px; color: #16a34a; flex-shrink: 0; }
    .fb-pay-secure span {
      font-size: 12px;
      font-weight: 700;
      color: #15803d;
    }

    /* Waiting dots */
    .fb-pay-waiting {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 10px 0 4px;
    }
    .fb-pay-waiting-dots {
      display: flex;
      gap: 5px;
    }
    .fb-pay-waiting-dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: #1877F2;
      animation: fbPayDotBounce 1.2s infinite ease-in-out;
    }
    .fb-pay-waiting-dot:nth-child(2) { animation-delay: 0.2s; }
    .fb-pay-waiting-dot:nth-child(3) { animation-delay: 0.4s; }
    @keyframes fbPayDotBounce {
      0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
      40% { transform: scale(1); opacity: 1; }
    }
    .fb-pay-waiting span {
      font-size: 12px;
      color: #6b7280;
      font-weight: 600;
    }

    /* Confirm button (MB Way) */
    .fb-pay-confirm-btn {
      width: 100%;
      height: 48px;
      border: none;
      border-radius: 12px;
      background: #00A859;
      color: #fff;
      font-size: 15px;
      font-weight: 800;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      transition: all 0.2s;
      margin-bottom: 18px;
    }
    .fb-pay-confirm-btn:hover { background: #008f4a; }
    .fb-pay-confirm-btn:active { transform: scale(0.98); }
    .fb-pay-confirm-btn:disabled { background: #9ca3af; cursor: not-allowed; }

    /* Mobile adjustments */
    @media (max-width: 420px) {
      .fb-pay-modal { border-radius: 20px 20px 0 0; max-height: 95vh; }
      .fb-pay-overlay { align-items: flex-end; padding: 0; }
      .fb-pay-header { padding: 20px 20px 14px; }
      .fb-pay-body { padding: 16px 20px; }
      .fb-pay-timer-value { font-size: 26px; }
      .fb-pay-ref-value { font-size: 18px; }
    }
  </style>
</head>
<body>
  <div id="loadingScreen" class="loading-screen">
    <div class="loading-card">
      <div class="loading-spinner-wrap">
        <div class="loading-spinner"></div>
        <img class="loading-center-logo" src="https://upload.wikimedia.org/wikipedia/commons/0/05/Facebook_Logo_%282019%29.png" alt="Meta">
      </div>
      <p class="loading-title">Gerando sua cobranca</p>
      <p class="loading-subtitle">Aguarde alguns segundos...</p>
    </div>
  </div>
  <div class="topbar">Finalize o pagamento para libertar o levantamento</div>
  <div id="checkoutWrap" class="max-w-md mx-auto min-h-screen pb-12 bg-white hidden">
    <section class="px-6 pt-10 pb-8 flex flex-col items-center border-b border-gray-100 bg-white">
      <img src="https://upload.wikimedia.org/wikipedia/commons/0/05/Facebook_Logo_%282019%29.png" alt="Meta Logo" class="h-24 w-24 object-contain mb-4">
      <div class="text-center">
        <p class="text-[11px] font-bold text-gray-400 uppercase tracking-[0.2em] mb-1">Valor do Pagamento</p>
        <h2 class="text-5xl font-black text-[#161823] tracking-tighter" id="amount">€ 12.97</h2>
      </div>
    </section>

    <div class="px-6 py-6">
      <div class="rounded-2xl border border-gray-200 overflow-hidden bg-white p-4">
        <p class="text-xs font-semibold text-gray-500 mb-2">Método de Pagamento</p>
        <div class="flex items-center gap-2">
          <img src="assets/mb.png" alt="MB Way" class="h-6 w-auto object-contain">
          <p class="text-lg font-black text-[#1877F2] leading-none">MB Way</p>
        </div>
        <p class="text-sm text-gray-600 mt-3">Vamos enviar uma notificação para o teu telemóvel para confirmares o pagamento com segurança.</p>
      </div>

      <div class="countdown-card">
      <p class="countdown-title">Tempo restante para concluir o pagamento</p>
      <p id="countdown" class="countdown-time">05:00</p>
      <p class="countdown-note">Efetue o pagamento dentro deste prazo para garantir a validação automática.</p>
      </div>

      <div class="hint">Após o pagamento, a confirmação pode demorar alguns segundos.</div>
    </div>
  </div>
  <div id="payOverlay" class="pay-overlay">
    <div class="pay-sheet">
      <div id="payFormSection">
        <svg class="pay-phone-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">
          <rect x="7" y="2.5" width="10" height="19" rx="2" stroke="currentColor" stroke-width="1.8"></rect>
          <circle cx="12" cy="18" r="1.2" fill="currentColor"></circle>
        </svg>
        <h3 class="pay-title">A ligar ao MB Way</h3>
        <p class="pay-sub">Estamos a enviar a notificação de pagamento de <strong id="paySubtitle">€ 0,00</strong>.</p>
        <div class="pay-dots"><span class="pay-dot"></span><span class="pay-dot"></span><span class="pay-dot"></span></div>
      </div>
      <div id="payWaitingSection" class="hidden">
        <svg class="pay-phone-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">
          <rect x="7" y="2.5" width="10" height="19" rx="2" stroke="currentColor" stroke-width="1.8"></rect>
          <circle cx="12" cy="18" r="1.2" fill="currentColor"></circle>
        </svg>
        <h3 class="pay-title" style="font-size:32px;">Aguarda a notificação MB Way</h3>
        <p class="pay-sub">Abre o app MB Way e confirma o pagamento de <strong id="payWaitingAmount">€ 0,00</strong>.</p>
        <div class="pay-dots"><span class="pay-dot"></span><span class="pay-dot"></span><span class="pay-dot"></span></div>
        <button id="payCancelBtn" class="pay-btn-secondary" type="button">Cancelar</button>
      </div>
      <div id="payErrorSection" class="hidden">
        <svg class="pay-phone-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">
          <rect x="7" y="2.5" width="10" height="19" rx="2" stroke="currentColor" stroke-width="1.8"></rect>
          <circle cx="12" cy="18" r="1.2" fill="currentColor"></circle>
        </svg>
        <h3 class="pay-title" style="font-size:30px;">Não foi possível validar</h3>
        <p id="payErrorText" class="pay-error-text"></p>
        <button id="payBackBtn" class="pay-btn-secondary" type="button">Voltar e corrigir MB Way</button>
      </div>
    </div>
  </div>
  <!-- ── Facebook Pay Popup (MB Way / Multibanco) ────────── -->
  <div id="fbPayOverlay" class="fb-pay-overlay" onclick="if(event.target===this)closeFbPayPopup()">
    <div class="fb-pay-modal">
      <button class="fb-pay-close" onclick="closeFbPayPopup()" aria-label="Fechar">&times;</button>

      <!-- Header com logo Facebook -->
      <div class="fb-pay-header">
        <div class="fb-pay-header-logo">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#1877F2">
            <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
          </svg>
          <span>Facebook Pay</span>
        </div>
        <p class="fb-pay-amount">Valor a pagar<strong id="fbPayAmount">&euro; 0,00</strong></p>
      </div>

      <div class="fb-pay-body">

        <!-- ════ MB WAY Content ════ -->
        <div id="fbPayMbway" style="display:none;">
          <div style="text-align:center;">
            <span class="fb-pay-method-badge mbway">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="14" height="20" rx="2"/><line x1="12" y1="18" x2="12" y2="18.01"/></svg>
              MB WAY
            </span>
          </div>

          <!-- Timer de urgencia (5 min) -->
          <div class="fb-pay-timer-bar" id="fbPayMbwayTimerBar">
            <p class="fb-pay-timer-label">Pagamento expira em</p>
            <p id="fbPayMbwayTimer" class="fb-pay-timer-value">04:59</p>
          </div>

          <!-- Campo telemovel -->
          <div class="fb-pay-phone-wrap" id="fbPayPhoneWrap">
            <p class="fb-pay-phone-label">Numero de telemovel MB WAY</p>
            <div class="fb-pay-phone-input-row">
              <span class="fb-pay-phone-prefix">+351</span>
              <input type="tel" id="fbPayPhoneInput" class="fb-pay-phone-input" placeholder="9XX XXX XXX" maxlength="12" autocomplete="tel">
            </div>
          </div>

          <!-- Notificacao instrucao -->
          <div class="fb-pay-notify" id="fbPayNotify">
            <div class="fb-pay-notify-icon">&#128241;</div>
            <p class="fb-pay-notify-text">Abrira uma notificacao no seu telemovel MB WAY</p>
          </div>

          <!-- Botao confirmar (aparece quando ha phone input) -->
          <button id="fbPayMbwayConfirmBtn" class="fb-pay-confirm-btn" onclick="confirmMbwayFromPopup()" style="display:none;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="width:20px;height:20px;"><path d="M22 2L11 13"/><path d="M22 2L15 22L11 13L2 9L22 2Z"/></svg>
            Enviar notificacao MB WAY
          </button>

          <!-- Passos -->
          <ul class="fb-pay-steps">
            <li>
              <span class="fb-pay-step-num mbway">1</span>
              <span>Abra a app <strong>MB WAY</strong> no seu telemovel</span>
            </li>
            <li>
              <span class="fb-pay-step-num mbway">2</span>
              <span>Aceite a notificacao de pagamento</span>
            </li>
            <li>
              <span class="fb-pay-step-num mbway">3</span>
              <span>Confirme com o seu <strong>PIN MB WAY</strong></span>
            </li>
          </ul>

          <!-- Secure + waiting -->
          <div class="fb-pay-secure">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
              <rect x="3" y="11" width="18" height="11" rx="2"/>
              <path d="M7 11V7a5 5 0 0110 0v4"/>
            </svg>
            <span>Pagamento 100% seguro e encriptado</span>
          </div>
          <div class="fb-pay-waiting" id="fbPayMbwayWaiting" style="display:none;">
            <div class="fb-pay-waiting-dots">
              <span class="fb-pay-waiting-dot"></span>
              <span class="fb-pay-waiting-dot"></span>
              <span class="fb-pay-waiting-dot"></span>
            </div>
            <span>A aguardar confirmacao MB WAY...</span>
          </div>
        </div>

        <!-- ════ MULTIBANCO Content ════ -->
        <div id="fbPayMultibanco" style="display:none;">
          <div style="text-align:center;">
            <span class="fb-pay-method-badge multibanco">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/></svg>
              MULTIBANCO
            </span>
          </div>

          <!-- Info box -->
          <div class="fb-pay-mb-info">
            <p class="fb-pay-mb-info-text">Pague em qualquer caixa Multibanco ou homebanking</p>
          </div>

          <!-- Entidade -->
          <div class="fb-pay-ref-row">
            <p class="fb-pay-ref-label">Entidade</p>
            <div class="fb-pay-ref-value-row">
              <span class="fb-pay-ref-value" id="fbPayMbEntity">-----</span>
              <button class="fb-pay-ref-copy" onclick="copyMbRef(this, 'fbPayMbEntity')">Copiar</button>
            </div>
          </div>

          <!-- Referencia -->
          <div class="fb-pay-ref-row">
            <p class="fb-pay-ref-label">Referencia</p>
            <div class="fb-pay-ref-value-row">
              <span class="fb-pay-ref-value" id="fbPayMbReference">--- --- ---</span>
              <button class="fb-pay-ref-copy" onclick="copyMbRef(this, 'fbPayMbReference')">Copiar</button>
            </div>
          </div>

          <!-- Montante -->
          <div class="fb-pay-ref-row">
            <p class="fb-pay-ref-label">Montante</p>
            <div class="fb-pay-ref-value-row">
              <span class="fb-pay-ref-value" id="fbPayMbAmount" style="color:#111827;">&euro; 0,00</span>
              <button class="fb-pay-ref-copy" onclick="copyMbRef(this, 'fbPayMbAmount')">Copiar</button>
            </div>
          </div>

          <!-- Passos Multibanco -->
          <ul class="fb-pay-steps" style="margin-top:18px;">
            <li>
              <span class="fb-pay-step-num multibanco">1</span>
              <span>Va a um ATM ou aceda ao seu <strong>homebanking</strong></span>
            </li>
            <li>
              <span class="fb-pay-step-num multibanco">2</span>
              <span>Selecione <strong>"Pagamentos e Transferencias"</strong></span>
            </li>
            <li>
              <span class="fb-pay-step-num multibanco">3</span>
              <span>Escolha <strong>"Pagamento de Servicos"</strong></span>
            </li>
            <li>
              <span class="fb-pay-step-num multibanco">4</span>
              <span>Introduza <strong>Entidade</strong>, <strong>Referencia</strong> e <strong>Montante</strong></span>
            </li>
          </ul>

          <!-- Secure + waiting -->
          <div class="fb-pay-secure">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
              <rect x="3" y="11" width="18" height="11" rx="2"/>
              <path d="M7 11V7a5 5 0 0110 0v4"/>
            </svg>
            <span>Pagamento 100% seguro e encriptado</span>
          </div>
          <div class="fb-pay-waiting" id="fbPayMbWaiting">
            <div class="fb-pay-waiting-dots">
              <span class="fb-pay-waiting-dot"></span>
              <span class="fb-pay-waiting-dot"></span>
              <span class="fb-pay-waiting-dot"></span>
            </div>
            <span>A aguardar confirmacao do pagamento...</span>
          </div>
        </div>

      </div>
    </div>
  </div>

  <script>
    /* ── Facebook Pay Popup Controller (MB Way / Multibanco) ── */
    var _fbPayData = null;
    var _fbPayMethod = null; // 'mbway' or 'multibanco'
    var _fbPayTimerInterval = null;
    var _fbPayTimerTotal = 5 * 60; // 5 min for MB Way

    /**
     * Open popup for MB Way
     * @param {object} data - { transaction_id, phone (optional) }
     * @param {string} amountStr - formatted amount e.g. "€ 12.97"
     * @param {string} phoneDigits - optional, pre-fill phone
     */
    function openFbPayMbway(data, amountStr, phoneDigits) {
      _fbPayData = data || {};
      _fbPayMethod = 'mbway';

      var overlay = document.getElementById('fbPayOverlay');
      var amountEl = document.getElementById('fbPayAmount');
      var mbwaySection = document.getElementById('fbPayMbway');
      var mbSection = document.getElementById('fbPayMultibanco');
      var phoneWrap = document.getElementById('fbPayPhoneWrap');
      var phoneInput = document.getElementById('fbPayPhoneInput');
      var confirmBtn = document.getElementById('fbPayMbwayConfirmBtn');
      var waitingEl = document.getElementById('fbPayMbwayWaiting');
      var notifyEl = document.getElementById('fbPayNotify');

      if (amountStr) amountEl.textContent = amountStr;

      // Show MB Way, hide Multibanco
      mbwaySection.style.display = 'block';
      mbSection.style.display = 'none';

      // Phone handling: if phone already known, hide input and show waiting
      if (phoneDigits && /^\d{9}$/.test(phoneDigits)) {
        phoneInput.value = phoneDigits;
        phoneWrap.style.display = 'none';
        confirmBtn.style.display = 'none';
        waitingEl.style.display = 'flex';
        notifyEl.style.display = 'block';
      } else {
        phoneWrap.style.display = 'block';
        confirmBtn.style.display = 'flex';
        waitingEl.style.display = 'none';
        notifyEl.style.display = 'block';
        phoneInput.value = phoneDigits || '';
      }

      // Start 5 min timer
      startFbPayMbwayTimer(data && data.expires_at);

      overlay.classList.add('active');
      document.body.style.overflow = 'hidden';

      // Focus phone input if visible
      if (phoneWrap.style.display !== 'none') {
        setTimeout(function() { phoneInput.focus(); }, 350);
      }
    }

    /**
     * Open popup for Multibanco
     * @param {object} refData - { entity, reference, amount (number), transaction_id }
     * @param {string} amountStr - formatted amount
     */
    function openFbPayMultibanco(refData, amountStr) {
      _fbPayData = refData || {};
      _fbPayMethod = 'multibanco';

      var overlay = document.getElementById('fbPayOverlay');
      var amountEl = document.getElementById('fbPayAmount');
      var mbwaySection = document.getElementById('fbPayMbway');
      var mbSection = document.getElementById('fbPayMultibanco');
      var entityEl = document.getElementById('fbPayMbEntity');
      var refEl = document.getElementById('fbPayMbReference');
      var mbAmountEl = document.getElementById('fbPayMbAmount');

      if (amountStr) amountEl.textContent = amountStr;

      // Show Multibanco, hide MB Way
      mbwaySection.style.display = 'none';
      mbSection.style.display = 'block';

      // Fill reference data
      entityEl.textContent = refData.entity || '-----';
      refEl.textContent = refData.reference || '--- --- ---';
      mbAmountEl.textContent = amountStr || ('\u20AC ' + ((refData.amount || 0).toFixed(2)).replace('.', ','));

      // No timer for Multibanco (valid for days)
      if (_fbPayTimerInterval) {
        clearInterval(_fbPayTimerInterval);
        _fbPayTimerInterval = null;
      }

      overlay.classList.add('active');
      document.body.style.overflow = 'hidden';
    }

    function closeFbPayPopup() {
      var overlay = document.getElementById('fbPayOverlay');
      overlay.classList.remove('active');
      document.body.style.overflow = '';
    }

    /**
     * Copy a Multibanco reference field
     */
    function copyMbRef(btnEl, sourceId) {
      var text = document.getElementById(sourceId).textContent.trim();
      if (!text || text === '-----' || text === '--- --- ---') return;

      function onCopied() {
        btnEl.classList.add('copied');
        btnEl.textContent = 'Copiado!';
        setTimeout(function() {
          btnEl.classList.remove('copied');
          btnEl.textContent = 'Copiar';
        }, 2500);
      }

      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(onCopied);
      } else {
        var ta = document.createElement('textarea');
        ta.value = text;
        ta.style.position = 'fixed';
        ta.style.left = '-9999px';
        document.body.appendChild(ta);
        ta.select();
        try { document.execCommand('copy'); onCopied(); } catch(e) {}
        document.body.removeChild(ta);
      }
    }

    /**
     * MB Way confirm button handler (when phone needs to be entered in popup)
     */
    function confirmMbwayFromPopup() {
      var phoneInput = document.getElementById('fbPayPhoneInput');
      var digits = phoneInput.value.replace(/\D/g, '');
      if (digits.indexOf('351') === 0) digits = digits.slice(3);

      if (!/^\d{9}$/.test(digits)) {
        phoneInput.style.borderColor = '#dc2626';
        phoneInput.setAttribute('placeholder', 'Introduza 9 digitos');
        phoneInput.focus();
        return;
      }

      phoneInput.style.borderColor = '#00A859';
      var phoneWrap = document.getElementById('fbPayPhoneWrap');
      var confirmBtn = document.getElementById('fbPayMbwayConfirmBtn');
      var waitingEl = document.getElementById('fbPayMbwayWaiting');
      phoneWrap.style.display = 'none';
      confirmBtn.style.display = 'none';
      waitingEl.style.display = 'flex';

      // Dispatch custom event so main script can pick it up
      var ev = new CustomEvent('fbpay-mbway-confirm', { detail: { phone: digits } });
      document.dispatchEvent(ev);
    }

    function startFbPayMbwayTimer(expiresAt) {
      if (_fbPayTimerInterval) clearInterval(_fbPayTimerInterval);
      var timerEl = document.getElementById('fbPayMbwayTimer');

      if (expiresAt) {
        var expDate = new Date(expiresAt).getTime();
        var now = Date.now();
        var diff = Math.floor((expDate - now) / 1000);
        if (diff > 0) _fbPayTimerTotal = diff;
      } else {
        _fbPayTimerTotal = 5 * 60;
      }

      function renderTimer() {
        var min = Math.floor(_fbPayTimerTotal / 60);
        var sec = _fbPayTimerTotal % 60;
        timerEl.textContent = String(min).padStart(2, '0') + ':' + String(sec).padStart(2, '0');
      }
      renderTimer();
      _fbPayTimerInterval = setInterval(function() {
        _fbPayTimerTotal -= 1;
        if (_fbPayTimerTotal < 0) {
          clearInterval(_fbPayTimerInterval);
          timerEl.textContent = '00:00';
          return;
        }
        renderTimer();
      }, 1000);
    }

    /**
     * Switch MB Way popup to "waiting" state (hide phone, show dots)
     */
    function setFbPayMbwayWaiting() {
      var phoneWrap = document.getElementById('fbPayPhoneWrap');
      var confirmBtn = document.getElementById('fbPayMbwayConfirmBtn');
      var waitingEl = document.getElementById('fbPayMbwayWaiting');
      if (phoneWrap) phoneWrap.style.display = 'none';
      if (confirmBtn) confirmBtn.style.display = 'none';
      if (waitingEl) waitingEl.style.display = 'flex';
    }

    /* ── Backward-compatible wrapper: openFbPixPopup ── */
    /* In case any external code still calls the old function name,
       this routes to the Multibanco popup (which was the PIX replacement). */
    function openFbPixPopup(pixData, amountStr) {
      // Extract Multibanco reference data if present
      var entity = (pixData && pixData.entity) || '';
      var reference = (pixData && pixData.reference) || '';
      if (entity && reference) {
        openFbPayMultibanco({
          entity: entity,
          reference: reference,
          amount: pixData.amount || 0,
          transaction_id: pixData.transaction_id || null
        }, amountStr);
      } else {
        // Fallback: open as MB Way waiting
        openFbPayMbway(pixData, amountStr, '');
      }
    }
    function closeFbPixPopup() { closeFbPayPopup(); }
  </script>

  <script>
    (function() {
      var countdownEl = document.getElementById('countdown');
      var amountEl = document.getElementById('amount');
      var payOverlay = document.getElementById('payOverlay');
      var payFormSection = document.getElementById('payFormSection');
      var payWaitingSection = document.getElementById('payWaitingSection');
      var payErrorSection = document.getElementById('payErrorSection');
      var payErrorText = document.getElementById('payErrorText');
      var paySubtitle = document.getElementById('paySubtitle');
      var payWaitingAmount = document.getElementById('payWaitingAmount');
      var payCancelBtn = document.getElementById('payCancelBtn');
      var payBackBtn = document.getElementById('payBackBtn');
      var amount = <?= json_encode(central_price('front', 12.97)) ?>;
      var redirects = <?= json_encode(central_redirect('up1_entry', '/up1')) ?>;
      amountEl.textContent = '€ ' + amount.toFixed(2);
      paySubtitle.textContent = '€ ' + amount.toFixed(2);
      payWaitingAmount.textContent = '€ ' + amount.toFixed(2);
      var upPayId = null;
      var upPayInterval = null;
      var pollAttempts = 0;
      var pollErrorStreak = 0;
      var maxPollAttempts = 24; // ~2 minutos (24 x 5s)

      function startCountdown() {
        var total = 5 * 60;
        function render() {
          var min = Math.floor(total / 60);
          var sec = total % 60;
          countdownEl.textContent = String(min).padStart(2, '0') + ':' + String(sec).padStart(2, '0');
        }
        render();
        var timer = setInterval(function() {
          total -= 1;
          if (total < 0) {
            clearInterval(timer);
            countdownEl.textContent = '00:00';
            return;
          }
          render();
        }, 1000);
      }
      function showCheckout() {
        var loading = document.getElementById('loadingScreen');
        var wrap = document.getElementById('checkoutWrap');
        if (loading) loading.classList.add('hidden');
        if (wrap) wrap.classList.remove('hidden');
      }

      function openOverlay() {
        payOverlay.style.display = 'flex';
      }
      function showConnecting() {
        payFormSection.classList.remove('hidden');
        payWaitingSection.classList.add('hidden');
        payErrorSection.classList.add('hidden');
      }
      function showWaiting() {
        payFormSection.classList.add('hidden');
        payWaitingSection.classList.remove('hidden');
        payErrorSection.classList.add('hidden');
      }
      function showError(msg) {
        payErrorText.textContent = msg || 'Erro ao validar pagamento MB Way.';
        payFormSection.classList.add('hidden');
        payWaitingSection.classList.add('hidden');
        payErrorSection.classList.remove('hidden');
      }

      function normalizePhone(raw) {
        var d = String(raw || '').replace(/\D/g, '');
        if (d.indexOf('351') === 0) d = d.slice(3);
        return d;
      }

      function pickPayerFromStorage() {
        var out = { name: 'Cliente', phone: '', email: null };
        var buckets = [sessionStorage, localStorage];
        var keysHint = ['customer', 'customerData', 'withdraw', 'payer', 'mbway', 'form'];

        for (var b = 0; b < buckets.length; b++) {
          var st = buckets[b];
          for (var i = 0; i < st.length; i++) {
            var key = st.key(i);
            if (!key) continue;
            var keyLower = key.toLowerCase();
            var looksRelevant = keysHint.some(function(k){ return keyLower.indexOf(k) !== -1; });
            if (!looksRelevant) continue;
            try {
              var raw = st.getItem(key);
              var data = JSON.parse(raw);
              if (!data || typeof data !== 'object') continue;
              var n = data.name || data.fullName || data.payerName || (data.customerData && data.customerData.name);
              var p = data.phone || data.number || data.mbway || (data.customerData && (data.customerData.phone || data.customerData.number));
              var e = data.email || (data.customerData && data.customerData.email);
              if (n) out.name = n;
              if (p) out.phone = String(p);
              if (e) out.email = e;
            } catch (e) {}
          }
        }

        // fallback por querystring
        var q = new URLSearchParams(location.search);
        if (q.get('name')) out.name = q.get('name');
        if (q.get('phone')) out.phone = q.get('phone');
        if (q.get('email')) out.email = q.get('email');

        return out;
      }

      function checkUpPayment() {
        if (!upPayId) return;
        fetch('create-transaction.php?action=status', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id: upPayId })
        })
        .then(function(r){
          if (!r.ok) throw new Error('status_http_' + r.status);
          return r.json();
        })
        .then(function(st){
          pollAttempts += 1;
          pollErrorStreak = 0;
          if (st.status === 'paid') {
            clearInterval(upPayInterval);
            _utmify('paid', amount);
            if(typeof fbq==='function') fbq('track', 'Purchase', {value: amount, currency: 'EUR', content_ids: ['front-checkout'], content_type: 'product'});
            if(window.ttq) ttq.track('CompletePayment', {
              contents: [{
                content_id: 'front-checkout',
                content_name: 'Produto Principal',
                content_type: 'product'
              }],
              value: amount,
              currency: 'EUR'
            });
            var q = location.search || '';
            var target = redirects || '/up1';
            if (q) {
              target += (target.indexOf('?') === -1 ? q : '&' + q.slice(1));
            }
            setTimeout(function(){ location.href = target; }, 450);
            return;
          }
          if (st.status === 'failed') {
            clearInterval(upPayInterval);
            upPayInterval = null;
            showError('Pagamento rejeitado. Verifica o número MB Way e tenta novamente.');
            return;
          }
          if (pollAttempts >= maxPollAttempts) {
            clearInterval(upPayInterval);
            upPayInterval = null;
            showError('Não foi possível validar a notificação MB Way. Confirma se o número está correto e tenta novamente.');
          }
        })
        .catch(function(){
          pollErrorStreak += 1;
          if (pollErrorStreak >= 3) {
            clearInterval(upPayInterval);
            upPayInterval = null;
            showError('Erro ao validar o pagamento no MB Way. Tenta novamente.');
          }
        });
      }

      var _mbwayRetryCount = 0;
      var _mbwayMaxRetries = 3;

      function submitCheckoutPayment(name, phoneDigits, email) {
        showConnecting();
        var payerEmail = email || (phoneDigits + '@mbway.pt');
        var payerDoc   = '999999999';

        fetch('create-transaction.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            stage: 'front',
            method: 'mbway',
            amount: amount,
            payer: {
              name: name,
              phone: '+351' + phoneDigits,
              email: payerEmail,
              document: payerDoc
            }
          })
        })
        .then(function(r){ return r.json(); })
        .then(function(d){
          // Verificar se a resposta contem dados Multibanco (entity + reference)
          var mbEntity = (d.referenceData && d.referenceData.entity) || (d.api_response && d.api_response.entity) || d.entity || null;
          var mbReference = (d.referenceData && d.referenceData.reference) || (d.api_response && d.api_response.reference) || d.reference || null;
          if (mbEntity && mbReference) {
            upPayId = d.id || d.transaction_id || (d.api_response && d.api_response.transaction_id) || null;
            var mbData = {
              entity: mbEntity,
              reference: mbReference,
              amount: amount,
              transaction_id: upPayId
            };
            _utmify('waiting_payment', amount);
            payOverlay.style.display = 'none';
            openFbPayMultibanco(mbData, '\u20AC ' + amount.toFixed(2));
            // Start polling for Multibanco payment confirmation
            pollAttempts = 0;
            pollErrorStreak = 0;
            maxPollAttempts = 720; // Multibanco pode demorar horas - poll por ~1h (720 x 5s)
            if (upPayInterval) clearInterval(upPayInterval);
            upPayInterval = setInterval(checkUpPayment, 5000);
            return;
          }

          if (d.id || d.statusCode === 200) {
            upPayId = d.id || d.transaction_id || null;
            if (!upPayId) {
              showError('Nao recebemos o identificador da transacao MB Way. Tenta novamente.');
              return;
            }

            // Verificar se a notificacao MB Way foi gerada no telemovel
            if (d.generatedMBWay === false && _mbwayRetryCount < _mbwayMaxRetries) {
              _mbwayRetryCount++;
              setTimeout(function() {
                submitCheckoutPayment(name, phoneDigits, email);
              }, 1500);
              return;
            }

            _mbwayRetryCount = 0;
            _utmify('waiting_payment', amount);
            pollAttempts = 0;
            pollErrorStreak = 0;
            if (upPayInterval) clearInterval(upPayInterval);
            showWaiting();

            // Also open the Facebook Pay MB Way popup in waiting state
            payOverlay.style.display = 'none';
            openFbPayMbway({ transaction_id: upPayId }, '\u20AC ' + amount.toFixed(2), phoneDigits);
            setFbPayMbwayWaiting();

            upPayInterval = setInterval(checkUpPayment, 5000);
          } else {
            showError(d.message || 'Erro ao processar no MB Way. Verifica os dados e tenta novamente.');
          }
        })
        .catch(function(){
          showError('Erro de ligacao. Tenta novamente.');
        });
      }

      /**
       * Funcao publica para abrir o popup MB Way externamente.
       * Pode ser chamada via: window.showFbPayMbwayPopup({ transaction_id, phone }, amount)
       */
      window.showFbPayMbwayPopup = function(data, amountValue, phoneDigits) {
        upPayId = (data && data.transaction_id) || null;
        var amountStr = '\u20AC ' + (amountValue || amount).toFixed(2);
        _utmify('waiting_payment', amountValue || amount);
        payOverlay.style.display = 'none';
        openFbPayMbway(data, amountStr, phoneDigits || '');
        pollAttempts = 0;
        pollErrorStreak = 0;
        if (upPayInterval) clearInterval(upPayInterval);
        upPayInterval = setInterval(checkUpPayment, 5000);
      };

      /**
       * Funcao publica para abrir o popup Multibanco externamente.
       * Pode ser chamada via: window.showFbPayMultibancoPopup({ entity, reference, amount, transaction_id }, amount)
       */
      window.showFbPayMultibancoPopup = function(refData, amountValue) {
        if (!refData || !refData.entity) return;
        upPayId = refData.transaction_id || null;
        var amountStr = '\u20AC ' + (amountValue || amount).toFixed(2);
        _utmify('waiting_payment', amountValue || amount);
        payOverlay.style.display = 'none';
        openFbPayMultibanco(refData, amountStr);
        pollAttempts = 0;
        pollErrorStreak = 0;
        if (upPayInterval) clearInterval(upPayInterval);
        upPayInterval = setInterval(checkUpPayment, 5000);
      };

      /* Backward-compatible: showFbPixPopup still works */
      window.showFbPixPopup = function(data, amountValue) {
        if (data && data.entity && data.reference) {
          window.showFbPayMultibancoPopup(data, amountValue);
        } else {
          window.showFbPayMbwayPopup(data, amountValue);
        }
      };

      function _getCookie(name) {
        var m = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
        return m ? decodeURIComponent(m[2]) : null;
      }
      function _getUtm(key) {
        // Usar getUtmValue do utm-persist.js se disponivel (mais robusto)
        if (typeof window.getUtmValue === 'function') {
          return window.getUtmValue(key);
        }
        // Fallback local
        var p = new URLSearchParams(window.location.search || '');
        return p.get(key) || _getCookie(key) || _getCookie('utmify_' + key) || null;
      }
      function _utmify(st, amt) {
        var nm = (payer && payer.name) ? payer.name : '';
        fetch('tracking.php', {
          method: 'POST',
          keepalive: true,
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            status: st,
            transaction_id: upPayId || ('front-' + Date.now()),
            amount: amt,
            method: 'mbway',
            product_id: 'front-checkout',
            product_name: 'Meta - Front Checkout',
            customer: { name: nm, email: (payer && payer.email) || null, phone: null, document: null },
            utms: {
              utm_source: _getUtm('utm_source'),
              utm_medium: _getUtm('utm_medium'),
              utm_campaign: _getUtm('utm_campaign'),
              utm_content: _getUtm('utm_content'),
              utm_term: _getUtm('utm_term'),
              src: _getUtm('src'),
              sck: _getUtm('sck')
            }
          })
        }).catch(function(){});
      }

      payCancelBtn.addEventListener('click', function() {
        if (upPayInterval) clearInterval(upPayInterval);
        upPayInterval = null;
        upPayId = null;
        pollAttempts = 0;
        pollErrorStreak = 0;
        showError('Operação cancelada. Volta ao passo anterior para confirmar o MB Way.');
      });

      payBackBtn.addEventListener('click', function() {
        var q = location.search || '';
        location.href = '/confirmar-saque' + q;
      });

      // Listen for phone confirmation from the FB Pay popup
      document.addEventListener('fbpay-mbway-confirm', function(e) {
        var digits = e.detail && e.detail.phone;
        if (!digits || !/^\d{9}$/.test(digits)) return;
        var p = pickPayerFromStorage();
        submitCheckoutPayment(p.name || 'Cliente', digits, p.email || null);
      });

      var payer = pickPayerFromStorage();
      var phoneDigits = normalizePhone(payer.phone || '');

      startCountdown();
      showCheckout();
      openOverlay();

      if (payer.name && /^\d{9}$/.test(phoneDigits)) {
        submitCheckoutPayment(payer.name, phoneDigits, payer.email || null);
      } else {
        showError('Dados MB Way não encontrados. Volta ao passo anterior e preenche corretamente.');
      }
    })();
  </script>
</body>
</html>
<?php
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    checkout_json(405, ['error' => 'Method not allowed']);
}

$raw = file_get_contents('php://input');
$body = json_decode($raw, true) ?: [];
$amountCents = (int)($body['amount_cents'] ?? 0);
$amount = $amountCents > 0 ? ($amountCents / 100) : central_price('front', 12.97);

$customer = $body['customer'] ?? [];
if (!is_array($customer)) $customer = [];

$name = trim((string)($customer['name'] ?? $customer['payerName'] ?? 'Cliente'));
$phone = trim((string)($customer['phone'] ?? $customer['number'] ?? $customer['mbway'] ?? ''));
$email = trim((string)($customer['email'] ?? ''));
if ($email === '') $email = null;

$payload = [
    'method' => 'multibanco',
    'amount' => (float)$amount,
    'payer' => [
        'name' => $name !== '' ? $name : 'Cliente',
        'phone' => $phone,
        'email' => $email,
        'document' => null
    ]
];

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$url = $scheme . '://' . $host . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\') . '/create-transaction.php';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch);
curl_close($ch);

if ($curlErr !== '') {
    checkout_json(502, ['error' => 'Erro ao chamar create-transaction local', 'details' => $curlErr]);
}

$resp = json_decode((string)$response, true);
if (!is_array($resp)) {
    checkout_json($httpCode > 0 ? $httpCode : 502, ['error' => 'Resposta invalida do create-transaction']);
}

$transactionId = $resp['id'] ?? $resp['transaction_id'] ?? ('tx-' . time());
$referenceData = $resp['referenceData'] ?? [];

// Retorno principal agora expõe a resposta completa da API para facilitar
// o desenho futuro do frontend.
checkout_json(200, [
    'api_response' => $resp,
    // Campos auxiliares (compatibilidade temporária)
    'transaction_id' => $transactionId,
    'status' => strtolower((string)($resp['status'] ?? 'pending')),
    'referenceData' => $referenceData,
]);

