<?php
ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../../config/koneksi.php');

$sid = session_id();
$sql_0 = mysqli_query($conn, "SELECT * FROM `tb_seo` WHERE cuid = 1") or die(mysqli_error());
$s0 = mysqli_fetch_array($sql_0);


if (!function_exists('get_active_base_url')) {
    include(__DIR__ . '/../../config/url_helper.php');
}
$urlweb = get_active_base_url();


// Cek apakah user sudah login
if (!isset($_SESSION['user'])) {
    header('Location: ' . $urlweb . '/m/?notif=6');
    exit();
}

// Cek apakah ada data QRIS di session
if (!isset($_SESSION['qris_payment']) || empty($_SESSION['qris_payment'])) {
    header('Location: ' . $urlweb . '/m/account/deposit');
    exit();
}

$qrisData = $_SESSION['qris_payment'];
$qrisContent = $qrisData['qris_data'];
$amount = $qrisData['amount'];
$kd_transaksi = $qrisData['kd_transaksi'];
$trx_id = $qrisData['trx_id'];

// Generate QR Code image URL
$qrImageUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' . urlencode($qrisContent);

include "../header.php";
?>

<div class="container-wrapper acc" style="background-color: black">
    <div class="container container-box noSidePadding">
        <div class="content">
            <div class="box-wrapper plr-15">
                <div class="box-wrapper plr-15">
                    <h4 class="text-center" style="color: gold; margin-top: 20px;">Pembayaran QRIS</h4>
                    <hr style="border-color: #333;">
                    
                    <div class="row">
                        <div class="col-md-12 text-center">
                            <div class="alert alert-info">
                                <strong>Kode Transaksi:</strong> <?php echo htmlspecialchars($kd_transaksi); ?><br>
                                <strong>Jumlah:</strong> Rp <?php echo number_format($amount, 0, ',', '.'); ?>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12 text-center">
                            <h5 style="color: white; margin-bottom: 20px;">Scan QR Code dengan aplikasi e-wallet atau mobile banking Anda</h5>
                            <div style="background: white; padding: 20px; display: inline-block; border-radius: 10px; margin-bottom: 20px;">
                                <img src="<?php echo htmlspecialchars($qrImageUrl); ?>" alt="QR Code" style="max-width: 300px; width: 100%;">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <div class="alert alert-warning">
                                <strong>Petunjuk:</strong>
                                <ol style="text-align: left; margin-top: 10px;">
                                    <li>Buka aplikasi e-wallet atau mobile banking Anda</li>
                                    <li>Pilih menu Scan QRIS atau QR Code</li>
                                    <li>Scan QR Code di atas</li>
                                    <li>Pastikan nominal sesuai: <strong>Rp <?php echo number_format($amount, 0, ',', '.'); ?></strong></li>
                                    <li>Lakukan pembayaran</li>
                                    <li>Saldo akan otomatis masuk setelah pembayaran berhasil</li>
                                </ol>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12 text-center">
                            <p style="color: #999; font-size: 12px;">
                                QRIS akan expired dalam 20 menit. Jika sudah expired, silakan buat transaksi baru.
                            </p>
                            <p style="color: #999; font-size: 12px;">
                                Transaction ID: <?php echo htmlspecialchars($trx_id); ?>
                            </p>
                        </div>
                    </div>
                    
                    <div class="row mt-4">
                        <div class="col-md-12 text-center">
                            <button type="button" class="btn btn-primary" id="btnCheckStatus" onclick="checkPaymentStatus()">
                                Cek Status Pembayaran
                            </button>
                            <a href="<?php echo $urlweb; ?>/m/account/deposit" class="btn btn-secondary">Kembali</a>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <div id="statusMessage" style="display: none;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let checkInterval = null;
let checkCount = 0;
const maxChecks = 120; // Maksimal 10 menit (120 x 5 detik)

function checkPaymentStatus() {
    // Prevent multiple intervals
    if (checkInterval) {
        clearInterval(checkInterval);
        checkInterval = null;
    }
    
    const btnCheckStatus = document.getElementById('btnCheckStatus');
    const statusMessage = document.getElementById('statusMessage');
    
    if (!btnCheckStatus || !statusMessage) {
        console.error('Elements not found');
        return;
    }
    
    btnCheckStatus.disabled = true;
    btnCheckStatus.textContent = 'Memeriksa...';
    statusMessage.style.display = 'block';
    statusMessage.innerHTML = '<div class="alert alert-info">Memeriksa status pembayaran...</div>';
    
    // Function untuk melakukan check
    function doCheck() {
        checkCount++;
        
        fetch('<?php echo $urlweb; ?>/function/check_qris_status.php?trx_id=<?php echo urlencode($trx_id); ?>')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Status check response:', data);
                
                if (data.success && data.status === 'success') {
                    if (checkInterval) {
                        clearInterval(checkInterval);
                        checkInterval = null;
                    }
                    statusMessage.innerHTML = '<div class="alert alert-success"><strong>Pembayaran Berhasil!</strong><br>Saldo Anda telah ditambahkan. Halaman akan di-refresh dalam 3 detik...</div>';
                    btnCheckStatus.disabled = true;
                    btnCheckStatus.textContent = 'Pembayaran Berhasil';
                    
                    // Clear session dan redirect
                    setTimeout(function() {
                        window.location.href = '<?php echo $urlweb; ?>/m/account/deposit?notif=success';
                    }, 3000);
                } else if (data.success && data.status === 'pending') {
                    statusMessage.innerHTML = '<div class="alert alert-warning">Menunggu pembayaran... (Cek ke-' + checkCount + ')</div>';
                    btnCheckStatus.disabled = false;
                    btnCheckStatus.textContent = 'Cek Status Pembayaran';
                } else {
                    statusMessage.innerHTML = '<div class="alert alert-info">Status: ' + (data.status || 'Pending') + '</div>';
                    btnCheckStatus.disabled = false;
                    btnCheckStatus.textContent = 'Cek Status Pembayaran';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                statusMessage.innerHTML = '<div class="alert alert-danger">Error memeriksa status. Silakan coba lagi.</div>';
                btnCheckStatus.disabled = false;
                btnCheckStatus.textContent = 'Cek Status Pembayaran';
            });
        
        // Stop checking setelah maxChecks
        if (checkCount >= maxChecks) {
            if (checkInterval) {
                clearInterval(checkInterval);
                checkInterval = null;
            }
            btnCheckStatus.disabled = false;
            btnCheckStatus.textContent = 'Cek Status Pembayaran';
            statusMessage.innerHTML = '<div class="alert alert-warning">Pemeriksaan otomatis dihentikan. Silakan klik tombol untuk mengecek secara manual.</div>';
        }
    }
    
    // Check pertama kali langsung
    doCheck();
    
    // Cek status setiap 5 detik
    checkInterval = setInterval(doCheck, 5000);
}

// Auto check setelah 10 detik
setTimeout(function() {
    checkPaymentStatus();
}, 10000);
</script>

<?php include "../footer.php"; ?>
