<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bangla QR Payment</title>
    <style>
        body{font-family:Arial,sans-serif;background:#f7f8fa;margin:0;padding:24px;color:#1f2937}
        .wrap{max-width:460px;margin:0 auto;background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:22px;text-align:center}
        .qr{word-break:break-all;border:1px dashed #9ca3af;border-radius:8px;padding:18px;margin:18px 0;background:#fafafa}
        .muted{color:#6b7280;font-size:14px}
        .danger{color:#b91c1c}
        .success{color:#047857}
        .status{border-radius:8px;background:#f3f4f6;margin:14px 0;padding:12px;font-size:14px}
        button{background:#0f766e;border:0;color:#fff;border-radius:8px;padding:11px 14px;font-weight:700;cursor:pointer}
        button:disabled{opacity:.65;cursor:not-allowed}
        a{color:#047857;text-decoration:none;font-weight:700}
    </style>
</head>
<body>
    <div class="wrap">
        <h2>Bangla QR Payment</h2>
        <p>Amount: {{ number_format((float) $transaction->amount, 2) }} {{ $transaction->currency }}</p>

        @if($transaction->qr_payload)
            @php($qrPayload = (string) $transaction->qr_payload)
            @if(preg_match('/^(https?:\/\/|data:image\/)/', $qrPayload))
                <div class="qr"><img src="{{ $qrPayload }}" alt="Bangla QR" style="max-width:100%;height:auto"></div>
            @else
                <div class="qr">{{ $qrPayload }}</div>
            @endif
            <p class="muted">Scan this QR from your bank or MFS app. Payment will be confirmed only after provider verification.</p>
            <div class="status">
                <strong>Payment status:</strong>
                <span id="payment-status">{{ str_replace('_', ' ', $transaction->status) }}</span>
                <div id="payment-message" class="muted" style="margin-top:6px">Waiting for provider confirmation...</div>
            </div>
            <button type="button" id="check-status">Check verified status</button>
        @else
            <p class="danger">Bangla QR provider API is not fully configured yet. This order has not been marked paid.</p>
            <p class="muted">{{ data_get($transaction->request_payload, 'message', 'Please configure official Bangla QR dynamic API credentials and endpoints.') }}</p>
        @endif

        @if($callback)
            <p><a href="{{ $callback }}">Back to order without payment confirmation</a></p>
        @endif
    </div>
    @if($transaction->qr_payload)
        <script>
            (function () {
                var statusUrl = @json(route('bangla-qr.status', $transaction));
                var callbackUrl = @json($callback);
                var statusEl = document.getElementById('payment-status');
                var messageEl = document.getElementById('payment-message');
                var checkBtn = document.getElementById('check-status');
                var attempts = 0;
                var maxAttempts = 120;

                function callbackWithStatus(status) {
                    if (!callbackUrl) {
                        return null;
                    }
                    var separator = callbackUrl.indexOf('?') === -1 ? '?' : '&';
                    return callbackUrl + separator + 'status=' + encodeURIComponent(status);
                }

                function setState(text, message, className) {
                    if (statusEl) {
                        statusEl.textContent = text;
                        statusEl.className = className || '';
                    }
                    if (messageEl) {
                        messageEl.textContent = message || '';
                    }
                }

                function checkStatus(manual) {
                    attempts += 1;
                    if (checkBtn) {
                        checkBtn.disabled = true;
                    }
                    fetch(statusUrl, {headers: {'Accept': 'application/json'}})
                        .then(function (response) { return response.json(); })
                        .then(function (data) {
                            var status = String(data.status || '').toLowerCase();
                            if (status === 'paid' && data.verified_by_system) {
                                setState('paid', 'Payment verified by provider. Redirecting...', 'success');
                                var successUrl = callbackWithStatus('success');
                                if (successUrl) {
                                    window.location.href = successUrl;
                                }
                                return;
                            }

                            if (status === 'paid' && data.manually_verified) {
                                setState('paid', 'Payment approved from manual verification queue. Redirecting...', 'success');
                                var manualSuccessUrl = callbackWithStatus('success');
                                if (manualSuccessUrl) {
                                    window.location.href = manualSuccessUrl;
                                }
                                return;
                            }

                            if (['failed', 'expired', 'cancelled', 'canceled', 'amount_mismatch'].indexOf(status) !== -1) {
                                setState(status, 'Payment was not verified. Please try another payment method.', 'danger');
                                return;
                            }

                            setState(status || 'pending', data.message || 'Payment is still waiting for provider confirmation.', '');
                            if (attempts < maxAttempts && !manual) {
                                window.setTimeout(function () { checkStatus(false); }, 5000);
                            }
                        })
                        .catch(function () {
                            setState('pending', 'Unable to check status right now. Retrying...', '');
                            if (attempts < maxAttempts && !manual) {
                                window.setTimeout(function () { checkStatus(false); }, 7000);
                            }
                        })
                        .finally(function () {
                            if (checkBtn) {
                                checkBtn.disabled = false;
                            }
                        });
                }

                if (checkBtn) {
                    checkBtn.addEventListener('click', function () { checkStatus(true); });
                }
                window.setTimeout(function () { checkStatus(false); }, 3000);
            })();
        </script>
    @endif
</body>
</html>
