@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-12 col-md-offset-0">
            <div class="panel panel-default">
                <div class="panel-heading">Checkout for Bidder #{{ $bidder->bidder_assigned_number }}</div>

                <div class="panel-body">
                    <h4>Total Amount Due: ${{ number_format($total_cost, 2) }}</h4>
                    <hr>
                    
                    <div id="checkout-container" style="height: 100vh; overflow: hidden;">
                        <div class="text-center">
                            <p>Loading secure checkout...</p>
                            <div class="spinner-border" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                        </div>
                    </div>

                    <hr>
                    <div class="text-center">
                        <a href="/mywinnings?bidder_number={{ $bidder->bidder_assigned_number }}" class="btn btn-default">Cancel and Return</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://checkout.north.com/checkout.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', async () => {
        const bidderId = "{{ $bidder->idbidders }}";
        const csrfToken = "{{ csrf_token() }}";

        try {
            // Create a checkout session
            const response = await fetch(`/north/session/${bidderId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                }
            });

            const data = await response.json();
            console.log('North Session Response:', data);

            if (data.error) {
                document.getElementById('checkout-container').innerHTML = `<div class="alert alert-danger">${data.error}</div>`;
                return;
            }

            const sessionToken = data.sessionToken;
            if (!sessionToken) {
                document.getElementById('checkout-container').innerHTML = `<div class="alert alert-danger">Invalid session token received from server.</div>`;
                return;
            }

            // Initialize North Checkout
            // The global 'checkout' object is provided by checkout.js
            console.log('Mounting checkout with token:', sessionToken);
            await checkout.mount(sessionToken, 'checkout-container');

            const handleCompletion = (result) => {
                console.log('Payment complete event received:', result);
                // Redirect to verify the payment on the server
                window.location.href = `/north/verify/${bidderId}?sessionToken=${sessionToken}`;
            };

            // Handle completion
            checkout.onPaymentComplete(handleCompletion);
            
            // Support for possible variations in event names
            if (typeof checkout.onPaymentSuccess === 'function') {
                checkout.onPaymentSuccess(handleCompletion);
            }

            // Handle errors
            if (typeof checkout.onPaymentError === 'function') {
                checkout.onPaymentError((error) => {
                    console.error('Payment Error:', error);
                    // Don't clear the container, just prepend the error
                    const errorDiv = document.createElement('div');
                    errorDiv.className = 'alert alert-danger';
                    errorDiv.innerHTML = `<strong>Payment Error:</strong> ${error.message || 'An error occurred during payment.'}`;
                    document.querySelector('.panel-body').prepend(errorDiv);
                });
            }

            // Show a fallback button after a short delay to allow for manual verification if the redirect fails
            setTimeout(() => {
                const fallbackDiv = document.createElement('div');
                fallbackDiv.className = 'text-center';
                fallbackDiv.style.marginTop = '20px';
                fallbackDiv.innerHTML = `
                    <p class="text-muted">Already completed your payment but still on this page?</p>
                    <a href="/north/verify/${bidderId}?sessionToken=${sessionToken}" class="btn btn-info">Verify Payment Status</a>
                `;
                document.querySelector('.panel-body').appendChild(fallbackDiv);
            }, 5000);

        } catch (error) {
            console.error('Checkout Error:', error);
            document.getElementById('checkout-container').innerHTML = '<div class="alert alert-danger">An error occurred while initializing checkout. Please try again.</div>';
        }
    });
</script>
@endsection
