@extends('tablar::page')

@section('content')
<style>
    #checkout-container {
        height: 900px;
        width: 100%;
        margin-top: 20px;
        overflow: hidden;
    }
    #checkout-container iframe {
        width: 100% !important;
        height: 100% !important;
        border: none !important;
    }
</style>
<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col">
                <h2 class="page-title">Checkout</h2>
            </div>
        </div>
    </div>
</div>
<div class="page-body">
    <div class="container-xl">
        <div class="card">
            <div class="card-body">
                <div id="checkout-container">
                    <div class="text-center">
                        <p>Loading secure checkout...</p>
                        <div class="spinner-border" role="status"></div>
                    </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 {
            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.</div>`;
                return;
            }

            await checkout.mount(sessionToken, 'checkout-container');

            const handleCompletion = (result) => {
                window.location.href = `/north/verify/${bidderId}?sessionToken=${sessionToken}`;
            };

            checkout.onPaymentComplete(handleCompletion);
            if (typeof checkout.onPaymentSuccess === 'function') {
                checkout.onPaymentSuccess(handleCompletion);
            }
        } catch (error) {
            console.error('Checkout Error:', error);
            document.getElementById('checkout-container').innerHTML = '<div class="alert alert-danger">An error occurred. Please try again.</div>';
        }
    });
</script>
@endsection
@push('js')
@endpush
