<?php
session_start();
require_once '../configs.php';
require_once 'KamiPayAPI.php';

// Verificar parámetros
if (!isset($_GET['op']) || !isset($_GET['ref'])) {
    header("Location: ../donaciones.php?error=" . urlencode("Parámetros de pago PIX inválidos"));
    exit();
}

$operation_id = $_GET['op'];
$external_reference = $_GET['ref'];

// Obtener datos de la transacción
try {
    $stmt = $pdo->prepare("SELECT * FROM kamipay_transactions WHERE operation_id = ? AND external_reference = ? LIMIT 1");
    $stmt->execute([$operation_id, $external_reference]);
    $transaction = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$transaction) {
        header("Location: ../donaciones.php?error=" . urlencode("Transacción PIX no encontrada"));
        exit();
    }
    
    // Verificar si la transacción ha expirado
    if (strtotime($transaction['expires_at']) < time()) {
        // Actualizar estado a expirado
        $stmt = $pdo->prepare("UPDATE kamipay_transactions SET status = 'expired' WHERE id = ?");
        $stmt->execute([$transaction['id']]);
        
        header("Location: ../donaciones.php?error=" . urlencode("La transacción PIX ha expirado. Intente nuevamente"));
        exit();
    }
    
} catch (PDOException $e) {
    error_log("Error accessing KamiPay transaction: " . $e->getMessage());
    header("Location: ../donaciones.php?error=" . urlencode("Error al acceder a la transacción"));
    exit();
}

// Calcular tiempo restante
$time_remaining = strtotime($transaction['expires_at']) - time();
$minutes_remaining = floor($time_remaining / 60);
$seconds_remaining = $time_remaining % 60;
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pago PIX - L2Jade</title>
    <!-- Favicon -->
    <link rel="icon" type="image/png" href="../assets/media/favicons/favicon-32x32.png">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome para iconos -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Modern Antiqua Font -->
    <link href="https://fonts.googleapis.com/css2?family=Modern+Antiqua&display=swap" rel="stylesheet">
    <!-- QR Code Generator -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>
    
    <style>
        :root {
            --jade: #00c896;
            --jade-light: #33d9ac;
            --jade-dark: #00967c;
            --dark-bg: #0a0a12;
        }
        
        body {
            font-family: 'Modern Antiqua', serif;
            background-color: #000000;
            color: #f1f1f1;
            min-height: 100vh;
            cursor: url("../assets/media/cursors/image.png"), auto !important;
        }
        
        .background-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            overflow: hidden;
        }
        
        .background-image {
            position: absolute;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
        }
        
        .container {
            position: relative;
            z-index: 10;
            padding: 2rem 1rem;
        }
        
        .payment-card {
            background-color: rgba(10, 10, 18, 0.9);
            backdrop-filter: blur(8px);
            border: 1px solid rgba(0, 200, 150, 0.3);
            border-radius: 1rem;
            padding: 2rem;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
        }
        
        .qr-container {
            background: white;
            border-radius: 1rem;
            padding: 1rem;
            display: inline-block;
            margin: 1rem 0;
        }
        
        .timer {
            background-color: rgba(220, 38, 38, 0.2);
            border: 1px solid rgba(220, 38, 38, 0.4);
            border-radius: 0.5rem;
            padding: 1rem;
            text-align: center;
            margin: 1rem 0;
        }
        
        .timer.warning {
            background-color: rgba(245, 158, 11, 0.2);
            border-color: rgba(245, 158, 11, 0.4);
        }
        
        .timer.danger {
            background-color: rgba(220, 38, 38, 0.3);
            border-color: rgba(220, 38, 38, 0.6);
            animation: pulse 1s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.7; }
            100% { opacity: 1; }
        }
        
        .transaction-details {
            background-color: rgba(17, 24, 39, 0.5);
            border-radius: 0.5rem;
            padding: 1rem;
            margin: 1rem 0;
        }
        
        .copy-button {
            background-color: var(--jade);
            border: none;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .copy-button:hover {
            background-color: var(--jade-dark);
        }
        
        .status-indicator {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            font-weight: 500;
        }
        
        .status-pending {
            background-color: rgba(245, 158, 11, 0.2);
            color: #f59e0b;
            border: 1px solid rgba(245, 158, 11, 0.4);
        }
        
        .status-processing {
            background-color: rgba(59, 130, 246, 0.2);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.4);
        }
        
        .status-completed {
            background-color: rgba(34, 197, 94, 0.2);
            color: #22c55e;
            border: 1px solid rgba(34, 197, 94, 0.4);
        }
        
        .back-button {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            background-color: rgba(107, 114, 128, 0.2);
            border: 1px solid rgba(107, 114, 128, 0.4);
            color: #d1d5db;
            text-decoration: none;
            border-radius: 0.5rem;
            transition: all 0.3s;
        }
        
        .back-button:hover {
            background-color: rgba(107, 114, 128, 0.3);
            color: white;
        }
        
        .instructions {
            background-color: rgba(59, 130, 246, 0.1);
            border: 1px solid rgba(59, 130, 246, 0.3);
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin: 1rem 0;
        }
        
        .instructions h4 {
            color: #60a5fa;
            margin-bottom: 1rem;
        }
        
        .instructions ol {
            margin: 0;
            padding-left: 1.5rem;
        }
        
        .instructions li {
            margin-bottom: 0.5rem;
        }
    </style>
</head>
<body>
    <!-- Contenedor de fondo -->
    <div class="background-container">
        <img src="../assets/media/background 3.jpg.jpeg" alt="Fondo místico" class="background-image">
        <div class="overlay"></div>
    </div>

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="payment-card">
                    <!-- Header -->
                    <div class="text-center mb-4">
                        <h2 style="color: var(--jade);">
                            <i class="fas fa-qrcode"></i> Pago PIX
                        </h2>
                        <p class="text-muted">Escaneie o código QR com seu aplicativo do banco</p>
                    </div>

                    <!-- Timer -->
                    <div class="timer" id="timer">
                        <h5><i class="fas fa-clock"></i> Tempo restante</h5>
                        <div id="countdown" style="font-size: 1.5rem; font-weight: bold;">
                            <?= sprintf('%02d:%02d', $minutes_remaining, $seconds_remaining) ?>
                        </div>
                    </div>

                    <!-- QR Code -->
                    <div class="text-center">
                        <div class="qr-container">
                            <canvas id="qr-code"></canvas>
                        </div>
                        <p class="small text-muted">Código PIX válido por 15 minutos</p>
                    </div>

                    <!-- PIX Code Copy -->
                    <div class="text-center mb-4">
                        <label class="form-label">Ou copie o código PIX:</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="pix-code" 
                                   value="<?= htmlspecialchars($transaction['emv_code']) ?>" readonly>
                            <button class="copy-button" onclick="copyPixCode()">
                                <i class="fas fa-copy"></i> Copiar
                            </button>
                        </div>
                    </div>

                    <!-- Transaction Details -->
                    <div class="transaction-details">
                        <h5 style="color: var(--jade); margin-bottom: 1rem;">
                            <i class="fas fa-info-circle"></i> Detalhes da Transação
                        </h5>
                        <div class="row">
                            <div class="col-6"><strong>Personagem:</strong></div>
                            <div class="col-6"><?= htmlspecialchars($transaction['character_name']) ?></div>
                        </div>
                        <div class="row">
                            <div class="col-6"><strong>Quantidade JC:</strong></div>
                            <div class="col-6"><?= number_format($transaction['amount_jc'], 0, ',', '.') ?> JC</div>
                        </div>
                        <div class="row">
                            <div class="col-6"><strong>Valor BRL:</strong></div>
                            <div class="col-6">R$ <?= number_format($transaction['amount_brl'], 2, ',', '.') ?></div>
                        </div>
                        <div class="row">
                            <div class="col-6"><strong>Equivalente USDT:</strong></div>
                            <div class="col-6"><?= number_format($transaction['amount_usdt'], 4, ',', '.') ?> USDT</div>
                        </div>
                        <div class="row">
                            <div class="col-6"><strong>Status:</strong></div>
                            <div class="col-6">
                                <span class="status-indicator status-<?= $transaction['status'] ?>" id="status-indicator">
                                    <i class="fas fa-clock"></i>
                                    <span id="status-text">Aguardando pagamento</span>
                                </span>
                            </div>
                        </div>
                    </div>

                    <!-- Instructions -->
                    <div class="instructions">
                        <h4><i class="fas fa-mobile-alt"></i> Como pagar com PIX</h4>
                        <ol>
                            <li>Abra o aplicativo do seu banco</li>
                            <li>Selecione a opção PIX</li>
                            <li>Escolha "Ler QR Code" ou "Pix Copia e Cola"</li>
                            <li>Escaneie o QR code ou cole o código PIX</li>
                            <li>Confirme o pagamento de R$ <?= number_format($transaction['amount_brl'], 2, ',', '.') ?></li>
                            <li>Aguarde a confirmação automática</li>
                        </ol>
                    </div>

                    <!-- Actions -->
                    <div class="text-center">
                        <a href="../donaciones.php" class="back-button">
                            <i class="fas fa-arrow-left"></i>
                            Voltar às doações
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        // Configurar dados da transação
        const transactionData = {
            operationId: '<?= $operation_id ?>',
            externalRef: '<?= $external_reference ?>',
            emvCode: '<?= addslashes($transaction['emv_code']) ?>',
            expiresAt: <?= strtotime($transaction['expires_at']) * 1000 ?>, // Convert to milliseconds
            status: '<?= $transaction['status'] ?>'
        };

        // Gerar QR Code
        const qr = new QRious({
            element: document.getElementById('qr-code'),
            value: transactionData.emvCode,
            size: 250,
            level: 'M'
        });

        // Função para copiar código PIX
        function copyPixCode() {
            const pixCodeInput = document.getElementById('pix-code');
            pixCodeInput.select();
            pixCodeInput.setSelectionRange(0, 99999); // Para dispositivos móveis
            
            try {
                document.execCommand('copy');
                
                // Feedback visual
                const button = event.target.closest('button');
                const originalHtml = button.innerHTML;
                button.innerHTML = '<i class="fas fa-check"></i> Copiado!';
                button.style.backgroundColor = '#22c55e';
                
                setTimeout(() => {
                    button.innerHTML = originalHtml;
                    button.style.backgroundColor = '';
                }, 2000);
                
            } catch (err) {
                alert('Erro ao copiar. Selecione o texto manualmente.');
            }
        }

        // Timer countdown
        let timeRemaining = Math.floor((transactionData.expiresAt - Date.now()) / 1000);
        const timerElement = document.getElementById('timer');
        const countdownElement = document.getElementById('countdown');

        function updateTimer() {
            if (timeRemaining <= 0) {
                countdownElement.innerHTML = '00:00';
                timerElement.classList.add('danger');
                document.querySelector('.qr-container').style.opacity = '0.5';
                
                // Redirect after expiration
                setTimeout(() => {
                    window.location.href = '../donaciones.php?error=' + encodeURIComponent('A transação PIX expirou');
                }, 3000);
                
                return;
            }
            
            const minutes = Math.floor(timeRemaining / 60);
            const seconds = timeRemaining % 60;
            
            countdownElement.innerHTML = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            
            // Change timer color based on time remaining
            if (timeRemaining <= 60) {
                timerElement.classList.add('danger');
            } else if (timeRemaining <= 300) {
                timerElement.classList.add('warning');
            }
            
            timeRemaining--;
        }

        // Update timer every second
        updateTimer();
        const timerInterval = setInterval(updateTimer, 1000);

        // Check payment status periodically
        let statusCheckInterval = setInterval(checkPaymentStatus, 10000); // Every 10 seconds

        function checkPaymentStatus() {
            fetch('check_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    operation_id: transactionData.operationId,
                    external_ref: transactionData.externalRef
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status && data.status !== transactionData.status) {
                    updatePaymentStatus(data.status, data.message);
                    
                    if (data.status === 'completed') {
                        clearInterval(statusCheckInterval);
                        clearInterval(timerInterval);
                        
                        // Redirect to success page
                        setTimeout(() => {
                            window.location.href = '../index.php?success=' + encodeURIComponent('Pagamento PIX confirmado! JC creditado ao personagem.');
                        }, 3000);
                    }
                }
            })
            .catch(error => {
                console.error('Error checking payment status:', error);
            });
        }

        function updatePaymentStatus(status, message) {
            const statusIndicator = document.getElementById('status-indicator');
            const statusText = document.getElementById('status-text');
            
            // Remove existing status classes
            statusIndicator.className = 'status-indicator';
            
            switch(status) {
                case 'processing':
                    statusIndicator.classList.add('status-processing');
                    statusIndicator.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <span>Processando pagamento</span>';
                    break;
                case 'completed':
                    statusIndicator.classList.add('status-completed');
                    statusIndicator.innerHTML = '<i class="fas fa-check"></i> <span>Pagamento confirmado!</span>';
                    break;
                case 'failed':
                    statusIndicator.classList.add('status-danger');
                    statusIndicator.innerHTML = '<i class="fas fa-times"></i> <span>Pagamento falhou</span>';
                    break;
            }
            
            transactionData.status = status;
        }

        // Handle page visibility change (when user switches tabs)
        document.addEventListener('visibilitychange', function() {
            if (!document.hidden) {
                // Page became visible again, check status immediately
                checkPaymentStatus();
            }
        });
    </script>
</body>
</html>
