<?php
    $qrisData = $transactions->qris_code; 
    
    // Hitung waktu kadaluarsa: Waktu Transaksi Dibuat + 5 Menit
    $createdAt = \Carbon\Carbon::parse($transactions->created_at);
    $expiredAt = $createdAt->copy()->addMinutes(5);
    $now = \Carbon\Carbon::now();
    
    // Hitung sisa detik (Bisa minus jika sudah lewat)
    $remainingSeconds = $now->diffInSeconds($expiredAt, false);
    
    // Jika waktu sudah lewat dari 5 menit, paksa jadi 0
    if ($remainingSeconds <= 0) {
        $remainingSeconds = 0;
    }
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Checkout - QRIS Payment</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" type="image/x-icon" href="<?php echo e(asset('Content/QrisBayar/ATCPulsafav.ico')); ?>">
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('Content/qrisbayar.css')); ?>" />
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('Content/bootstrap.css')); ?>" />
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>

    <style>
        body { padding: 1em; background-color: #f8f9fa; }
        
        /* CSS Untuk Responsibilitas Gambar QRIS */
        .qr-container { 
            background: white; 
            padding: 15px; 
            border-radius: 15px; 
            display: inline-block; 
            box-shadow: 0 4px 6px rgba(0,0,0,0.1); 
            max-width: 100%; 
        }
        .qr-image { 
            width: 100%; 
            max-width: 300px; /* Maksimal besar di PC */
            height: auto; 
            border: 5px solid white; 
            border-radius: 10px; 
            object-fit: contain; 
        }
        
        .amount-text { font-size: 2rem; font-weight: bold; color: #000; }
        .timer-text { color: #dc3545; font-weight: bold; }
    </style>
</head>

<body>

    
    <div id="divExpired" class="container-fluid w-100 text-center pt-5" style="display: none;">
        <div class="row">
            <div class="col-12">
                <img src="https://cdni.iconscout.com/illustration/premium/thumb/boy-getting-payment-success-illustration-svg-download-png-13200752.png" alt="" width="300" style="max-width: 100%; height: auto;" />
            </div>
        </div>
        <div class="row pt-2">
            <div class="col-12">
                <h4 id="finalStatusTitle">Pembayaran sedang di Verifikasi.</h4>
            </div>
        </div>
        <div class="row">
            <div class="col-12">
                <h4 id="finalStatusSub">Mohon menunggu</h4>
            </div>
        </div>
        <div class="row pt-2">
            <div class="col-12">
                <p class="h6 expired_countdown"></p>
            </div>
        </div>
    </div>

    
    <div id="divBayar" class="container-fluid w-100 text-center pt-5">
        <div class="row mb-3">
            <div class="col-12">
                <img src="<?php echo e(asset('uploads/' . general()->logo)); ?>" alt="Logo" width="150" style="max-width: 100%; height: auto;">
            </div>
        </div>
        <div class="row">
            <div class="col-12">
                <h4 class="text-danger" style="font-size: 1.2rem;">Jangan tutup layar ini sebelum pembayaran terkonfirmasi</h4>
                <h6>Silakan Scan kode QRIS <?php echo e($transactions->transaction_by); ?> di bawah:</h6>
            </div>
        </div>

        <div class="row pt-3">
            <div class="col-12">
                <div class="qr-container">
                    <img id="qrImageDisplay" class="qr-image" src="<?php echo e($qrisData); ?>" alt="QRIS Code">
                </div>
            </div>
        </div>

        <div class="row pt-3">
            <div class="col-12">
                <div class="amount-text">IDR <?php echo e(number_format($transactions->total, 0, ',', '.')); ?></div>
                <p class="text-muted">Order ID: <?php echo e($transactions->trx_id); ?></p>
            </div>
        </div>

        <div class="row pt-2">
            <div class="col-12">
                <button type="button" id="SaveQR" class="btn btn-info shadow-sm" style="font-size: 0.85rem;">Download Kode QR</button>
                
            </div>
        </div>

        <div class="row pt-4">
            <div class="col-12">
                <p class="qr_timeout_timer timer-text"></p>
            </div>
        </div>

        <div class="row mt-3">
            <div class="col-12 border-top pt-3">
                <p style="font-size: 0.8rem" class="text-muted">Klik tombol di bawah jika Anda ingin membatalkan transaksi.</p>
                <button onclick="cancelPay()" class="btn btn-outline-danger btn-sm">Batalkan Transaksi</button>
            </div>
        </div>
    </div>

    <script>
        var isCancelled = false; // Flag anti-bentrok

        $(document).ready(function() {
            // Karena langsung pakai img tag, tidak perlu fungsi generate canvas jQuery di sini.
        });

        $('#SaveQR').click(function(e) {
            e.preventDefault();
            var imageUrl = $('#qrImageDisplay').attr('src');

            // Membuat elemen link <a> sementara
            var link = document.createElement('a');
            link.href = imageUrl;
            link.download = 'QRIS-<?php echo e($transactions->trx_id); ?>.png';
            link.target = '_blank'; // Fallback: Buka di tab baru jika browser menolak download langsung

            // Mengeksekusi klik secara sinkron agar tidak diblokir pop-up blocker
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // Opsional: Beri instruksi ke user jika browser menolak force-download
            setTimeout(function() {
                alert("Jika gambar tidak terunduh otomatis, gambar akan terbuka di halaman baru.\n\nSilakan Tekan Lama (di HP) atau Klik Kanan (di PC) pada gambar tersebut lalu pilih 'Simpan Gambar'.");
            }, 500);
        });

        // 2. LOGIKA COUNTDOWN SINKRON SERVER
        var expire_in_seconds = <?php echo e($remainingSeconds); ?>; 
        
        if (expire_in_seconds <= 0) {
            cancelAndRedirect();
        } else {
            var timer = setInterval(function () {
                var minutes = Math.floor(expire_in_seconds / 60);
                var seconds = expire_in_seconds % 60;
                var formattedSeconds = seconds < 10 ? '0' + seconds : seconds;
                
                $('.qr_timeout_timer').text('Kode QR akan kadaluarsa dalam ' + minutes + ' Menit ' + formattedSeconds + ' Detik');

                if (expire_in_seconds <= 0) {
                    clearInterval(timer);
                    cancelAndRedirect();
                }
                expire_in_seconds--;
            }, 1000);
        }

        // 3. FUNGSI AUTO CANCEL SAAT WAKTU HABIS
        function cancelAndRedirect() {
            if (isCancelled) return;
            isCancelled = true;
            
            $('.qr_timeout_timer').text('Waktu Habis!');
            alert("Waktu pembayaran habis. Transaksi otomatis dibatalkan.");
            
            var trx_id = "<?php echo e($transactions->trx_id); ?>";
            $.ajax({
                url: "/api/qr/cancel_pay/" + trx_id,
                type: "GET",
                success: function() {
                    window.location.replace("<?php echo e(route('account.deposit')); ?>");
                },
                error: function() {
                    window.location.replace("<?php echo e(route('account.deposit')); ?>");
                }
            });
        }

        // 4. AUTO CHECK STATUS PEMBAYARAN (POLLING)
        var checkStatusInterval = setInterval(function() {
            if (isCancelled) {
                clearInterval(checkStatusInterval);
                return;
            }

            var trx_id = "<?php echo e($transactions->trx_id); ?>";
            $.ajax({
                url: "/api/qr/pay_status/" + trx_id,
                type: "GET",
                success: function(response) {
                    if (response.status == 1) {
                        clearInterval(checkStatusInterval);
                        if(typeof timer !== 'undefined') clearInterval(timer);
                        ShowFinalPage("Pembayaran Berhasil!", "Saldo Anda akan segera bertambah.");
                    }
                }
            });
        }, 5000);

        // 5. FUNGSI BATALKAN TRANSAKSI MANUAL
        function cancelPay() {
            if(confirm("Apakah Anda yakin ingin membatalkan transaksi ini?")) {
                isCancelled = true; // Kunci semua proses JS yang sedang berjalan
                
                var trx_id = "<?php echo e($transactions->trx_id); ?>";
                $.ajax({
                    url: "/api/qr/cancel_pay/" + trx_id,
                    type: "GET",
                    beforeSend: function() {
                        $('.btn-outline-danger').text('Sedang membatalkan...').prop('disabled', true);
                    },
                    success: function(response) {
                        window.location.replace("<?php echo e(route('account.deposit')); ?>");
                    },
                    error: function() {
                        window.location.replace("<?php echo e(route('account.deposit')); ?>");
                    }
                });
            }
        }

        // 6. TAMPILAN AKHIR & REDIRECT SUCCESS
        function ShowFinalPage(title, sub) {
            isCancelled = true;
            $('#divBayar').hide();
            $('#divExpired').show();
            if(title) $('#finalStatusTitle').text(title);
            if(sub) $('#finalStatusSub').text(sub);

            var countdown = 5;
            var timer2 = setInterval(function() {
                $('.expired_countdown').text('Anda akan dialihkan dalam ' + countdown + ' Detik');
                if (countdown <= 0) {
                    clearInterval(timer2);
                    window.location.replace("<?php echo e(route('account.home')); ?>");
                }
                countdown--;
            }, 1000);
        }
        
        function extractQrisData(imageUrl) {
            // 1. Buat elemen gambar virtual
            var img = new Image();
            
            // Penting: Minta izin akses CORS agar canvas tidak diblokir browser
            img.crossOrigin = "Anonymous"; 
            
            img.onload = function() {
                // 2. Buat elemen canvas sementara
                var canvas = document.createElement("canvas");
                var context = canvas.getContext("2d");
                
                canvas.width = img.width;
                canvas.height = img.height;
                
                // 3. Gambar URL ke dalam canvas
                context.drawImage(img, 0, 0, img.width, img.height);
                
                // 4. Ambil data piksel gambar
                var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
                
                // 5. Baca menggunakan jsQR
                var code = jsQR(imageData.data, imageData.width, imageData.height, {
                    inversionAttempts: "dontInvert",
                });
                
                if (code) {
                    // BERHASIL! Data QRIS asli didapatkan
                    var qrisAsli = code.data;
                    console.log("Data QRIS Asli: ", qrisAsli);
                    
                    // Contoh penggunaan: Tampilkan di layar atau alert
                    alert("Berhasil ekstrak data QRIS:\n\n" + qrisAsli);
                    
                    // Atau letakkan di input/textarea jika user ingin meng-copy nya
                    // $('#qrisDataText').val(qrisAsli);
                    
                } else {
                    console.error("Gagal membaca QR Code dari gambar tersebut.");
                }
            };
            
            img.onerror = function() {
                console.error("Gagal memuat gambar. Ini biasanya karena diblokir oleh CORS (Cross-Origin).");
            };
        
            // Trigger pemuatan gambar
            img.src = imageUrl;
        }
    </script>
</body>
</html><?php /**PATH /www/wwwroot/website/sewa/dragon158/resources/views/frontend/desktop/pages/account/transactions/qr.blade.php ENDPATH**/ ?>