{% extends "base.html" %}
{% comment %}
Copyright (C) 2018-2025 by BDE ENS Paris-Saclay
SPDX-License-Identifier: GPL-3.0-or-later
{% endcomment %}
{% load i18n crispy_forms_tags %}

{% block content %}
<div class="card bg-white mb-3">
  <h3 class="card-header text-center">
    {{ title }}
  </h3>
  <form method="post" action="" id="recipe_form">
    {% csrf_token %}
    <div class="card-body">
      {% crispy recipe_form %}
      {# Keep all form elements in the same card-body for proper structure #}
      {{ formset.management_form }}
      <h3 class="text-center mt-4">{% trans "Add ingredients" %}</h3>
      <table class="table table-condensed table-striped">
        {% for form in formset %}
        {% if forloop.first %}
        <thead>
          <tr>
            <th>{{ form.name.label }}</th>
          </tr>
        </thead>
        <tbody id="form_body">
        {% endif %}
          <tr class="row-formset ingredients">
            <td>
              {# Force prefix on the form fields #}
              {{ form.name.as_widget }}
            </td>
          </tr>
        {% endfor %}
        </tbody>
      </table>
    </div>
  {# Display buttons to add and remove ingredients #}
    <div class="card-body">
        <div class="btn-group btn-block" role="group">
            <button type="button" id="add_more" class="btn btn-success">{% trans "Add ingredient" %}</button>
            <button type="button" id="remove_one" class="btn btn-danger">{% trans "Remove ingredient" %}</button>
        </div>
        <button class="btn btn-primary" type="submit" form="recipe_form">{% trans "Submit"%}</button>
    </div>
  </form>
</div>

{# Hidden div that store an empty supplement form, to be copied into new forms #}
<div id="empty_form" style="display: none;">
    <table class='no_error'>
        <tbody id="for_real">
            <tr class="row-formset">
                <td>{{ formset.empty_form.name }}</td>
            </tr>
        </tbody>
    </table>
</div>

{% endblock %}

{% block extrajavascript %}
<script>
/* script that handles add and remove lines */
$(document).ready(function() {
  const totalFormsInput = $('input[name$="-TOTAL_FORMS"]');
  const initialFormsInput = $('input[name$="-INITIAL_FORMS"]');

  function updateTotalForms(n) {
    if (totalFormsInput.length) {
      totalFormsInput.val(n);
    }
  }

  const initialCount = $('#form_body .row-formset').length;
  updateTotalForms(initialCount);

  const foods = {{ ingredients | safe }};

function prepopulate () {
	for (var i = 0; i < {{ ingredients_count }}; i++) {
		let prefix = 'id_form-' + parseInt(i) + '-';
		document.getElementById(prefix + 'name').value = foods[i]['name'];
	};
}
prepopulate();

  $('#add_more').click(function() {
    let formIdx = totalFormsInput.length ? parseInt(totalFormsInput.val(), 10) : $('#form_body .row-formset').length;
    let newForm = $('#for_real').html().replace(/__prefix__/g, formIdx);
    $('#form_body').append(newForm);
    updateTotalForms(formIdx + 1);
  });

  $('#remove_one').click(function() {
    let formIdx = totalFormsInput.length ? parseInt(totalFormsInput.val(), 10) : $('#form_body .row-formset').length;
    if (formIdx > 1) {
      $('#form_body tr.row-formset:last').remove();
      updateTotalForms(formIdx - 1);
    }
  });
  
  $('#recipe_form').on('submit', function() {
    const totalInput = $('input[name$="-TOTAL_FORMS"]');
    const prefix = totalInput.length ? totalInput.attr('name').replace(/-TOTAL_FORMS$/, '') : 'form';

    $('#form_body tr.row-formset').each(function(i) {
      const input = $(this).find('input,select,textarea').first();
      if (input.length) {
        const newName = `${prefix}-${i}-name`;
        input.attr('name', newName).attr('id', `id_${newName}`).prop('disabled', false);
      }
    });

    const visibleCount = $('#form_body tr.row-formset').length;
    if (totalInput.length) totalInput.val(visibleCount);
  });
});
</script>
{% endblock %}