<div class="row">
  <div class="col-md-12 mt-2">
    <form id="cmsForm" method="post" action="/packages/add" enctype="multipart/form-data" novalidate>
      <div class="card card-info">
        <div class="card-header">
          <h4 class="card-title">
            <%= sectionTitle %>
          </h4>
        </div>
        <div class="card-body">
          <div class="form-row">

            <!-- Produkt Auswahl -->
            <div class="form-group col-md-6">
              <label class="required" for="product_id">Produkt</label>
              <select id="product_id" name="product_id" class="form-control" required>
                <option selected disabled>Produkt wählen</option>
                <% if (products && products.length> 0) { %>
                  <% products.forEach(function(product) { %>
                    <option value="<%= product.id %>">
                      <%= product.model_name %>
                    </option>
                    <% }) %>
                      <% } else { %>
                        <option disabled>Keine Produkte verfügbar</option>
                        <% } %>
              </select>
            </div>

            <!-- Paketnummer -->
            <div class="form-group col-md-6">
              <label class="required" for="package_number">Artikel-Nr</label>
              <input type="text" id="package_number" name="package_number" class="form-control"
                placeholder="Enter Artikel-Nr" required onkeypress="return /[a-zA-Z0-9 ]/i.test(event.key)"
                oninput="this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '')" />
            </div>

            <!-- Lieferant -->
            <div class="form-group col-md-6">
              <label class="required" for="supplier">Lieferant</label>
              <input type="text" id="supplier" name="supplier" class="form-control" placeholder="Enter Lieferant"
                required onkeypress="return /[a-zA-Z0-9 ]/i.test(event.key)"
                oninput="this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '')" />
            </div>

          </div>

          <!-- Materialien Auswahl -->
          <div class="form-group mt-4 p-2">
            <label class="required">Materialien verwenden</label>
            <table class="table table-bordered" id="materialsTable">
              <thead>
                <tr>
                  <th>Material</th>
                  <th>Verwendete Menge</th>
                  <th>Aktion</th>
                </tr>
              </thead>
              <tbody>
                <tr class="material-row">
                  <td>
                    <select name="materials[0][material_id]" class="form-control material-select" required>
                      <option selected disabled>Material wählen</option>

                      <% if (materials && materials.length> 0) { %>
                        <% materials.forEach(function(mat) { %>
                          <option value="<%= mat.id %>">
                            <%= mat.material_name %>
                              (<%= mat.quantity %>
                                <%= mat.unit %> verfügbar)
                          </option>
                          <% }) %>
                            <% } %>
                    </select>
                  </td>

                  <!-- HIDDEN INITIALLY -->
                  <td class="quantity-column">
                    <input type="number" name="materials[0][quantity]" class="form-control quantity-input" min="1"
                      style="display:none;">
                  </td>

                  <td>
                    <button type="button" class="btn btn-danger remove-material">-</button>
                  </td>
                </tr>
              </tbody>
            </table>
            <button type="button" class="btn btn-primary" id="addMaterialRow">Weitere Material hinzufügen</button>
          </div>

        </div>

        <div class="card-footer">
          <button type="submit" id="savebtn" class="btn btn-info">
            Speichern
          </button>
          <button type="button" class="btn btn-default">
            <a href="/packages/list">Zurück</a>
          </button>
        </div>
      </div>
    </form>
  </div>
</div>
<script>
  $(document).ready(function () {
    let materialIndex = 1;

    // Function to refresh dropdown options
    function refreshMaterialDropdowns() {
      let selectedIds = [];

      // Collect all selected material IDs
      $(".material-select").each(function () {
        let val = $(this).val();
        if (val) selectedIds.push(val);
      });

      // Hide selected options from all other dropdowns
      $(".material-select").each(function () {
        let currentSelect = $(this);
        currentSelect.find("option").show(); // reset first

        currentSelect.find("option").each(function () {
          let optionVal = $(this).val();

          if (optionVal && selectedIds.includes(optionVal)) {
            // Hide if selected in another dropdown
            if (currentSelect.val() !== optionVal) {
              $(this).hide();
            }
          }
        });
      });
    }

    // Add new material row
    // Add new material row
    $("#addMaterialRow").click(function () {
      let newRow = `
    <tr class="material-row">
      <td>
        <select name="materials[${materialIndex}][material_id]"
          class="form-control material-select" required>

          <option selected disabled>Material wählen</option>

          <% materials.forEach(function(mat) { %>
            <option value="<%= mat.id %>">
              <%= mat.material_name %>
              (<%= mat.quantity %> <%= mat.unit %> verfügbar)
            </option>
          <% }) %>
        </select>
      </td>

      <!-- HIDDEN INITIALLY -->
      <td class="quantity-column">
  <input
    type="number"
    name="materials[${materialIndex}][quantity]"
    class="form-control quantity-input"
    min="1"
    style="display:none;"
  >
</td>

      <td>
        <button type="button" class="btn btn-danger remove-material">-</button>
      </td>
    </tr>
  `;

      $("#materialsTable tbody").append(newRow);

      materialIndex++;

      refreshMaterialDropdowns();
    });

    $("#materialsTable tbody").append(newRow);
    materialIndex++;

    refreshMaterialDropdowns(); // update immediately
  });

  // Remove material row
  $(document).on("click", ".remove-material", function () {
    $(this).closest("tr").remove();
    refreshMaterialDropdowns();
  });

  // On change of any dropdown
  // On change of material dropdown
  $(document).on("change", ".material-select", function () {

  let row = $(this).closest("tr");

  if ($(this).val()) {
    row.find(".quantity-input").show().attr("required", true);
  } else {
    row.find(".quantity-input").hide().val("");
  }

  refreshMaterialDropdowns();
});

</script>