<?php
// ==========================================================
// ARQUIVO: obrigado.php
// OBJETIVO: Página de Sucesso com Verificação Real
// ==========================================================

session_start();
require 'includes/conexao.php';

// Segurança: Apenas logado
if (!isset($_SESSION['account_id'])) {
    header("Location: login.php");
    exit;
}

$page_title = "Processando Pagamento...";
include 'includes/header.php'; 
?>

<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script>
<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>

<style>
    /* --- THEME CYBER DARK --- */
    :root {
        --bg-deep: #020617;
        --card-bg: #1e293b;
        --accent: #10b981; /* Verde Sucesso */
        --warning: #f59e0b; /* Laranja Espera */
        --glow: rgba(16, 185, 129, 0.5);
    }

    body { background-color: var(--bg-deep); color: white; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }

    .thank-container {
        min-height: 85vh;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20px;
        background: radial-gradient(circle at center, #1e1b4b 0%, var(--bg-deep) 70%);
    }

    .success-card {
        background: rgba(30, 41, 59, 0.85);
        backdrop-filter: blur(20px);
        -webkit-backdrop-filter: blur(20px);
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 24px;
        padding: 60px 40px;
        text-align: center;
        max-width: 600px;
        width: 100%;
        box-shadow: 0 25px 60px rgba(0,0,0,0.6);
        position: relative;
        overflow: hidden;
        transition: all 0.5s ease;
    }

    /* Borda animada (Loader) */
    .border-loader::after {
        content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px;
        background: linear-gradient(90deg, transparent, var(--warning), transparent);
        animation: scan 2s infinite linear;
    }
    
    /* Borda de Sucesso */
    .border-success::after {
        content: ''; position: absolute; top: 0; left: 0; right: 0; height: 4px;
        background: var(--accent);
        box-shadow: 0 0 20px var(--accent);
        animation: none;
    }

    .icon-wrapper {
        width: 110px; height: 110px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 50%;
        display: flex; align-items: center; justify-content: center;
        margin: 0 auto 35px auto;
        border: 2px solid rgba(255,255,255,0.1);
        transition: all 0.5s ease;
    }

    /* Estado: Carregando */
    .icon-loading { animation: spin 2s infinite linear; border-color: var(--warning); color: var(--warning); }
    .icon-loading i { font-size: 3rem; }

    /* Estado: Sucesso */
    .icon-success { 
        background: rgba(16, 185, 129, 0.1);
        border-color: var(--accent);
        box-shadow: 0 0 40px var(--glow);
        animation: pulse 2s infinite;
        transform: scale(1.1);
    }
    .icon-success i { font-size: 4rem; color: var(--accent); }

    h1 {
        font-family: 'Rajdhani', sans-serif;
        font-weight: 800;
        font-size: 2.8rem;
        margin-bottom: 15px;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    .status-text { font-size: 1.1rem; color: #cbd5e1; margin-bottom: 30px; line-height: 1.6; }

    /* Botões */
    .btn-action {
        display: block; width: 100%; padding: 18px; border-radius: 12px;
        font-weight: 800; text-transform: uppercase; letter-spacing: 1px;
        text-decoration: none; transition: 0.3s; margin-bottom: 15px; border: none; font-size: 1rem;
        opacity: 0.5; pointer-events: none; cursor: not-allowed;
        filter: grayscale(1);
    }
    
    .btn-active { 
        opacity: 1; pointer-events: all; cursor: pointer; filter: grayscale(0);
    }

    .btn-primary-glow {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white;
        box-shadow: 0 10px 30px rgba(16, 185, 129, 0.3);
    }
    .btn-primary-glow:hover { transform: translateY(-3px); box-shadow: 0 20px 40px rgba(16, 185, 129, 0.5); color: white; }

    .btn-secondary-ghost {
        background: rgba(255,255,255,0.05);
        border: 1px solid rgba(255,255,255,0.1);
        color: #94a3b8;
        opacity: 1; pointer-events: all; cursor: pointer; filter: grayscale(0);
    }
    .btn-secondary-ghost:hover { background: rgba(255,255,255,0.1); border-color: white; color: white; }

    .loader-text { font-size: 0.85rem; color: var(--warning); font-weight: bold; letter-spacing: 1px; text-transform: uppercase; }

    /* Animações */
    @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); } 70% { box-shadow: 0 0 0 25px rgba(16, 185, 129, 0); } 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); } }
    @keyframes scan { 0% { transform: translateX(-100%); } 100% { transform: translateX(100%); } }
    @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
</style>

<div class="thank-container">
    <div class="success-card border-loader" id="mainCard" data-aos="zoom-in">
        
        <div class="icon-wrapper icon-loading" id="iconBox">
            <i class="fas fa-circle-notch" id="statusIcon"></i>
        </div>

        <h1 id="statusTitle">Verificando...</h1>
        
        <p class="status-text" id="statusMsg">
            Aguardando a confirmação do seu pagamento.<br>
            Não feche esta página, geralmente leva poucos segundos.
        </p>

        <div id="loadingArea" class="loader-text mb-4">
            <i class="fas fa-satellite-dish fa-spin me-2"></i> Conectando ao Banco...
        </div>

        <div class="actions">
            <a href="shop.php" class="btn-action btn-primary-glow" id="btnShop">
                <i class="fas fa-lock me-2" id="btnIcon"></i> Aguardando Confirmação
            </a>
            <a href="account.php" class="btn-action btn-secondary-ghost">
                <i class="fas fa-arrow-left me-2"></i> Voltar ao Painel
            </a>
        </div>

    </div>
</div>

<script>
    AOS.init();

    // 1. Pega o ID da Transação da URL
    const urlParams = new URLSearchParams(window.location.search);
    const transactionId = urlParams.get('tid');

    let checkInterval;
    let attempts = 0;
    const maxAttempts = 200; // ~10 minutos tentando

    function startChecking() {
        // Monta a URL de verificação
        let fetchUrl = 'check_last_payment.php';
        if (transactionId) {
            fetchUrl += '?tid=' + transactionId;
        }

        // Loop de verificação
        checkInterval = setInterval(() => {
            attempts++;
            
            fetch(fetchUrl)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'approved') {
                    paymentApproved();
                } else if (attempts >= maxAttempts) {
                    paymentTimeout();
                }
                // Se for 'pending' ou 'not_found', o loop continua...
            })
            .catch(err => console.error("Erro na verificação:", err));

        }, 3000); // Checa a cada 3 segundos
    }

    function paymentApproved() {
        clearInterval(checkInterval); // Para o loop
        
        // Elementos da UI
        const card = document.getElementById('mainCard');
        const iconBox = document.getElementById('iconBox');
        const icon = document.getElementById('statusIcon');
        const title = document.getElementById('statusTitle');
        const msg = document.getElementById('statusMsg');
        const btn = document.getElementById('btnShop');
        const loadArea = document.getElementById('loadingArea');

        // Transformação Visual (Sucesso)
        card.classList.remove('border-loader');
        card.classList.add('border-success');
        
        iconBox.classList.remove('icon-loading');
        iconBox.classList.add('icon-success');
        
        icon.className = 'fas fa-check';
        
        title.innerText = "PAGAMENTO APROVADO!";
        title.style.background = "none";
        title.style.color = "#10b981"; // Verde neon
        title.style.textShadow = "0 0 20px rgba(16, 185, 129, 0.6)";
        
        msg.innerHTML = "Seus pontos foram creditados com sucesso.<br>Obrigado por apoiar o servidor!";
        
        // Remove texto de loading
        if(loadArea) loadArea.style.display = 'none';
        
        // Ativa o Botão do Shop
        btn.classList.add('btn-active');
        btn.innerHTML = '<i class="fas fa-shopping-cart me-2"></i> GASTAR MEUS PONTOS';
        
        // Efeito de Confetes
        fireConfetti();
    }

    function paymentTimeout() {
        // Não encerra o loop completamente para não frustrar se for apenas lentidão bancária
        // Mas avisa o usuário
        document.getElementById('statusTitle').innerText = "Ainda Verificando...";
        document.getElementById('statusMsg').innerText = "O banco está demorando um pouco mais que o normal. Você pode verificar seu saldo no painel em breve.";
    }

    function fireConfetti() {
        var duration = 3000;
        var end = Date.now() + duration;
        (function frame() {
            confetti({ particleCount: 5, angle: 60, spread: 55, origin: { x: 0 } });
            confetti({ particleCount: 5, angle: 120, spread: 55, origin: { x: 1 } });
            if (Date.now() < end) requestAnimationFrame(frame);
        }());
    }

    // Inicia assim que carrega
    window.addEventListener('load', startChecking);
</script>

<?php include 'includes/footer.php'; ?>