document.addEventListener("DOMContentLoaded", function() {
  // Retrieve order ID from URL query parameter
  const urlParams = new URLSearchParams(window.location.search);
  const orderId = urlParams.get('orderId');
  const selectedSponsorshipLevel = urlParams.get('sponsorshipLevel');
  console.log("sponsorshipLevel in payment page"+selectedSponsorshipLevel);
  if (selectedSponsorshipLevel === '1') {
    $('#registrationFee').text('Please pay Registration Fee: ₹200000');
  } else if (selectedSponsorshipLevel === '2') {
    
    $('#registrationFee').text('Please pay Registration Fee: ₹300000');
  } else if (selectedSponsorshipLevel === '0') {
    
    $('#registrationFee').text('Please pay Registration Fee: ₹80000');
  }
  $('#acceptTerms').change(function() {
    const isChecked = this.checked;
    const $payButton = $('#payButton');

    // Enable or disable the Pay Now button based on checkbox state
    $payButton.prop('disabled', !isChecked);

    // Change button color and hover message based on disabled state
    if (!isChecked) {
      $payButton.css({
        'background-color': '#ccc',  // Gray color when disabled
        'cursor': 'not-allowed'      // Not allowed cursor when disabled
      }).attr('title', 'Please accept the terms and conditions to proceed');
    } else {
      $payButton.css({
        'background-color': '#3399cc',  // Original color when enabled
        'cursor': 'pointer'             // Pointer cursor when enabled
      }).removeAttr('title');
    }
  });

  // Add event listener to Pay Now button
  document.getElementById('payButton').addEventListener('click', function() {
    // Initiate Razorpay payment
    fetch(`/createPayment?orderId=${orderId}&sponsorshipLevel=${selectedSponsorshipLevel}`, { method: 'POST' })
      .then(response => response.json())
      .then(data => {
        const { key, amount, currency, order_id, name, description, image } = data;
        console.log("amount to be paid::"+amount);
        const options = {
          "key": key,
          "amount": amount,
          "currency": currency,
          "order_id": order_id,
          "name": name,
          "description": description,
          "image": image,
          "handler": function (response) {
            // Handle successful payment response
            console.log('Payment successful:', response);
            // Redirect to payment successful page
            window.location.href = '/payment-successful';
          },
          "prefill": {
            "name": "Customer Name",
            "email": "customer@example.com"
          },
          "theme": {
            "color": "#3399cc"
          }
        };
        // Open Razorpay checkout with options
        const rzp = new Razorpay(options);
        rzp.open();
      })
      .catch(error => console.error('Error creating payment:', error));
  });
});
