<?php
session_start();

// Cek apakah ada data QRIS di session
if (!isset($_SESSION['qris_data']) || empty($_SESSION['qris_data'])) {
    // Redirect ke halaman deposit jika tidak ada data
    header('Location: pages/user/deposit.php');
    exit;
}

// Ambil data dari session
$qrisData = $_SESSION['qris_data'];

// Ambil data dari database untuk redirect URL
include "config/koneksi.php";

$query = "SELECT urlweb FROM tb_seo LIMIT 1";
$result = mysqli_query($conn, $query);
$seo_data = mysqli_fetch_assoc($result);
$redirect_url = $seo_data ? $seo_data['urlweb'] : 'https://3d695fb89807.ngrok-free.app';

// Extract data dari response API
$qr_string = $qrisData['qris_response']['data']['data'] ?? '';
$trx_id = $qrisData['qris_response']['data']['trx_id'] ?? 'N/A';
$amount = number_format($qrisData['amount'] ?? 0, 0, ',', '.');
$username = $qrisData['username'] ?? 'N/A';
$expired_seconds = $qrisData['qris_response']['data']['expired_at'] ?? 1200;

// Validasi QR string
if (empty($qr_string)) {
    echo "Error: QR Code data tidak tersedia";
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pembayaran QRIS</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
            line-height: 1.6;
        }

        .container {
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
            padding: 20px;
        }

        .card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            margin-bottom: 20px;
        }

        .card-header {
            background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
            color: white;
            padding: 25px;
            text-align: center;
            position: relative;
        }

        .card-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            opacity: 0.3;
        }

        .card-header h1 {
            font-size: 1.8rem;
            font-weight: 700;
            margin: 0;
            position: relative;
            z-index: 1;
        }

        .card-header .subtitle {
            font-size: 0.9rem;
            opacity: 0.9;
            margin-top: 5px;
            position: relative;
            z-index: 1;
        }

        .card-body {
            padding: 30px;
        }

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

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

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

            100% {
                transform: rotate(360deg);
            }
        }

        .loading p {
            color: #666;
            font-size: 1.1rem;
        }

        .qr-container {
            text-align: center;
            padding: 30px;
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            border-radius: 16px;
            margin: 20px 0;
            border: 2px solid #e2e8f0;
            position: relative;
            overflow: hidden;
        }

        .qr-container::before {
            content: '';
            position: absolute;
            top: -2px;
            left: -2px;
            right: -2px;
            bottom: -2px;
            background: linear-gradient(45deg, #8b5cf6, #7c3aed, #6d28d9, #5b21b6);
            border-radius: 16px;
            z-index: -1;
            animation: borderGlow 3s ease-in-out infinite alternate;
        }

        @keyframes borderGlow {
            0% {
                opacity: 0.5;
            }

            100% {
                opacity: 1;
            }
        }

        .qr-code {
            max-width: 250px;
            width: 100%;
            height: auto;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(139, 92, 246, 0.3);
            transition: transform 0.3s ease;
            background: white;
            padding: 10px;
        }

        .qr-code:hover {
            transform: scale(1.05);
        }

        .payment-info {
            background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
            padding: 25px;
            border-radius: 16px;
            margin: 20px 0;
            border: 1px solid #cbd5e1;
        }

        .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 15px 0;
            padding: 12px 0;
            border-bottom: 1px solid #e2e8f0;
        }

        .info-row:last-child {
            border-bottom: none;
        }

        .info-label {
            font-weight: 600;
            color: #475569;
            font-size: 0.95rem;
        }

        .info-value {
            color: #1e293b;
            font-weight: 700;
            font-size: 0.95rem;
            background: linear-gradient(135deg, #8b5cf6, #7c3aed);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .countdown {
            text-align: center;
            font-size: 1.2rem;
            font-weight: 700;
            color: #dc2626;
            margin: 25px 0;
            padding: 20px;
            background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
            border-radius: 16px;
            border: 2px solid #fecaca;
        }

        .countdown i {
            color: #dc2626;
            margin-right: 8px;
        }

        .instructions {
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            padding: 25px;
            border-radius: 16px;
            margin: 20px 0;
            border: 1px solid #e2e8f0;
        }

        .instructions h5 {
            color: #1e293b;
            font-size: 1.1rem;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .instructions h5 i {
            color: #8b5cf6;
        }

        .step {
            margin: 15px 0;
            padding: 15px;
            background: white;
            border-radius: 12px;
            border-left: 4px solid #8b5cf6;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .step:hover {
            transform: translateX(5px);
            box-shadow: 0 4px 20px rgba(139, 92, 246, 0.15);
        }

        .step strong {
            color: #8b5cf6;
            margin-right: 8px;
        }

        .alert {
            margin: 20px 0;
            border-radius: 12px;
            padding: 20px;
            border: none;
            position: relative;
            overflow: hidden;
        }

        .alert-info {
            background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
            color: #1e40af;
            border-left: 4px solid #3b82f6;
        }

        .alert-info i {
            color: #3b82f6;
            margin-right: 8px;
        }

        .btn-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-top: 25px;
        }

        .btn {
            padding: 16px 24px;
            border: none;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
            position: relative;
            overflow: hidden;
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s;
        }

        .btn:hover::before {
            left: 100%;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
        }

        .btn:active {
            transform: translateY(0);
        }

        .btn-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }

        .btn-primary {
            background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
            color: white;
        }

        .btn i {
            font-size: 1.1rem;
        }

        .expired-alert {
            background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
            color: #dc2626;
            border-left: 4px solid #dc2626;
            margin-bottom: 20px;
        }

        .expired-alert i {
            color: #dc2626;
            margin-right: 8px;
        }

        /* Mobile Responsiveness */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }

            .card-header {
                padding: 20px;
            }

            .card-header h1 {
                font-size: 1.5rem;
            }

            .card-body {
                padding: 20px;
            }

            .qr-container {
                padding: 20px;
            }

            .qr-code {
                max-width: 200px;
            }

            .btn-container {
                grid-template-columns: 1fr;
                gap: 12px;
            }

            .btn {
                padding: 14px 20px;
                font-size: 0.95rem;
            }

            .info-row {
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }

            .info-value {
                align-self: flex-end;
            }

            .countdown {
                font-size: 1.1rem;
                padding: 15px;
            }

            .instructions h5 {
                font-size: 1rem;
            }

            .step {
                padding: 12px;
                font-size: 0.9rem;
            }
        }

        @media (max-width: 480px) {
            .container {
                padding: 10px;
            }

            .card-header {
                padding: 15px;
            }

            .card-header h1 {
                font-size: 1.3rem;
            }

            .card-body {
                padding: 15px;
            }

            .qr-code {
                max-width: 180px;
            }

            .btn {
                padding: 12px 16px;
                font-size: 0.9rem;
            }
        }

        /* Animation for content appearance */
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Pulse animation for countdown */
        .pulse {
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.05);
            }

            100% {
                transform: scale(1);
            }
        }

        .error-message {
            color: #dc2626;
            text-align: center;
            padding: 20px;
            background: #fee;
            border-radius: 12px;
            margin: 20px 0;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="card">
            <div class="card-header">
                <h1><i class="fas fa-qrcode"></i> PEMBAYARAN QRIS</h1>
                <div class="subtitle">Scan QR Code untuk melakukan pembayaran</div>
            </div>
            <div class="card-body">
                <div id="loading" class="loading">
                    <div class="spinner"></div>
                    <p>Memuat QR Code...</p>
                </div>

                <div id="qris-content" style="display: none;" class="fade-in">
                    <!-- QR Code Container -->
                    <div class="qr-container">
                        <img id="qr-image" src="" alt="QR Code QRIS" class="qr-code">
                    </div>

                    <!-- Payment Information -->
                    <div class="payment-info">
                        <div class="info-row">
                            <span class="info-label">Username:</span>
                            <span class="info-value" id="username"><?php echo htmlspecialchars($username); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Nominal:</span>
                            <span class="info-value" id="amount">Rp <?php echo $amount; ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Transaction ID:</span>
                            <span class="info-value" id="trx-id"><?php echo htmlspecialchars($trx_id); ?></span>
                        </div>
                    </div>

                    <!-- Countdown Timer -->
                    <div class="countdown pulse">
                        <i class="fas fa-clock"></i>
                        Sisa Waktu: <span id="countdown-timer">20:00</span>
                    </div>

                    <!-- Instructions -->
                    <div class="instructions">
                        <h5><i class="fas fa-info-circle"></i> Cara Pembayaran:</h5>
                        <div class="step">
                            <strong>1.</strong> Buka aplikasi mobile banking atau e-wallet Anda
                        </div>
                        <div class="step">
                            <strong>2.</strong> Pilih menu "Scan QR" atau "QRIS"
                        </div>
                        <div class="step">
                            <strong>3.</strong> Arahkan kamera ke QR Code di atas
                        </div>
                        <div class="step">
                            <strong>4.</strong> Konfirmasi pembayaran di aplikasi Anda
                        </div>
                        <div class="step">
                            <strong>5.</strong> Tunggu konfirmasi pembayaran berhasil
                        </div>
                    </div>

                    <div class="alert alert-info">
                        <i class="fas fa-exclamation-triangle"></i>
                        <strong>Penting:</strong> Jangan menutup halaman ini sampai pembayaran selesai.
                        Sistem akan otomatis memverifikasi pembayaran Anda.
                    </div>

                    <!-- Action Buttons -->
                    <div class="btn-container">
                        <button class="btn btn-success" onclick="cekStatus()">
                            <i class="fas fa-sync-alt"></i> Cek Status
                        </button>
                        <button class="btn btn-primary" onclick="goBack()">
                            <i class="fas fa-arrow-left"></i> Kembali
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

    <script>
        // Data dari PHP
        const qrString = <?php echo json_encode($qr_string); ?>;
        const redirectUrl = <?php echo json_encode($redirect_url); ?>;
        const expiredSeconds = <?php echo $expired_seconds; ?>;

        console.log('=== PAYMENT PAGE LOADED ===');
        console.log('QR String Length:', qrString.length);
        console.log('QR String:', qrString.substring(0, 50) + '...');
        console.log('Expired Seconds:', expiredSeconds);
        console.log('Redirect URL:', redirectUrl);

        // Function untuk generate QR Code
        function generateQRCode() {
            console.log('Generating QR Code...');
            
            if (!qrString || qrString.length === 0) {
                console.error('QR String is empty!');
                document.getElementById('loading').innerHTML = '<div class="error-message">Error: Data QR Code tidak tersedia</div>';
                return;
            }

            // Generate QR Code menggunakan API
const qrApiUrl = 'https://api.qrserver.com/v1/create-qr-code/?data=' + encodeURIComponent(qrString);
            
            console.log('QR API URL:', qrApiUrl);

            const qrImage = document.getElementById('qr-image');
            
            qrImage.onload = function() {
                console.log('QR Code loaded successfully!');
                // Hide loading, show content
                document.getElementById('loading').style.display = 'none';
                document.getElementById('qris-content').style.display = 'block';
                
                // Start countdown
                startCountdown();
            };
            
            qrImage.onerror = function() {
                console.error('Failed to load QR Code');
                document.getElementById('loading').innerHTML = '<div class="error-message">Gagal memuat QR Code. Silakan refresh halaman.</div>';
            };
            
            qrImage.src = qrApiUrl;
        }

        // Countdown timer
        let countdownInterval;
        let remainingSeconds = expiredSeconds;

        function startCountdown() {
            console.log('Starting countdown from', remainingSeconds, 'seconds');
            
            updateCountdownDisplay();
            
            countdownInterval = setInterval(function() {
                remainingSeconds--;
                updateCountdownDisplay();
                
                if (remainingSeconds <= 0) {
                    clearInterval(countdownInterval);
                    handleExpired();
                }
            }, 1000);
        }

        function updateCountdownDisplay() {
            const minutes = Math.floor(remainingSeconds / 60);
            const seconds = remainingSeconds % 60;
            const display = String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
            
            document.getElementById('countdown-timer').textContent = display;
            
            // Change color when time is running out
            const countdownElement = document.querySelector('.countdown');
            if (remainingSeconds <= 60) {
                countdownElement.style.background = 'linear-gradient(135deg, #fee2e2 0%, #fecaca 100%)';
                countdownElement.classList.add('pulse');
            }
        }

        function handleExpired() {
            console.log('Payment expired');
            const contentDiv = document.getElementById('qris-content');
            contentDiv.innerHTML = `
                <div class="alert expired-alert">
                    <i class="fas fa-times-circle"></i>
                    <strong>Waktu Habis!</strong> QR Code telah kadaluarsa. Silakan lakukan transaksi baru.
                </div>
                <div class="btn-container">
                    <button class="btn btn-primary" onclick="goBack()">
                        <i class="fas fa-arrow-left"></i> Kembali
                    </button>
                </div>
            `;
        }

        function cekStatus() {
            console.log('Checking payment status...');
            window.location.href = redirectUrl;
        }

        function goBack() {
            // Clear session data (optional, bisa ditambahkan endpoint untuk clear session)
            window.location.href = 'pages/user/deposit.php';
        }

        // Initialize page when DOM is ready
        window.addEventListener('DOMContentLoaded', function() {
            console.log('DOM Content Loaded');
            generateQRCode();
        });

        // Handle page visibility (pause countdown when tab is hidden)
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                console.log('Page hidden, pausing countdown');
                clearInterval(countdownInterval);
            } else {
                console.log('Page visible, resuming countdown');
                if (remainingSeconds > 0) {
                    startCountdown();
                }
            }
        });
    </script>
</body>

</html>