{% extends "shopit/base.html" %}
{% load i18n cms_tags sekizai_tags shop_tags shopit_tags %}

{% block page_title %}{{ product.name }}{% endblock %}

{% block content %}
  <div class="col-md-8 push-2">
    {{ product.description|safe }}
    <h4 id="price" class="text-info">{{ product.price }}</h4>
    <hr>

    {# Display attribute choices for a group product. #}
    {% if product.is_group %}
      <form id="attributes" class="mb-3">
        <h5>{% trans "Choose variation" %}</h5>
        {% for attr in product.get_attribute_choices.values %}
          <div class="row">
            <div class="form-group col-md-4">
              <label for="id_{{ attr.code }}">{{ attr.name }}</label>
              <select id="id_{{ attr.code }}" name="{{ attr.code }}">
                {% for option in attr.choices %}
                  <option value="{{ option.value }}">{{ option.name }}</option>
                {% endfor %}
              </select>
            </div>
          </div>
        {% endfor %}
      </form>

      <p id="variant" class="badge badge-default">{% trans "Not available." %}</p>
    {% endif %}

    {% add_to_cart watch=True %}

    <div>{% render_placeholder product.content %}</div>
  </div>

  {% addtoblock "js" %}
    <script>
      (function ($) {
        'use strict';

        var PRODUCT = $.parseJSON('{{ data|rest_json|escapejs }}');

        $(document).ready(function () {
          var $addToCart = $('.add-to-cart');
          var $attributes = $('#attributes');

          var selectVariant = function () {
            var formData = $attributes.serializeArray();
            var variantExists = false;

            $.each(PRODUCT.variants, function (key, variant) {
              var valid = true;

              $.each(formData, function (key, option) {
                if (variant.attributes[option.name.replace('-', '_')].value !== option.value) { valid = false; }
              });

              if (valid) {
                $addToCart.trigger('setProduct', [variant]);
                variantExists = true;

                // Populate DOM with variant data here.
                $('#variant').text(variant.name +' ('+ variant.price +')');
                $('#price').text(variant.price);
                return false;
              }
            });

            if (!variantExists) {
              $addToCart.trigger('setProduct', [PRODUCT]);
              $('#variant').text('{% trans "Not available." %}');
            }
          };

          if (PRODUCT.variants) {
            selectVariant();
            $attributes.find('select').on('change', selectVariant);
          } else {
            $addToCart.trigger('setProduct', [PRODUCT]);
          }
        });

      })(jQuery);
    </script>
  {% endaddtoblock %}
{% endblock %}
