@extends('components.layouts.base')

@section('content')
<div class="container mx-auto px-4 py-8">
    <div class="max-w-md mx-auto bg-white rounded-lg shadow-md p-6">
        <h1 class="text-2xl font-bold text-center mb-6">Pembayaran</h1>

        <div class="mb-4">
            <p class="text-gray-600">Order ID: <span class="font-semibold">{{ $order->id }}</span></p>
            <p class="text-gray-600">Transaction ID: <span class="font-semibold">{{ $transactionId }}</span></p>
        </div>

        <button id="pay-button" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-4 rounded-lg transition duration-200">
            Bayar Sekarang
        </button>
    </div>
</div>

<script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="{{ config('services.midtrans.client_key') }}"></script>
<script type="text/javascript">
document.getElementById('pay-button').onclick = function(){
    snap.pay('{{ $snapToken }}', {
        onSuccess: function(result){
            console.log('Payment success:', result);

            // Kirim data ke server
            fetch('{{ route('payment.success') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify(result)
            }).then(response => {
                if (response.ok) {
                    window.location.href = '{{ route('payment.success') }}?order_id=' + result.order_id;
                }
            });
        },

        onPending: function(result){
            console.log('Payment pending:', result);

            fetch('{{ route('payment.pending') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify(result)
            }).then(response => {
                if (response.ok) {
                    window.location.href = '{{ route('payment.pending') }}?order_id=' + result.order_id;
                }
            });
        },

        onError: function(result){
            console.log('Payment error:', result);

            fetch('{{ route('payment.error') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify(result)
            }).then(response => {
                if (response.ok) {
                    window.location.href = '{{ route('payment.error') }}?order_id=' + result.order_id;
                }
            });
        }
    });
};
</script>
@endsection
