@php
$amount = request('amount', $amount ?? 0);
$transactionId = request('invoice_number', $transactionId ?? 'HILNEX' . time() . rand(100, 999));
$currentLocale = app()->getLocale();
$otherLocale = ($currentLocale === 'en') ? 'bn' : 'en';
$otherLocaleLabel = $currentLocale === 'en' ? 'বাংলা' : 'English';

// Manually build the language switch URL to preserve all query parameters
$langSwitchUrl = LaravelLocalization::getLocalizedURL($otherLocale, url()->current() . '?' .
http_build_query(request()->query()), [], true);
@endphp
@extends('layouts.pay')

@section('content')
@push('styles')
<style>
@layer utilities {

    /* Custom shadow
    .custom-shadow {
        box-shadow: 0 4px 15px -2px rgba(255, 255, 255, 0.3),
            0 2px 8px -3px rgba(255, 255, 255, 0.2);
    } */
}
</style>

@push('scripts')


<div class="min-h-screen flex flex-col items-center justify-center  sm:p-4">
    <div class="relative w-full max-w-sm sm:max-w-lg">
        {{-- Merchant Info - Positioned to overlap --}}
        <div
            class="absolute top-1 left-1/2 -translate-x-1/2 -translate-y-[40%] sm:-translate-y-1/2 flex flex-col items-center justify-center text-center z-50">
            <div class="w-30 h-30 sm:w-36 sm:h-36 rounded-full flex items-center justify-center custom-shadow">
                <img src="{{ $brand && $brand->brand_logo ? url($brand->brand_logo) : asset('images/merchant-logo.jpg') }}"
                    alt="{{ $brand->name ?? __('Default Gateway') }}"
                    class="w-[85%] h-[85%] object-cover rounded-full border-2 ">
            </div>
        </div>

        {{-- Payment Box --}}
        <div class="payment-container w-full bg-[#80808014] backdrop-blur-xl shadow-1xl border border-white/20 notranslate flex flex-col overflow-hidden rounded-xl"
            style="max-height: 90vh;">
            <div
                class="payment-header flex justify-between items-center p-4 sm:p-6 bg-black text-white relative z-40 flex-shrink-0 pt-8 sm:pt-14 w-full">
                @php
                $dashboardUrl = url()->previous(); // Default back URL
                if (Auth::check()) {
                $dashboardUrl = Auth::user()->role === 'admin' ? route('admin.dashboard') : route('user.dashboard');
                }
                @endphp
                <a href="{{ url('/') }}" id="home-btn" class="text-white hover:scale-110 transition-transform"
                    title="Go to Homepage">
                    <i class="fas fa-home text-xl"></i>
                </a>
                <a href="{{ $dashboardUrl }}" id="back-btn"
                    class="w-10 h-10 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/30 transition-all duration-300"
                    title="{{ __('Back') }}">
                    <i class="fas fa-arrow-left"></i>
                </a>
            </div>

            <!-- Scrollable Content Area -->
            <div id="scrollable-content" class="overflow-y-auto transition-all duration-500 ease-in-out flex-grow">
                <div
                    class="nav-tabs flex items-center bg-white/90 backdrop-blur-md p-1 sm:p-2 mx-2 sm:mx-6 mt-2 rounded-lg shadow-sm border border-gray-100 sticky top-0 z-10">
                    @php
                    $tabs = [
                    ['key' => 'payment', 'icon' => 'fa-mobile-alt', 'label' => __('Payment'), 'translate_key' =>
                    'tab_payment'],
                    ['key' => 'details', 'icon' => 'fa-receipt', 'label' => __('Details'), 'translate_key' =>
                    'tab_details'],
                    ['key' => 'support', 'icon' => 'fa-headset', 'label' => __('Support'), 'translate_key' =>
                    'tab_support'],
                    ];
                    @endphp
                    <div class="flex-grow flex space-x-1 sm:space-x-2">
                        @foreach($tabs as $index => $tab)
                        <div class="nav-tab text-gray-600 hover:bg-gray-100 flex-grow text-center py-2 sm:py-3 rounded-md font-medium cursor-pointer flex items-center justify-center gap-2 transition-all duration-300 transform hover:scale-105"
                            data-tab="{{ $tab['key'] }}" title="{{ $tab['label'] }}"
                            data-translate-key="{{ $tab['translate_key'] }}">
                            <i class="fas {{ $tab['icon'] }} text-sm sm:text-base"></i>
                            <span class="text-xs sm:text-sm">{{ $tab['label'] }}</span>
                        </div>
                        @endforeach
                    </div>
                    {{-- Language Switcher --}}
                    <a href="{{ $langSwitchUrl }}"
                        class="text-gray-500 hover:text-indigo-600 font-medium cursor-pointer flex items-center gap-2 transition-all duration-300 text-xs px-3"
                        title="{{ __('Switch Language') }}" id="language-switcher">
                        <i class="fas fa-language text-base"></i>
                        <span class="hidden sm:inline">{{ $otherLocaleLabel }}</span>
                    </a>
                </div>

                <!-- Tab Content -->
                <div class="tab-content p-3 sm:p-6 space-y-6 w-full">
                    <!-- Payment Tab -->
                    <div class="tab-panel hidden" id="payment-panel">
                        @if ($error ?? false)
                        <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 rounded-r-lg mb-6 animate-pulse"
                            role="alert">
                            <p class="font-bold flex items-center gap-2">
                                <i class="fas fa-exclamation-triangle"></i> <span
                                    data-translate-key="payment_error_title">{{ __('Payment Error') }}</span>
                            </p>
                            <p class="text-sm mt-1" data-translate-key="payment_error_message">{{ $error }}</p>
                        </div>
                        @endif

                        <h3 class="text-lg font-bold text-[#ffffff] mb-5 flex items-center gap-2">
                            <i class="fas fa-credit-card text-[#ffffff]"></i> <span
                                data-translate-key="select_payment_method">{{ __('Select Payment Method') }}</span>
                        </h3>

                        @php
                        $mobileWallets = ['bkash', 'nagad', 'rocket', 'upay', 'cellfin', 'tap', 'okwallet', 'surecash',
                        'mcash', 'mycash', 'ipay'];
                        $bankWallets = ['ibl', 'abbank', 'citybank', 'sonali', 'dbbl', 'basic', 'ebl', 'bbrac', 'basia',
                        'agrani', 'jamuna', 'ific'];
                        $cryptoWallets = ['binance', 'payeer'];
                        @endphp
                        <div class="payment-methods grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 sm:gap-4 mb-6">
                            @forelse ($activeWallets ?? [] as $wallet)
                            @if(in_array($wallet->wallet_type, $mobileWallets) && $wallet->status == 1)
                            @foreach(['personal', 'agent', 'merchant', 'payment'] as $type)
                            @if($wallet->{'is_' . $type . '_active'})
                            <div class="payment-method group relative border border-gray-200 rounded-xl sm:p-4 text-center cursor-pointer transition-all duration-300 hover:border-indigo-600 hover:shadow-xl hover:-translate-y-2 bg-white hover:bg-gradient-to-br hover:from-indigo-50 hover:to-purple-50"
                                data-method="{{ $wallet->wallet_type }}-{{ $type }}">
                                <img src="{{ asset('assets/image/bank-img/' . $wallet->wallet_type . '.svg') }}"
                                    alt="{{ __(ucfirst($wallet->wallet_type)) }}"
                                    class="h-8 w-8 sm:h-8 mx-auto mb-2 transition-transform group-hover:scale-110">
                                <div class="font-bold text-gray-800 text-[10px] sm:text-xs">{{ __(ucfirst($wallet->wallet_type)) }}
                                </div>
                                <div
                                    class="absolute top-1 right-1 bg-gradient-to-r from-indigo-600 to-purple-600 text-white text-[10px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wider shadow-md animate-pulse">
                                    {{ __(strtoupper($type)) }}
                                </div>
                            </div>
                            @endif
                            @endforeach
                            @elseif((in_array($wallet->wallet_type, $bankWallets) || in_array($wallet->wallet_type,
                            $cryptoWallets)) && $wallet->status == 1)
                            <div class="payment-method group relative border border-gray-200 rounded-lg p-2 sm:p-4 text-center cursor-pointer transition-all duration-300 hover:border-indigo-600 hover:shadow-xl hover:-translate-y-2 bg-white hover:bg-gradient-to-br hover:from-indigo-50 hover:to-purple-50"
                                data-method="{{ $wallet->wallet_type }}"
                                title="{{ __(ucfirst(str_replace('_', ' ', $wallet->wallet_type))) }}">
                                @php
                                $svgPath = 'assets/image/bank-img/' . $wallet->wallet_type . '.svg';
                                $pngPath = 'assets/image/bank-img/' . $wallet->wallet_type . '.png';
                                $defaultPath = 'assets/image/bank-img/default.svg';
                                $imagePath = file_exists(public_path($svgPath)) ? $svgPath :
                                (file_exists(public_path($pngPath)) ? $pngPath : $defaultPath);
                                @endphp
                                <img src="{{ asset($imagePath) }}" alt="{{ ucfirst($wallet->wallet_type) }}"
                                    class="h-12 sm:h-16 mx-auto mb-2 transition-transform group-hover:scale-110">
                                <div class="font-bold text-gray-800 text-[10px] sm:text-xs">
                                    {{ __(ucfirst(str_replace('_', ' ', $wallet->wallet_type))) }}</div>
                                <div
                                    class="absolute top-1 right-1 text-white text-[10px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wider shadow-md
                                                        {{ in_array($wallet->wallet_type, $bankWallets) ? 'bg-green-600' : 'bg-yellow-600' }}">
                                    {{ in_array($wallet->wallet_type, $bankWallets) ? __('BANK') : __('CRYPTO') }}
                                </div>
                            </div>
                            @endif
                            @empty
                            <div class="col-span-3 text-center text-gray-500 py-8">
                                <i class="fas fa-ban text-4xl mb-2"></i>
                                <p>{{ __('No payment methods available.') }}</p>
                            </div>
                            @endforelse
                        </div>

                        <!-- Transaction Summary -->
                        <div
                            class="transaction-details bg-gradient-to-r from-indigo-50 to-purple-50 rounded-lg p-5 border border-indigo-100">
                            <h3 class="text-lg font-bold text-gray-800 flex items-center gap-2 mb-4">
                                <i class="fas fa-file-invoice-dollar text-indigo-600"></i> <span
                                    data-translate-key="transaction_summary">{{ __('Transaction Summary') }}</span>
                            </h3>
                            <div class="space-y-3">
                                <div class="flex justify-between">
                                    <span class="text-gray-600"
                                        data-translate-key="invoice_to">{{ __('Invoice To:') }}</span>
                                    <span
                                        class="font-semibold text-gray-800">{{ $brand->name ?? __('BD Better Pay') }}</span>
                                </div>
                                <div class="flex justify-between text-xl sm:text-2xl font-bold text-indigo-600">
                                    <span data-translate-key="payable">{{ __('Payable:') }}</span>
                                    <span>৳{{ number_format($amount ?? 0, 2) }}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Details Tab -->
                    <div class="tab-panel hidden" id="details-panel">
                        <div class="w-full">
                            @include('frontend.transaction-details', [
                            'brandName' => $brand->name ?? __('Default Gateway'),
                            'transactionId' => $transactionId,
                            'amount' => $amount ?? 0,
                            'totalPayable' => $amount ?? 0,
                            ])
                        </div>
                    </div>

                    <!-- Support Tab -->
                    <div class="tab-panel hidden" id="support-panel">
                        <div class="w-full">
                            <h3 class="text-lg font-bold text-gray-800 mb-5" data-translate-key="support_title">
                                {{ __("We're Here to Help") }}</h3>
                            <div class="space-y-3">
                                @php
                                $supports = [
                                ['icon' => 'fa-envelope', 'label' => __('Email Us'), 'value' => $brand->support_mail ??
                                null, 'href' => 'mailto:'],
                                ['icon' => 'fa-comments', 'label' => __('Live Chat'), 'value' => true, 'href' => '#'],
                                ];
                                @endphp
                                @foreach($supports as $support)
                                <a href="{{ $support['value'] ? $support['href'] . $support['value'] : '#' }}"
                                    {{ $support['value'] ? '' : 'onclick="return false;"' }}
                                    class="support-option flex items-center p-3 sm:p-4 bg-gradient-to-r from-gray-50 to-gray-100 rounded-lg hover:from-indigo-50 hover:to-purple-50 transition-all duration-300 transform hover:scale-105 {{ !$support['value'] ? 'opacity-50 cursor-not-allowed' : '' }}">
                                    <div
                                        class="w-12 h-12 rounded-full bg-black text-white flex items-center justify-center text-xl shadow-lg">
                                        <i class="fas {{ $support['icon'] }}"></i>
                                    </div>
                                    <div class="ml-4 font-medium text-gray-800">
                                        {{ $support['label'] }}{{ $support['value'] && !str_starts_with($support['icon'], 'fa-comments') ? ': ' . $support['value'] : '' }}
                                    </div>
                                </a>
                                @endforeach
                            </div>

                            <div
                                class="mt-6 bg-gradient-to-r from-indigo-50 to-purple-50 rounded-lg p-5 border border-indigo-100">
                                <!-- <h3 class="font-bold text-gray-800 flex items-center gap-2 mb-3">
                                    <i class="fas fa-clock text-indigo-600"></i> <span
                                        data-translate-key="support_hours">{{ __('Support Hours') }}</span>
                                </h3> -->
                                <div class="text-sm space-y-1 text-gray-700">
                                    <div class="flex justify-between"><span
                                            data-translate-key="sun_thu">{{ __('Sun - Thu:') }}</span> <span
                                            class="font-medium">9:00 AM - 11:00 PM</span></div>
                                    <div class="flex justify-between"><span
                                            data-translate-key="fri_sat">{{ __('Fri - Sat:') }}</span> <span
                                            class="font-medium">10:00 AM - 8:00 PM</span></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Footer -->
            <div
                class="payment-footer bg-black text-white p-4 sm:p-6 flex flex-col sm:flex-row justify-between items-center gap-4 z-10 flex-shrink-0">
                <div class="secure-badge flex items-center gap-2 text-xs sm:text-sm font-medium">
                    <i class="fas fa-shield-alt animate-pulse"></i>
                    <span data-translate-key="ssl_encrypted">{{ __('256-bit SSL Encrypted By Team Hilnex.') }}</span>
                </div>
                <!-- <div class="pay-amount font-bold text-lg sm:text-xl order-first sm:order-none">
                    <span data-translate-key="pay_btn_prefix">{{ __('Pay') }}</span>
                    ৳{{ number_format($amount ?? 0, 2) }}
                </div> -->
                <button id="pay-now-btn"
                    class="pay-button w-full sm:w-auto bg-white text-black px-8 py-3 rounded-lg font-bold flex items-center justify-center gap-2 hover:shadow-xl hover:scale-105 transition-all duration-300">
                    <i class="fas fa-lock"></i>
                    <!-- <span data-translate-key="pay_now">{{ __('Pay Now') }}</span> -->
                    <span data-translate-key="pay_now"> ৳{{ number_format($amount ?? 0, 2) }}</span>
                </button>
            </div>

            {{-- Hidden bKash button that will be triggered programmatically --}}
            <button id="bKash_button" class="hidden"></button>
        </div>
    </div>

    {{-- Copyright Footer --}}
    <footer class="w-full max-w-lg pt-6 pb-4 text-white/60 text-xs z-20 text-center">
        <div class="flex items-center justify-center gap-2 mb-2 opacity-80">
            <img src="{{ asset('assets/image/hilnex-logo3.png') }}" alt="HilnexPay Logo" class="h-10">
        </div>
        <p>&copy; {{ date('Y') }} HilnexPay. <span
                data-translate-key="all_rights_reserved">{{ __('All Rights Reserved.') }}</span></p>
    </footer>
</div>

@endsection

@push('scripts')
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script>
// Pass PHP variables to JavaScript
const BRAND_ID = '{{ $brand->id ?? null }}';
const AMOUNT = '{{ $amount ?? 0 }}';
const TRANSACTION_ID = '{{ $transactionId }}';
document.addEventListener('DOMContentLoaded', function() {
    // UI handlers
    const tabs = document.querySelectorAll('.nav-tab');
    const panels = document.querySelectorAll('.tab-panel');
    const paymentMethods = document.querySelectorAll('.payment-method');
    const payButton = document.getElementById('pay-now-btn');
    const backBtn = document.getElementById('back-btn');
    const homeBtn = document.getElementById('home-btn');
    const container = document.querySelector('.payment-container');
    const scrollableContent = document.getElementById('scrollable-content');
    let selectedMethod = null;
    let isProcessing = false; // Global processing lock

    // Activate the first tab and panel by default
    if (tabs.length > 0 && panels.length > 0) {
        tabs[0].classList.add('active', 'bg-black', 'text-white', 'shadow-lg');
        tabs[0].classList.remove('text-gray-600', 'hover:bg-gray-100');
        panels[0].classList.remove('hidden');
    }

    // Tab switching logic
    tabs.forEach(t => {
        t.addEventListener('click', function(e) {
            const key = t.dataset.tab;

            // Skip if processing
            if (isProcessing) return;

            if (key === 'translate') {
                e.preventDefault();
                const target = (currentLang === 'en') ? 'bn' : 'en';
                setLanguage(target);
                return;
            }

            tabs.forEach(tab => {
                tab.classList.remove('active', 'bg-black', 'text-white', 'shadow-lg');
                tab.classList.add('text-gray-600', 'hover:bg-gray-100');
            });
            panels.forEach(p => p.classList.add('hidden'));

            this.classList.add('active', 'bg-black', 'text-white', 'shadow-lg');
            this.classList.remove('text-gray-600', 'hover:bg-gray-100');

            const panel = document.getElementById(key + '-panel');
            if (panel) panel.classList.remove('hidden');
        });
    });

    // Close button handler
    function preventNavigationIfProcessing(event) {
        if (isProcessing) {
            event.preventDefault();
            console.log("Action prevented: A payment is currently processing.");
        }
    }

    if (backBtn) {
        backBtn.addEventListener('click', preventNavigationIfProcessing);
    }

    if (homeBtn) {
        homeBtn.addEventListener('click', preventNavigationIfProcessing);
    }

    // Payment method selection
    paymentMethods.forEach(method => {
        method.addEventListener('click', function(e) {

            // Prevent multiple clicks
            if (isProcessing) return;

            selectedMethod = this.dataset.method;
            const methodParts = selectedMethod.split('-');
            const gatewayType = methodParts.length > 1 ? methodParts[1] : null;

            // Handle bKash client-side checkout directly
            if (selectedMethod.startsWith('bkash-') && gatewayType === 'merchant') {
                console.log('Initiating bKash client-side payment...');
                $('#bKash_button').trigger('click'); // This will trigger the bKash.init() flow
                return; // Stop further execution for bKash merchant
            }

            // Set processing state
            isProcessing = true;

            // Handle bKash payment gateway
            if (selectedMethod.startsWith('bkash-')) {
                console.log('Initiating bKash payment...');
                $('#bKash_button').trigger('click');
                return;
            }

            // Show loading state for other payment methods
            if (payButton) payButton.disabled = true;
            const originalContent = this.innerHTML;
            this.innerHTML =
                `<div class="flex justify-center items-center h-full"><i class="fas fa-spinner fa-spin text-2xl text-indigo-600"></i></div>`;

            // Determine action based on gateway type
            let formAction = "{{ route('payment.redirect') }}";
            let useBrandKey = true;

            // All non-bkash-merchant flows will use the server-side redirect

            // Create and submit form
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = formAction;

            const csrfInput = document.createElement('input');
            csrfInput.type = 'hidden';
            csrfInput.name = '_token';
            csrfInput.value = '{{ csrf_token() }}';
            form.appendChild(csrfInput);

            const inputs = {
                amount: "{{ $amount ?? 0 }}",
                brand_id: BRAND_ID,
                method: selectedMethod,
                system_trx_id: "{{ $transactionId }}",
            };

            if (useBrandKey) {
                inputs.brand_key = "{{ $brand->brand_key ?? request('brand_key') ?? '' }}";
            }

            for (const name in inputs) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = name;
                input.value = inputs[name];
                form.appendChild(input);
            }

            document.body.appendChild(form);
            form.submit();
        });
    });

    // Pay Now button handler
    if (payButton) {
        payButton.addEventListener('click', function() {
            if (isProcessing) {
                console.log('Payment already processing, please wait...');
                return;
            }

            if (!selectedMethod) {
                alert("{{ __('Please select a payment method.') }}");
                return;
            }

            // Find and click the selected method
            const selectedElement = document.querySelector(
                `.payment-method[data-method="${selectedMethod}"]`);
            if (selectedElement) {
                selectedElement.click();
            }
        });
    }

    // Reset processing state function (call this when payment flow completes)
    window.resetPaymentState = function() {
        isProcessing = false;
        if (payButton) payButton.disabled = false;

        // Reset all payment method buttons
        paymentMethods.forEach(method => {
            const originalContent = method.getAttribute('data-original-content');
            if (originalContent) {
                method.innerHTML = originalContent;
            }
        });
    };

});
</script>
<!-- bKash Checkout Script -->
<script id="bkash-script" src="https://scripts.pay.bka.sh/versions/1.2.0-beta/checkout/bKash-checkout.js"></script>
<script>
$(document).ready(function() {
    let bKashInitialized = false;

    // Store original button content
    document.querySelectorAll('.payment-method').forEach(method => {
        method.setAttribute('data-original-content', method.innerHTML);
    });

    // Check if BRAND_ID is valid before allowing bKash initialization
    if (!BRAND_ID) {
        console.error('bKash payment cannot be initialized: Brand ID is missing or invalid.');
        // Optionally, disable bKash payment methods or show an error to the user
        $('.payment-method[data-method^="bkash-"]').each(function() {
            $(this).addClass('opacity-50 cursor-not-allowed').off('click').attr('title',
                'Brand not configured for bKash');
        });
        return; // Prevent further bKash script execution if brand ID is missing
    }

    $('#bKash_button').on('click', function() {
        if (bKashInitialized) {
            bKash.reconfigure({
                paymentRequest: {
                    amount: AMOUNT,
                    intent: 'sale',
                    currency: 'BDT',
                    merchantInvoiceNumber: TRANSACTION_ID
                }
            });
            bKash.create().onSuccess({});
            return;
        }

        // Show loading state
        var payButton = $('#pay-now-btn');
        var originalButtonText = payButton.html();
        payButton.html('<i class="fas fa-spinner fa-spin"></i> {{ __("Initializing...") }}').prop(
            'disabled', true);

        try {
            bKash.init({
                paymentMode: 'checkout',
                paymentRequest: {
                    amount: AMOUNT,
                    intent: 'sale',
                    currency: 'BDT',
                    merchantInvoiceNumber: TRANSACTION_ID
                },
                createRequest: function(request) {
                    console.log('bKash createRequest called');

                    $.ajax({
                        url: "{{ route('payment.client.create') }}",
                        type: 'POST',
                        data: { // Use the JavaScript variables here
                            amount: AMOUNT,
                            invoice: TRANSACTION_ID,
                            brand_id: BRAND_ID,
                            _token: '{{ csrf_token() }}'
                        },
                        success: function(data) {
                            console.log('bKash create response:', data);
                            if (data && data.paymentID) {
                                bKash.create().onSuccess(data);
                            } else {
                                var errorMsg = data.errorMessage || data
                                    .error || 'Failed to create bKash payment.';
                                alert(errorMsg);
                                bKash.create().onError();
                                window.resetPaymentState();
                                payButton.html(originalButtonText).prop(
                                    'disabled', false);
                            }
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            console.error('bKash Create Request Failed:',
                                jqXHR);
                            let errorMessage =
                                'An error occurred while creating the payment. Please try again.';
                            if (jqXHR.responseJSON && jqXHR.responseJSON
                                .error) {
                                errorMessage = jqXHR.responseJSON.error;
                            } else if (jqXHR.responseJSON && jqXHR.responseJSON
                                .message) {
                                errorMessage += '\nDetails: ' + jqXHR
                                    .responseJSON.message;
                            }
                            alert(errorMessage);
                            bKash.create().onError();
                            window.resetPaymentState();
                            payButton.html(originalButtonText).prop('disabled',
                                false);
                        }
                    });
                },
                executeRequestOnAuthorization: function() {
                    console.log('bKash executeRequestOnAuthorization called');

                    $.ajax({
                        url: "{{ route('payment.client.execute') }}",
                        type: 'POST',
                        data: {
                            paymentID: bKash.data.paymentID,
                            brand_id: BRAND_ID,
                            _token: '{{ csrf_token() }}'
                        },
                        success: function(data) {
                            console.log('bKash execute response:', data);
                            if (data && data.transactionStatus ===
                                'Completed') {
                                // Payment successful
                                // Pass both trxID and our internal transaction_id to the success page
                                window.location.href =
                                    "{{ route('payment.success') }}?trxID=" +
                                    data.trxID + "&transaction_id=" + data
                                    .internal_transaction_id;
                            } else {
                                var errorMsg = data.errorMessage || data
                                    .statusMessage ||
                                    'Payment execution failed.';
                                alert(errorMsg);
                                bKash.execute().onError();
                                window.resetPaymentState();
                            }
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            console.error('bKash Execute Request Failed:',
                                jqXHR);
                            let errorMessage =
                                'An error occurred during payment execution. Please check your transaction history or try again.';
                            if (jqXHR.responseJSON && jqXHR.responseJSON
                                .error) {
                                errorMessage = jqXHR.responseJSON.error;
                            }
                            alert(errorMessage);
                            bKash.execute().onError();
                            window.resetPaymentState();
                        }
                    });
                },
                onClose: function() {
                    console.log('bKash popup closed');
                    window.resetPaymentState();
                    payButton.html(originalButtonText).prop('disabled', false);
                }
            });

            bKashInitialized = true;
        } catch (error) {
            console.error('bKash initialization error:', error);
            alert('Failed to initialize bKash payment. Please try again.');
            window.resetPaymentState();
            payButton.html(originalButtonText).prop('disabled', false);
        }
    });
});
</script>
@endpush