<!-- Daterangepicker CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

<div class="row">
  <div class="col-md-12 mt-2">
    <form id="bannerForm" method="post" action="/manage-project/insert" 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">
            <!-- Project Name -->
            <div class="form-group col-md-6">
              <label class="required" for="project_name">Projektname</label>
              <input type="text" id="project_name" name="project_name" class="form-control"
                placeholder="Enter Projektname" required />
            </div>

            <!-- Project Image -->
            <div class="form-group col-md-6">
              <label for="image">Projektbild</label>
              <input type="file" class="form-control" style="padding: 4px 4px" name="image" id="image"
                accept="image/*" />
              <small class="form-text text-muted">Nur Bilddateien (jpg, png, etc.) erlaubt.</small>
              <div class="mt-2" id="imagePreviewContainer" style="display: none">
                <strong>Vorschau:</strong><br />
                <img id="imagePreview" src="#" alt="Bildvorschau" style="max-width: 100px; border-radius: 8px" />
              </div>
            </div>

            <!-- Location -->
            <div class="form-group col-md-6">
              <label class="required" for="location">Standort</label>
              <input type="text" id="location" name="location" class="form-control" placeholder="Enter Standort"
                required />
            </div>

            <!-- Contractor -->
            <div class="form-group col-md-6">
              <label class="required" for="assigned_contractor_id">Auftragnehmer</label>
              <select id="assigned_contractor_id" name="assigned_contractor_id" class="form-control" required>
                <option selected disabled>Bitte wählen</option>
                <% contractors.forEach(function(user) { %>
                  <option value="<%= user.id %>"><%= user.name %></option>
                <% }); %>
              </select>
            </div>

            <!-- Timeframe -->
            <div class="form-group col-md-6">
              <label class="required" for="timeframe">Zeitrahmen</label>
              <input type="text" id="timeframe" name="timeframe" class="form-control"
                placeholder="Wählen Sie den Zeitraum" required autocomplete="off" />
            </div>

            <!-- Dynamic Selection Section -->
            <div class="form-group col-md-12">
              <h6 style="color: rgb(0, 153, 51); font-weight: 500; margin-top: 10px; text-decoration: underline;">
                Auswahl der Produktartikelnummer ------->
              </h6>
            </div>

            <div id="productSectionsContainer" class="row col-md-12">
              <div class="product-section row col-md-12">
                <!-- Model Select -->
                <div class="form-group col-md-3">
                  <label class="required d-block">Produkt</label>
                  <select name="project_model_id[]" class="form-control modelSelect" required>
                    <option value="">Product wählen</option>
                    <% productModels.forEach(function(model) { %>
                      <option value="<%= model.id %>"><%= model.model_name %></option>
                    <% }); %>
                  </select>
                </div>

                <!-- Package Select -->
                <div class="form-group col-md-3">
                  <label class="required d-block">Teil</label>
                  <select name="package_id[]" class="form-control packageSelect" disabled required>
                    <option value="">Artikelwählen</option>
                  </select>
                </div>

                <!-- Warehouse Items -->
                <div class="form-group col-md-4">
                  <label class="required d-block">Seriennummern auswählen</label>
                  <div class="warehouseItemsContainer"
                    style="max-height: 200px; overflow-y: auto; border: 1px solid #ccc; border-radius: 6px; padding: 10px; background: #fafafa;">
                    <small class="text-muted">Bitte Modell & Artikelauswählen</small>
                  </div>
                </div>

                <div class="form-group col-md-2">
                  <label class="d-block visually-hidden">Aktion</label>
                  <button type="button" class="btn btn-success addProductBtn">+</button>
                  <button type="button" class="btn btn-danger removeProductBtn">-</button>
                </div>
              </div>
            </div>

            <!-- Description -->
            <div class="form-group col-md-6">
              <label for="project_description">Beschreibung</label>
              <textarea id="project_description" name="project_description" class="form-control" rows="3"
                placeholder="Projektbeschreibung eingeben"></textarea>
            </div>

            <!-- Status -->
            <div class="form-group col-md-6">
              <label class="required" for="status">Status</label>
              <select id="status" name="status" class="form-control" required>
                <option selected disabled>Status wählen</option>
                <option value="1">Aktiv</option>
                <option value="0">Inaktiv</option>
                <option value="2">Completed</option>
              </select>
            </div>
          </div>
        </div>

        <div class="card-footer">
          <button type="submit" class="btn btn-info">Speichern</button>
          <a href="/manage-project/list" class="btn btn-secondary">Zurück</a>
        </div>
      </div>
    </form>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/locale/de.js"></script>
<script>
  moment.locale("de");

  // Image Preview
  $("#image").on("change", function () {
    const file = this.files[0];
    const previewContainer = $("#imagePreviewContainer");
    const preview = $("#imagePreview");

    if (file) {
      const reader = new FileReader();
      reader.onload = function (e) {
        preview.attr("src", e.target.result);
        previewContainer.show();
      };
      reader.readAsDataURL(file);
    } else {
      preview.attr("src", "#");
      previewContainer.hide();
    }
  });

  // Date Range Picker
  $("#timeframe").daterangepicker({
    autoUpdateInput: true,
    locale: {
      format: "D MMMM YYYY",
      separator: " - ",
      applyLabel: "Anwenden",
      cancelLabel: "Abbrechen",
      fromLabel: "Von",
      toLabel: "Bis",
      customRangeLabel: "Benutzerdefiniert",
      weekLabel: "W",
      daysOfWeek: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
      monthNames: [
        "Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"
      ],
      firstDay: 1
    }
  });

let sectionIndex = 0; // initial section index

// Helper to get all selected package IDs
function getSelectedPackages() {
  let selected = [];
  $(".packageSelect").each(function () {
    const val = $(this).val();
    if (val) selected.push(val);
  });
  return selected;
}

$(document).ready(function () {

  // Add new product section
  $(document).on("click", ".addProductBtn", function () {
    sectionIndex++;
    const section = $(".product-section:first").clone();

    // Reset selects
    section.find(".modelSelect").val("");
    section.find(".packageSelect").html('<option value="">Artikelwählen</option>').prop("disabled", true);
    section.find(".warehouseItemsContainer").html('<small class="text-muted">Bitte Modell & Artikelauswählen</small>');

    section.find(".warehouseItemsContainer").attr("data-index", sectionIndex);

    $("#productSectionsContainer").append(section);
  });

  // Remove product section
  $(document).on("click", ".removeProductBtn", function () {
    if ($(".product-section").length > 1) {
      $(this).closest(".product-section").remove();
    }
  });

  // Load packages when model changes
  $(document).on("change", ".modelSelect", function () {
    const modelId = $(this).val();
    const section = $(this).closest(".product-section");
    const packageSelect = section.find(".packageSelect");
    const itemsContainer = section.find(".warehouseItemsContainer");
    const index = section.find(".warehouseItemsContainer").attr("data-index") || 0;

    packageSelect.prop("disabled", true).html("<option>Lädt...</option>");
    itemsContainer.html("<small class='text-muted'>Bitte Artikelauswählen</small>");

    $.get("/manage-project/packages/" + modelId, function (res) {
      packageSelect.prop("disabled", false).html('<option value="">Artikelwählen</option>');

      if (res.length === 0) {
        packageSelect.append('<option disabled>Keine Artikelgefunden</option>');
        return;
      }

      // Filter out already selected packages
      const selectedPackages = getSelectedPackages();

      res.forEach(pkg => {
        if (!selectedPackages.includes(pkg.id.toString())) {
          packageSelect.append(`<option value="${pkg.id}">${pkg.package_number}</option>`);
        }
      });
    });
  });

  // Load warehouse items when package changes
  $(document).on("change", ".packageSelect", function () {
    const packageId = $(this).val();
    const section = $(this).closest(".product-section");
    const itemsContainer = section.find(".warehouseItemsContainer");
    const index = section.find(".warehouseItemsContainer").attr("data-index") || 0;

    itemsContainer.html("<em>Lädt...</em>");

    $.get("/manage-project/warehouse-items/" + packageId, function (res) {
      itemsContainer.html("");
      if (res.length === 0) {
        itemsContainer.html('<div class="text-muted"><em>Keine Daten gefunden</em></div>');
        return;
      }
      res.forEach(item => {
        itemsContainer.append(`
          <div class="form-check">
            <input class="form-check-input" type="checkbox"
              name="warehouse_items[${index}][]" value="${item.item_id}" id="item_${index}_${item.item_id}">
            <label class="form-check-label" for="item_${index}_${item.item_id}">${item.serial_number}</label>
          </div>
        `);
      });
    });
  });

});


</script>
