{% extends 'base.html' %}

{% block title %}{{ grouped_order }} - Gestion{% endblock %}

{% block content %}
  <p class="desktop-hidden mobile-content-title">
    {% block content_title %}{{ grouped_order }} : gestion de la commande{% endblock %}
  </p>
  <div class="buttons">
    <a class="button is-light" href={% url 'order:grouped_order_detail' grouped_order.code %}>
      <i class="fa fa-arrow-left mr-3" aria-hidden="true"></i>Retour à la page de commande
    </a>
    <a class="button is-primary" href="{% url 'order:index' %}">
      <i class="fa fa-shopping-basket mr-3" aria-hidden="true"></i>Mes commandes
    </a>
  </div>
  <div class="box is-info">
    <div class="columns">
      <div class="column is-8">
        <p class="title">{{ grouped_order }}</p>
        {% if grouped_order.description %}<p class="formatted-text">{{ grouped_order.description }}</p>{% endif %}
      </div>
      <div class="column">
        {% if grouped_order.place %}
        <p><i class="fa fa-map-pin mr-3" aria-label="Lieu" title="Lieu" aria-hidden="true"></i>{{ grouped_order.place }}</p>
        {% endif %}
        <p><i class="fa fa-calendar-check-o mr-3" aria-label="Date limite de commande" title="Date limite de commande" aria-hidden="true"></i>
          Commandes avant le {{ grouped_order.deadline|date:'d M Y' }} à {{ grouped_order.deadline|date:'H:i' }}
        </p>
        <p><i class="fa fa-truck mr-3" aria-label="Date de livraison" title="Date de livraison" aria-hidden="true"></i>
          Livraison le {{ grouped_order.delivery_date }}{% if grouped_order.delivery_slot %}, {{ grouped_order.delivery_slot }}{% endif %}
        </p>
        <div class="buttons">
          <a class="button is-light" href="{% url 'order:update_grouped_order' grouped_order.code %}">
            <i class="fa fa-pencil mr-3" aria-hidden="true"></i>Modifier la commande
          </a>
          <a class="button is-light" href="{% url 'order:delete_grouped_order' grouped_order.code %}">
            <i class="fa fa-trash mr-3" aria-hidden="true"></i>Supprimer la commande
          </a>
        </div>
      </div>
    </div>
  </div>

  <div class="tabs is-toggle is-centered is-fullwidth">
    <ul>
      <li>
        <a id="resume-opener" class="is-active tablinks" onclick="openTab('resume')">
          <span class="is-hidden-desktop">Résumé</span>
          <span class="is-hidden-touch">Résumé de la commande</span>
        </a>
      </li>
      <li>
        <a id="commandes-opener" class="tablinks" onclick="openTab('commandes')">
          <span class="is-hidden-desktop">Commandes</span>
          <span class="is-hidden-touch">Liste des commandes</span>
        </a>
      </li>
      <li>
        <a id="partager-opener" class="tablinks" onclick="openTab('partager')">
          <span class="is-hidden-desktop">Partager</span>
          <span class="is-hidden-touch">Partager et exporter</span>
        </a>
      </li>
    </ul>
  </div>

  <div id="partager" class="box tabcontent">
    <p class="title">Partager et exporter</p>
    <div class="columns">
      <div class="column">
        {% if not grouped_order.is_to_be_delivered %}
        <p>
          <strong>Cette commande groupée est terminée</strong>, la livraison a eu lieu le {{ grouped_order.deadline }}.
        </p>
        {% elif not grouped_order.is_open %}
        <p>
          <strong>La période de commande est terminée</strong> depuis le {{ grouped_order.deadline }}.
          Vous pouvez préparer la livraison, qui aura lieu le {{ grouped_order.delivery_date }} !
        </p>
        {% else %}
        <p>Pour partager cette commande, il vous suffit de copier ce lien et de l'envoyer à vos connaissances : </p>
        <input class="input custom-width" type="text" value={{ share_link }} id="shareLink" disabled>
        <button class="button is-info" onclick="copyText('shareLink')">
          <i class="fa fa-files-o mr-3" aria-hidden="true"></i>Copier le lien
        </button>
        <p class="subtitle mt-4">Code de la commande : {{ grouped_order.code }}</p>
        {% endif %}
      </div>
      <div class="column">
        <p>Pour vous aider à distribuer les produits le jour J, vous pouvez télécharger la liste des commandes 
          au format PDF pour l'<strong>imprimer</strong>, ou au format CSV pour l'<strong>afficher dans un tableur</strong> :</p>
        <a class="button is-info" href="{% url 'order:grouped_order_sheet' grouped_order.code %}">
          <i class="fa fa-file-pdf-o mr-3" aria-hidden="true"></i>Commandes en PDF
        </a>
        <a class="button is-info" href="{% url 'order:grouped_order_csv_export' grouped_order.code %}">
          <i class="fa fa-file-excel-o mr-3" aria-hidden="true"></i>Commandes en CSV
        </a>
      </div>
    </div>
  </div>

  <div id="resume" class="box tabcontent">
    <a class="button is-primary is-pulled-right" href="{% url 'order:manage_items' grouped_order.code %}">Gérer les produits</a>
    <p class="title">Produits commandés</p>
    {% if grouped_order.item_set.all %}
    <table class="table">
      <thead>
        <tr>
          <th>Produit</th>
          <th>Prix unitaire</th>
          <th>Quantité</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody>
        {% for item in grouped_order.item_set.all %}
        <tr>
          <td>{{ item.name }}</td>
          <td>{{ item.price }} €</td>
          <td>{{ item.ordered_nb }}</td>
          <td>{{ item.get_total_price }} €</td>
        </tr>
        {% endfor %}
      </tbody>
      <tfoot>
        <th>Total</th>
        <th></th>
        <th>{{ total_ordered_items }}</th>
        <th>{{ grouped_order.total_price }} €</th>
      </tfoot>
    </table>
    {% else %}
    <p>Vous n'avez pas ajouté de produits à cette commande groupée. Ajoutez-en <a href="{% url 'order:manage_items' grouped_order.code %}">ici</a></p>
    {% endif %}
  </div>

  <div id="commandes" class="box tabcontent">
    <div class="buttons is-pulled-right">
      <a class="button is-info" href="{% url 'order:email_list' grouped_order.code %}?format=csv">
        <i class="fa fa-file-excel-o mr-3" aria-hidden="true"></i>Emails en CSV
      </a>
      <input id="email_list" name="email_list" hidden="true" value="{{ emails_list|join:';' }}" />
      <a class="button is-info" onclick="copyText('email_list')">
        <i class="fa fa-files-o mr-3" aria-hidden="true"></i>Copier les emails
      </a>
    </div>
    <p class="title">Liste des commandes</p>
    {% if grouped_order.order_set.all %}
    <table class="table">
      <thead>
        <tr>
          <th>Participant·e</th>
          <th>Montant</th>
          <th>Contact</th>
          <th>Voir</th>
        </tr>
      </thead>
      <tbody>
        {% for order in grouped_order.order_set.all %}
        <tr>
          <td>{{ order.author }}</td>
          <td>{{ order.price }} €</td>
          <td><a href="mailto:{{ order.author.email }}">{{ order.author.email }}</a>{% if order.author.phone %} / {{ order.author.phone }}{% endif %}</td>
          <td>
            <button class="button is-info is-small js-modal-trigger" data-target="order-detail-{{ order.id }}">
            Voir
            </button>
            {% if order.note %}
              <i class="fa fa-comment ml-3 mr-2" title="{{ order.note }}" aria-hidden="true"></i>
            {% else %}
              <span class="ml-5 mr-4"></span>
            {% endif %}
            <button class="button is-light is-small js-modal-trigger" data-target="confirm-delete-{{ order.id }}">
              Supprimer
            </button>
          </td>
        </tr>

        <!-- Order detail modal -->
        <div id="order-detail-{{ order.id }}" class="modal">
          <div class="modal-background"></div>
          <div class="modal-card ">
            <header class="modal-card-head has-background-info">
              <div class="modal-card-title-container">
                <p class="modal-card-title mb-2">Commande de {{ order.author }}</p>
                <p class="has-text-grey-dark">Le {{ order.created_date|date:'d M Y' }} à {{ order.created_date|date:'H:i' }}</p>
              </div>
              <button class="delete" aria-label="close"></button>
            </header>
            <section class="modal-card-body">
              <div class="columns">
                <div class="column">
                  {% for item in order.ordered_items.all %}
                  {{ item.nb }} × {{ item.item.name }}
                  <hr class="mb-0 mt-1">
                  {% endfor %}
                </div>
                {% if order.note %}
                <div class="column is-4">
                  <p class="mini-title">Note à l'organisateur·ice</p>
                  <p>{{ order.note }}</p>
                </div>
              </div>
              {% endif %}
            </section>
            <footer class="modal-card-foot">
              <p class="mini-title">Total à payer</p>
              <p>{{ order.price }} €</p>
            </footer>
          </div>
        </div>

        <!-- Confirm delete order modal -->
        <div id="confirm-delete-{{ order.id }}" class="modal">
          <div class="modal-background"></div>
          <div class="modal-card ">
            <header class="modal-card-head">
              <div class="modal-card-title-container">
                <p class="modal-card-title">Supprimer la commande de {{ order.author }} ?</p>
              </div>
            </header>
            <section class="modal-card-body">
              <div class="columns">
                <div class="column">
                  {% for item in order.ordered_items.all %}
                  {{ item.nb }} × {{ item.item.name }}
                  <hr class="mb-0 mt-1">
                  {% endfor %}
                </div>
                {% if order.note %}
                <div class="column is-4">
                  <p class="mini-title">Note à l'organisateur·ice</p>
                  <p>{{ order.note }}</p>
                </div>
              </div>
              {% endif %}
            </section>
            <footer class="modal-card-foot">
              <div class="columns">
                <div class="column is-8">
                  <p class="mini-title">Total à payer</p>
                  <p>{{ order.price }} €</p>
                </div>
                <div class="column">
                  <form action="{% url 'order:order_delete' grouped_order.code order.id %}" method="post">
                    {% csrf_token %}
                    <input type="submit" name="{{ item.id }}" value="Oui" class="button is-danger"/>
                    <a class="button is-light" aria-label="close">Non</a>
                  </form>
                </div>
            </footer>
          </div>
        </div>
        {% endfor %}

      </tbody>
      <tfoot>
        <th>Total</th>
        <th>{{ grouped_order.total_price }} €</th>
        <th></th>
        <th></th>
      </tfoot>
    </table>
    {% else %}
    <p>Personne n'a encore commandé. Partagez l'info à votre entourage !</p>
    {% endif %}
  </div>
  {% endblock %}

<script>
  {% block extra_js %}

  var previousCopied = null;
  var previousHtmlCopied = null;

  // Copy grouped order text
  function copyText(elementId) {
    var element = document.getElementById(elementId); 
    var text = element.value;
    navigator.clipboard.writeText(text).then(function() {
        console.debug('Copying to clipboard was successful!');
        console.debug('Copied text: ', text);
        var button = document.querySelector('[onclick="copyText(\'' + elementId + '\')"]');
        if (button !== null) {
            if (previousCopied !== null) {
                previousCopied.innerHTML = previousHtmlCopied;
            }
            var originalWidth = button.offsetWidth;

            previousHtmlCopied = button.innerHTML;
            button.innerHTML = '✓ ';
            previousCopied = button;
            if (button.offsetWidth !== originalWidth) {
                button.style.width = originalWidth + 'px';
            }
        }
    }, function(err) {
        console.error('Could not copy text: ', err);
    });
  }
  // Tabs
  function openTab(idToOpen) {
    var i, tabcontent, tablinks;

    // Get all elements with class="tabcontent" and hide them
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
      tabcontent[i].style.display = "none";
    }

    // Get all elements with class="tablinks" and remove the class "active"
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
      tablinks[i].parentNode.classList.remove("is-active");
    }

    // Show the current tab, and add an "is-active" class to the button that opened the tab
    document.getElementById(idToOpen).style.display = "block";
    document.getElementById(idToOpen+"-opener").parentNode.classList.add("is-active");
  }

  // Open by default the "resume" tab at first
  openTab("resume");

  // Modal
  document.addEventListener('DOMContentLoaded', () => {
    // Functions to open and close a modal
    function openModal($el) {
      $el.classList.add('is-active');
    }
  
    function closeModal($el) {
      $el.classList.remove('is-active');
    }
  
    function closeAllModals() {
      (document.querySelectorAll('.modal') || []).forEach(($modal) => {
        closeModal($modal);
      });
    }
  
    // Add a click event on buttons to open a specific modal
    (document.querySelectorAll('.js-modal-trigger') || []).forEach(($trigger) => {
      const modal = $trigger.dataset.target;
      const $target = document.getElementById(modal);
  
      $trigger.addEventListener('click', () => {
        openModal($target);
      });
    });
  
    // Add a click event on various child elements to close the parent modal
    (document.querySelectorAll('.modal-background, .modal-close, .modal-card-head .delete, .modal-card-foot .button') || []).forEach(($close) => {
      const $target = $close.closest('.modal');
  
      $close.addEventListener('click', () => {
        closeModal($target);
      });
    });
  
    // Add a keyboard event to close all modals
    document.addEventListener('keydown', (event) => {
      const e = event || window.event;
  
      if (e.keyCode === 27) { // Escape key
        closeAllModals();
      }
    });
  });

  {% endblock %}
</script>