{% extends 'tournaments/base.html' %}

{% block head_title %}La Boutique{% endblock %}
{% block first_title %}Padel Club{% endblock %}
{% block second_title %}La Boutique{% endblock %}

{% block content %}
<nav class="margin10">
  <a href="{% url 'shop:product_list' %}">La Boutique</a>
  <a href="{% url 'index' %}" class="orange">Accueil</a>
  <a href="{% url 'clubs' %}" class="orange">Clubs</a>
  {% if user.is_authenticated %}
  <a href="{% url 'my-tournaments' %}" class="orange">Mes tournois</a>
  <a href="{% url 'profile' %}">Mon compte</a>
  {% else %}
  <a href="{% url 'login' %}">Se connecter</a>
  {% endif %}
</nav>
{% if STRIPE_IS_TEST_MODE %}
<div class="alert alert-warning" style="background-color: #fff3cd; color: #856404; padding: 10px; margin: 10px 0; border-radius: 5px; border: 1px solid #ffeeba;">
    <strong>⚠️ Test Mode:</strong> Stripe is currently in test mode. No real payments will be processed.
    <br>
    <small>Use test card: 4242 4242 4242 4242 with any future date and any CVC.</small>
</div>
{% endif %}

<div class="grid-x">
    <div class="small-12 medium-9 large-6 my-block">
    <h1 class="club my-block topmargin20">Votre panier</h1>
    <div class="bubble">
      {% if display_data.items %}
      {% include 'shop/partials/order_items_display.html' with items=display_data.items total_quantity=display_data.total_quantity total_price=display_data.total_price edit_mode=True %}

      <div class="cart-summary">

        {% if user.is_authenticated %}
        <!-- For authenticated users: Direct Stripe payment button -->
        <button id="checkout-button" class="confirm-nav-button checkout-button">Procéder au paiement</button>
        {% else %}
        <!-- For guest users: Regular checkout path -->
        <a class="confirm-nav-button checkout-button" href="{% url 'shop:checkout' %}">Passer la commande</a>
        <div class="guest-checkout-notice">
          <p>Connectez-vous pour un paiement plus rapide.</p>
          <a class="styled-link" href="{% url 'login' %}?next={% url 'shop:view_cart' %}">Se connecter</a>
        </div>
        {% endif %}
        <hr>
        {% if display_data.items %}
        <a class="cancel-nav-button checkout-button" href="{% url 'shop:clear_cart' %}" onclick="return confirm('Êtes-vous sûr de vouloir supprimer votre panier ?');">Vider le panier</a>
        {% endif %}

        <!-- Debug buttons -->
        {% if settings.DEBUG %}
        <div style="margin-top: 20px; padding-top: 20px; border-top: 1px dashed #ccc;">
          <h3>Debug Payment Simulation</h3>
          <div style="display: flex; gap: 10px;">
            <a class="confirm-nav-button checkout-button" href="{% url 'shop:simulate_payment_success' %}" style="background-color: #28a745;">
              Simuler Paiement Réussi
            </a>
            <a class="cancel-nav-button checkout-button" href="{% url 'shop:simulate_payment_failure' %}" style="background-color: #dc3545;">
              Simuler Paiement Échoué
            </a>
          </div>
        </div>
        {% endif %}

      </div>
      {% else %}
      <p>Votre panier est vide.</p>
      <a class="confirm-nav-button checkout-button" href="{% url 'shop:product_list' %}">Retourner à la boutique</a>
      {% endif %}
    </div>
  </div>
</div>

{% if user.is_authenticated and display_data.items %}
<!-- Stripe JavaScript for authenticated users -->
<script src="https://js.stripe.com/v3/"></script>
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const checkoutButton = document.getElementById('checkout-button');

    checkoutButton.addEventListener('click', function() {
      // Show a loading indicator
      checkoutButton.textContent = 'Chargement...';
      checkoutButton.disabled = true;

      // Create order and get checkout session
      fetch('{% url "shop:create_checkout_session" %}', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRFToken': '{{ csrf_token }}'
        },
        credentials: 'same-origin',
      })
      .then(function(response) {
        return response.json();
      })
      .then(function(session) {
        if (session.error) {
          // Handle error
          alert(session.error);
          checkoutButton.textContent = 'Procéder au paiement';
          checkoutButton.disabled = false;
          return;
        }

        // Initialize Stripe
        const stripe = Stripe('{{ stripe_publishable_key }}');

        // Redirect to Stripe Checkout
        return stripe.redirectToCheckout({ sessionId: session.id });
      })
      .then(function(result) {
        // If redirectToCheckout fails
        if (result && result.error) {
          alert(result.error.message);
          checkoutButton.textContent = 'Procéder au paiement';
          checkoutButton.disabled = false;
        }
      })
      .catch(function(error) {
        console.error('Error:', error);
        alert('Une erreur est survenue. Veuillez réessayer.');
        checkoutButton.textContent = 'Procéder au paiement';
        checkoutButton.disabled = false;
      });
    });
  });
</script>
{% endif %}
{% endblock %}
