<!-- Modal de Pagamento -->
<div id="paymentModal" class="payment-modal" style="display: none;">
    <div class="payment-modal-overlay" onclick="closePaymentModal()"></div>
    <div class="payment-modal-content">
        <button class="payment-modal-close" onclick="closePaymentModal()">
            <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
        </button>
        
        <!-- Estado: Seleção de Método -->
        <div id="paymentMethodStep" class="payment-step">
            <div class="payment-modal-header">
                <iconify-icon icon="solar:card-bold" style="font-size: 2rem; color: var(--primary);"></iconify-icon>
                <h3>Escolha a forma de pagamento</h3>
                <p id="planInfo">Plano <span id="selectedPlanName">-</span> - R$ <span id="selectedPlanPrice">0,00</span>/mês</p>
            </div>
            
            <div class="payment-methods">
                <button class="payment-method-btn" onclick="processPayment('checkout')">
                    <iconify-icon icon="solar:card-bold"></iconify-icon>
                    <div>
                        <strong>Cartão de Crédito</strong>
                        <span>Pague em até 12x</span>
                    </div>
                </button>
                
                <button class="payment-method-btn" onclick="processPayment('pix')">
                    <iconify-icon icon="ic:baseline-pix"></iconify-icon>
                    <div>
                        <strong>PIX</strong>
                        <span>Aprovação instantânea</span>
                    </div>
                </button>
            </div>
        </div>
        
        <!-- Estado: Loading -->
        <div id="paymentLoadingStep" class="payment-step" style="display: none;">
            <div class="payment-loading">
                <div class="spinner"></div>
                <p>Processando pagamento...</p>
            </div>
        </div>
        
        <!-- Estado: PIX -->
        <div id="paymentPixStep" class="payment-step" style="display: none;">
            <div class="payment-modal-header">
                <iconify-icon icon="ic:baseline-pix" style="font-size: 2rem; color: #32BCAD;"></iconify-icon>
                <h3>Pague com PIX</h3>
                <p>Escaneie o QR Code ou copie o código</p>
            </div>
            
            <div class="pix-container">
                <div id="pixQrCode" class="pix-qr-code"></div>
                
                <div class="pix-code-container">
                    <input type="text" id="pixCode" readonly class="pix-code-input">
                    <button onclick="copyPixCode()" class="btn btn-primary">
                        <iconify-icon icon="solar:copy-bold"></iconify-icon>
                        Copiar
                    </button>
                </div>
                
                <p class="pix-expiry">Válido por <span id="pixExpiry">30 minutos</span></p>
            </div>
        </div>
        
        <!-- Estado: Erro -->
        <div id="paymentErrorStep" class="payment-step" style="display: none;">
            <div class="payment-error">
                <iconify-icon icon="solar:danger-triangle-bold" style="font-size: 4rem; color: var(--danger, #dc2626);"></iconify-icon>
                <h3>Erro no Pagamento</h3>
                <p id="paymentErrorMessage">Ocorreu um erro ao processar o pagamento.</p>
                <button onclick="showPaymentMethods()" class="btn btn-primary">
                    Tentar Novamente
                </button>
            </div>
        </div>
    </div>
</div>

<style>
.payment-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
}
.payment-modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.7);
    backdrop-filter: blur(4px);
}
.payment-modal-content {
    position: relative;
    background: var(--bg-card, #fff);
    border-radius: 16px;
    padding: 2rem;
    max-width: 450px;
    width: 90%;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}
.payment-modal-close {
    position: absolute;
    top: 1rem;
    right: 1rem;
    background: transparent;
    border: none;
    font-size: 1.5rem;
    color: var(--text-muted);
    cursor: pointer;
}
.payment-modal-header {
    text-align: center;
    margin-bottom: 1.5rem;
}
.payment-modal-header h3 {
    margin: 0.75rem 0 0.25rem;
    font-size: 1.25rem;
}
.payment-modal-header p {
    color: var(--text-muted);
    margin: 0;
    font-size: 0.9rem;
}
.payment-methods {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}
.payment-method-btn {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1.25rem;
    background: var(--bg-darker, #f5f5f5);
    border: 2px solid var(--border, #e0e0e0);
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s;
    text-align: left;
}
.payment-method-btn:hover {
    border-color: var(--primary);
    background: rgba(37, 99, 235, 0.05);
}
.payment-method-btn iconify-icon {
    font-size: 2rem;
    color: var(--primary);
}
.payment-method-btn strong {
    display: block;
    font-size: 1rem;
    color: var(--text-primary, #1a1a1a);
}
.payment-method-btn span {
    font-size: 0.85rem;
    color: var(--text-muted);
}
.payment-loading {
    text-align: center;
    padding: 3rem 0;
}
.spinner {
    width: 50px;
    height: 50px;
    border: 4px solid var(--border, #e0e0e0);
    border-top-color: var(--primary);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 1rem;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}
.pix-container {
    text-align: center;
}
.pix-qr-code {
    width: 200px;
    height: 200px;
    margin: 0 auto 1.5rem;
    background: #fff;
    padding: 1rem;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.pix-qr-code img {
    max-width: 100%;
    max-height: 100%;
}
.pix-code-container {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 1rem;
}
.pix-code-input {
    flex: 1;
    padding: 0.75rem;
    border: 1px solid var(--border);
    border-radius: 8px;
    font-size: 0.75rem;
    background: var(--bg-darker);
    color: var(--text-primary);
}
.pix-expiry {
    color: var(--text-muted);
    font-size: 0.85rem;
}
.payment-error {
    text-align: center;
    padding: 2rem 0;
}
.payment-error h3 {
    margin: 1rem 0 0.5rem;
}
.payment-error p {
    color: var(--text-muted);
    margin-bottom: 1.5rem;
}
</style>

<script>
let selectedPlanId = null;
let selectedPlanName = '';
let selectedPlanPrice = 0;
let checkingPayment = false;

function openCheckout(planId, planName, planPrice) {
    selectedPlanId = planId;
    selectedPlanName = planName;
    selectedPlanPrice = planPrice;
    
    document.getElementById('selectedPlanName').textContent = planName;
    document.getElementById('selectedPlanPrice').textContent = planPrice.toLocaleString('pt-BR', {minimumFractionDigits: 2});
    
    showPaymentMethods();
    document.getElementById('paymentModal').style.display = 'flex';
}

function closePaymentModal() {
    document.getElementById('paymentModal').style.display = 'none';
    checkingPayment = false;
}

function showStep(stepId) {
    document.querySelectorAll('.payment-step').forEach(step => {
        step.style.display = 'none';
    });
    document.getElementById(stepId).style.display = 'block';
}

function showPaymentMethods() {
    showStep('paymentMethodStep');
}

async function processPayment(method) {
    showStep('paymentLoadingStep');
    
    try {
        const response = await fetch('/pages/api/subscription-checkout.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                plan_id: selectedPlanId,
                payment_method: method
            })
        });
        
        const data = await response.json();
        
        if (!data.success) {
            throw new Error(data.error || 'Erro ao processar pagamento');
        }
        
        if (data.type === 'pix') {
            showStep('paymentPixStep');
            
            if (data.qr_code_base64) {
                document.getElementById('pixQrCode').innerHTML = 
                    '<img src="data:image/png;base64,' + data.qr_code_base64 + '" alt="QR Code PIX">';
            } else if (data.qr_code) {
                document.getElementById('pixQrCode').innerHTML = 
                    '<img src="' + data.qr_code + '" alt="QR Code PIX">';
            }
            
            document.getElementById('pixCode').value = data.pix_code || '';
            startPaymentCheck(data.transaction_id);
            
        } else if (data.type === 'redirect') {
            if (data.checkout_url) {
                window.location.href = data.checkout_url;
            } else {
                throw new Error('URL de checkout não disponível');
            }
        }
        
    } catch (error) {
        document.getElementById('paymentErrorMessage').textContent = error.message;
        showStep('paymentErrorStep');
    }
}

function copyPixCode() {
    const pixCode = document.getElementById('pixCode');
    pixCode.select();
    document.execCommand('copy');
    
    const btn = event.target.closest('button');
    const originalText = btn.innerHTML;
    btn.innerHTML = '<iconify-icon icon="solar:check-circle-bold"></iconify-icon> Copiado!';
    btn.style.background = 'var(--success, #22c55e)';
    
    setTimeout(() => {
        btn.innerHTML = originalText;
        btn.style.background = '';
    }, 2000);
}

function startPaymentCheck(transactionId) {
    checkingPayment = true;
    
    const checkInterval = setInterval(async () => {
        if (!checkingPayment) {
            clearInterval(checkInterval);
            return;
        }
        
        try {
            const response = await fetch('/api/check-payment.php?transaction_id=' + transactionId);
            const data = await response.json();
            
            if (data.status === 'approved' || data.status === 'paid') {
                clearInterval(checkInterval);
                window.location.href = '/pages/assinatura.php?status=approved&plan=' + selectedPlanId;
            }
        } catch (e) {
            console.log('Verificando pagamento...');
        }
    }, 5000);
    
    setTimeout(() => {
        checkingPayment = false;
        clearInterval(checkInterval);
    }, 30 * 60 * 1000);
}
</script>
