<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
document.getElementById('payment-form').addEventListener('submit', function(e) {
    const selectedGateway = document.querySelector('input[name="payment_gateway"]:checked').value;
    
    if (selectedGateway === 'razorpay') {
        e.preventDefault();
        initiateRazorpayPayment();
    }
    // For PayPal, form submits normally
});

function initiateRazorpayPayment() {
    const options = {
        "key": "{{ env('RAZORPAY_KEY') }}",
        "amount": "{{ $totalAmount * 100 }}",
        "currency": "INR",
        "name": "{{ config('app.name') }}",
        "description": "Promotion Package - {{ $package->name }}",
        "order_id": "{{ $transaction->order_id }}",
        "handler": function (response) {
            // Payment successful
            document.getElementById('transaction_id').value = '{{ $transaction->id }}';
            
            const form = document.getElementById('payment-form');
            const paymentIdInput = document.createElement('input');
            paymentIdInput.type = 'hidden';
            paymentIdInput.name = 'razorpay_payment_id';
            paymentIdInput.value = response.razorpay_payment_id;
            form.appendChild(paymentIdInput);
            
            const signatureInput = document.createElement('input');
            signatureInput.type = 'hidden';
            signatureInput.name = 'razorpay_signature';
            signatureInput.value = response.razorpay_signature;
            form.appendChild(signatureInput);
            
            form.action = "{{ route('seller.promotions.payment.callback') }}";
            form.submit();
        },
        "prefill": {
            "name": "{{ Auth::user()->name }}",
            "email": "{{ Auth::user()->email }}",
            "contact": "{{ Auth::user()->phone ?? '' }}"
        },
        "theme": {
            "color": "#f97316"
        },
        "modal": {
            "ondismiss": function() {
                alert('Payment cancelled');
            }
        }
    };
    
    const rzp = new Razorpay(options);
    rzp.open();
}
</script>
