{% extends 'uncloud/base.html' %}
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://js.stripe.com/v3/"></script>
{% endblock %}
    <div class="container">
      {% csrf_token %}
      <div id="content">
        <h1>Register Credit Card with Stripe</h1>
        <p>
          By submitting I authorise to send instructions to
          the financial institution that issued my card to take
          payments from my card account in accordance with the
          terms of my agreement with you.
        </p>

        <span id="message"></span>

        <input id="cardholder-name" type="text">
        <!-- placeholder for Elements -->
        <form id="setup-form" data-secret="{{ client_secret }}">
          <div id="card-element"></div>
          <div id="card-errors" role="alert"></div>
          <button id="card-button">
            Save Card
          </button>
        </form>
        <div id="ungleichmessage">The card will be registered with stripe.</div>

        <div id="goback" style="display: none;">
          <a href="{% url 'uncloudindex' %}">Go back to main page</a>
        </div>
      </div>


    <!-- Enable Stripe from UI elements - standard code -->
    <script>
      var cardholderName = document.getElementById('cardholder-name');
      var setupForm = document.getElementById('setup-form');
      var clientSecret = setupForm.dataset.secret;
      var stripe = Stripe('{{ stripe_pk }}');
    
      var cardButton = document.getElementById('card-button');
      var messageContainer = document.getElementById('message');
      var backmessage = document.getElementById('goback');
      var clientSecret = '{{ client_secret }}';

      var elements = stripe.elements();
      var cardElement = elements.create('card');
      cardElement.mount('#card-element');

      setupForm.addEventListener('submit', function(ev) {
        ev.preventDefault();
        stripe.confirmCardSetup(
          clientSecret,
          {
            payment_method: {
              card: cardElement,
              billing_details: {
                name: cardholderName.value,
              },
            },
          }
        ).then(function(result) {
          if (result.error) {
			      var message = document.createTextNode('Error:' + result.error.message);
			      messageContainer.appendChild(message);
		      } else {
            document.getElementById("ungleichmessage").innerHTML
		              = "Registered credit card with Stripe."
                  backmessage.style.display = "block";
			      // Return to API on success.
		      }
        });
      });
    </script>
