{% extends "core/base.jinja" %}
{% from "core/macros.jinja" import user_mini_profile, user_subscription %}

{% block title %}
  {{ counter }}
{% endblock %}

{% block additional_css %}
  <link rel="stylesheet" href="{{ static('counter/css/counter-click.scss') }}">
  <link rel="stylesheet" href="{{ static('bundled/core/components/ajax-select-index.css') }}">
  <link rel="stylesheet" href="{{ static('core/components/ajax-select.scss') }}">
  <link rel="stylesheet" href="{{ static('core/components/tabs.scss') }}">
  <link rel="stylesheet" href="{{ static("core/components/card.scss") }}">
{% endblock %}

{% block additional_js %}
  <script type="module" src="{{ static('bundled/counter/counter-click-index.ts') }}"></script>
  <script type="module" src="{{ static('bundled/counter/components/counter-product-select-index.ts') }}"></script>
  <script type="module" src="{{ static('bundled/core/components/tabs-index.ts') }}"></script>
{% endblock %}

{% block info_boxes %}
{% endblock %}


{% block nav %}
{% endblock %}

{% block content %}
  <h4>{{ counter }}</h4>

  <div id="bar-ui" x-data="counter({
                           customerBalance: {{ customer.amount }},
                           products: products,
                           formulas: formulas,
                           customerId: {{ customer.pk }},
                           formInitial: formInitial,
                           cancelUrl: '{{ cancel_url }}',
                           })">

    <div id="user_info">
      <h5>{% trans %}Customer{% endtrans %}</h5>
      {{ user_mini_profile(customer.user) }}
      {{ user_subscription(customer.user) }}
      <p>{% trans %}Amount: {% endtrans %}<span x-text="customerBalance"></span> €
        <span x-cloak x-show="getBasketSize() > 0">
          <i class="fa-solid fa-arrow-right"></i>
          <span x-text="(customerBalance - sumBasket()).toLocaleString(undefined, { minimumFractionDigits: 2 })"></span> €
        </span>
      </p>
    </div>

    <div id="click-form">
      <details class="accordion" id="selling-accordion" name="selling" open>
        <summary>{% trans %}Selling{% endtrans %}</summary>
        <div class="accordion-content">
          {% set counter_click_url = url('counter:click', counter_id=counter.id, user_id=customer.user_id) %}

          <form method="post" action="" @submit.prevent="handleCode">

            <counter-product-select
              name="code"
              x-ref="codeField"
              autofocus
              required
              placeholder="{% trans %}Select a product...{% endtrans %}"
            >
              <option value=""></option>
              <optgroup label="{% trans %}Operations{% endtrans %}">
                <option value="FIN">{% trans %}Confirm (FIN){% endtrans %}</option>
                <option value="ANN">{% trans %}Cancel (ANN){% endtrans %}</option>
              </optgroup>
              {%- for category, prices in categories.items() -%}
                <optgroup label="{{ category }}">
                  {%- for price in prices -%}
                    <option value="{{ price.id }}">{{ price.full_label }} ({{ price.product.code }})</option>
                  {%- endfor -%}
                </optgroup>
              {%- endfor -%}
            </counter-product-select>
          </form>

          {% for error in form.non_form_errors() %}
            <div class="alert alert-red">
              {{ error }}
            </div>
          {% endfor %}
          <p>{% trans %}Basket: {% endtrans %}</p>

          <form x-cloak method="post" action="" x-ref="basketForm">

            <div class="basket-message-container">
              <div
                x-cloak
                class="alert basket-message"
                :class="alertMessage.success ? 'alert-green' : 'alert-red'"
                x-show="alertMessage.open"
                x-transition.duration.500ms
                x-text="alertMessage.content"
              ></div>
            </div>

            {% csrf_token %}
            <div x-ref="basketManagementForm">
              {{ form.management_form }}
            </div>
            <ul>
              <li x-show="getBasketSize() === 0">
                <em>{% trans %}This basket is empty{% endtrans %}</em>
              </li>
              <template x-for="(item, index) in Object.values(basket)" :key="item.product.price.id">
                <li>
                  <template x-for="error in item.errors">
                    <div class="alert alert-red" x-text="error">
                    </div>
                  </template>

                  <div class="basket-row">
                    <div>
                      <button @click.prevent="addToBasket(item.product.price.id, -1)">-</button>
                      <span class="quantity" x-text="item.quantity"></span>
                      <button @click.prevent="addToBasket(item.product.price.id, 1)">+</button>
                    </div>

                    <span class="product-name" x-text="item.product.name"></span>
                    <span x-text="`${item.sum().toLocaleString(undefined, { minimumFractionDigits: 2 })} €`"></span>
                    <span x-show="item.getBonusQuantity() > 0"
                          x-text="`${item.getBonusQuantity()} x P`"></span>

                    <button
                      class="remove-item"
                      @click.prevent="removeFromBasket(item.product.price.id)"
                    ><i class="fa fa-trash-can delete-action"></i></button>
                  </div>

                  <input
                    type="hidden"
                    :value="item.quantity"
                    :id="`id_form-${index}-quantity`"
                    :name="`form-${index}-quantity`"
                    required
                    readonly
                  >
                  <input
                    type="hidden"
                    :value="item.product.price.id"
                    :id="`id_form-${index}-price_id`"
                    :name="`form-${index}-price_id`"
                    required
                    readonly
                  >
                </li>
              </template>
            </ul>

            <p class="margin-bottom">
              <strong>Total: </strong>
              <strong x-text="sumBasket().toLocaleString(undefined, { minimumFractionDigits: 2 })"></strong>
              <strong> €</strong>
            </p>

            <div class="row">
              <input
                class="btn btn-blue"
                type="submit"
                @click.prevent="finish"
                :disabled="getBasketSize() === 0"
                value="{% trans %}Finish{% endtrans %}"
              />
              <input
                class="btn btn-grey"
                type="submit" @click.prevent="cancel"
                value="{% trans %}Cancel{% endtrans %}"
              />
            </div>
          </form>
        </div>
      </details>
      <details
        class="accordion"
        name="selling"
        @toggle="if ($event.newState === 'open') $el.querySelector('input[type=number]')?.focus()"
      >
        <summary>{% trans %}Refilling{% endtrans %}</summary>
        {% if object.type == "BAR" %}
          {% if refilling_fragment %}
            <div
              class="accordion-content"
              @htmx:after-swap="onRefillingSuccess"
            >
              {{ refilling_fragment }}
            </div>
          {% else %}
            <div class="accordion-content">
              <p class="alert alert-yellow">
                {% trans trimmed %}
                  As a barman, you are not able to refill any account on your own.
                  An admin should be connected on this counter for that.
                  The customer can refill by using the eboutic.
                {% endtrans %}
              </p>
            </div>
          {% endif %}
          </details>
          {% if student_card_fragment %}
            <details class="accordion" name="selling">
              <summary>{% trans %}Student card{% endtrans %}</summary>
              <div class="accordion-content">
                {{ student_card_fragment }}
              </div>
            </details>
          {% endif %}

        {% endif %}
      </div>

      <div id="products">
        {% if not prices %}
          <div class="alert alert-red">
            {% trans %}No products available on this counter for this user{% endtrans %}
          </div>
        {% else %}
          <ui-tab-group>
            {% for category, prices in categories.items() -%}
              <ui-tab title="{{ category }}" {% if loop.index == 1 -%}active{%- endif -%}>
                <h5 class="margin-bottom">{{ category }}</h5>
                <div class="row gap-2x">
                  {% for price in prices -%}
                    <button class="card shadow" @click="addToBasket('{{ price.id }}', 1)">
                      <img
                        class="card-image"
                        alt="image de {{ price.full_label }}"
                        {% if price.product.icon %}
                          src="{{ price.product.icon.url }}"
                        {% else %}
                          src="{{ static('core/img/na.gif') }}"
                        {% endif %}
                      />
                      <span class="card-content">
                        <strong class="card-title">{{ price.full_label }}</strong>
                        <p>{{ price.amount }} €<br>{{ price.product.code }}</p>
                      </span>
                    </button>
                  {%- endfor %}
                </div>
              </ui-tab>
            {% endfor %}
          </ui-tab-group>
        {% endif %}
      </div>
    </div>
{% endblock content %}

{% block script %}
  {{ super() }}
  <script>
    const products = {
      {%- for price in prices -%}
        {{ price.id }}: {
          productId: {{ price.product_id }},
          price: { id: "{{ price.id }}", amount: {{ price.amount }} },
          code: "{{ price.product.code }}",
          name: "{{ price.full_label }}",
          hasTrayPrice: {{ price.product.tray | tojson }},
          quantityForTrayPrice: {{ price.product.QUANTITY_FOR_TRAY_PRICE }},
        },
      {%- endfor -%}
    };
    const formulas = [
      {%- for formula in formulas -%}
        {
          result: {{ formula.result_id }},
          products: [
            {%- for product in formula.products.all() -%}
              {{ product.id }},
            {%- endfor -%}
          ]
        },
      {%- endfor -%}
    ];
    const formInitial = [
      {%- for f in form -%}
        {%- if f.cleaned_data -%}
          {
            {%- if f.cleaned_data["id"] -%}
              id: '{{ f.cleaned_data["id"] | tojson }}',
            {%- endif -%}
            {%- if f.cleaned_data["quantity"] -%}
              quantity: {{ f.cleaned_data["quantity"] | tojson }},
            {%- endif -%}
            errors: {{ form_errors[loop.index0] | tojson }},
          },
        {%- endif -%}
      {%- endfor -%}
    ];
  </script>
{% endblock script %}