<script>
/* ============================================================
   6️⃣ WAREHOUSE FORM MODULE
============================================================ */

document.getElementById("addRow").addEventListener("click", function () {

    const container = document.getElementById("warehouseRows");

    const newRow = document.createElement("div");
    newRow.className = "warehouse-row row mb-2";

    newRow.innerHTML = `
       <div class="form-group basic  col-md-3">
            <div class="input-wrapper">
                <label class="label">Warehouse Name</label>
                <input type="text" name="warehouse_name[]" class="form-control"  required>
            </div>
        </div>

        <div class="form-group basic  col-md-3">
            <div class="input-wrapper">
                <label class="label">Location</label>
                <input type="text" name="location[]" class="form-control"  required>
            </div>
        </div>

        <div class="form-group basic  col-md-2">
            <div class="input-wrapper">
                <label class="label">Capacity</label>
                <input type="number" name="capacity[]" class="form-control"  required>
            </div>
        </div>

        <div class="form-group basic  col-md-2">
       <div class="live-search-wrapper"
                         data-endpoint="fetch_scripts/get_store_managers.php"
                         data-hidden-name="manager_id[]"
                         data-display-fields="firstname,secondname"
                         data-value-field="id">
                    
                        <label class="label">Manager</label>
                    
                        <!-- ❌ REMOVE name from text input -->
                        <input type="text"
                               class="form-control liveSearchInput"
                               placeholder="Search..."
                               autocomplete="off">
                    
                        <!-- ✅ ADD name here instead -->
                        <input type="hidden"
                               class="liveHiddenInput"
                               name="manager_id[]">
                    
                        <div class="liveResults"></div>
                    </div>
        </div>
        <div class="form-group basic col-md-2 d-flex align-items-center">
            <button type="button" class="btn btn-danger btn-sm removeRow">Remove</button>
        </div>
    `;

            container.appendChild(newRow);
            
            const newSelect = newRow.querySelector(".managerSelect");
            populateSingleManagerDropdown(newSelect);
});



/* Remove Row (Event Delegation) */
document.getElementById("warehouseRows")
    .addEventListener("click", function (e) {
        if (e.target.classList.contains("removeRow")) {
            e.target.closest(".warehouse-row").remove();
        }
    });


/* Submit Multiple Warehouses */
document.getElementById("warehouseForm")
    .addEventListener("submit", function (e) {

        e.preventDefault();

        const formData = new FormData(this);

        fetch('../includes/save_warehouses.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {

            if (data.status === "success") {

                //alert("Warehouses saved successfully");
                showToast("Warehouses saved successfully", "success");


                this.reset();
                document.getElementById("warehouseRows").innerHTML = "";
                document.getElementById("addRow").click();

            } else {

               // alert("Error: " + (data.message || "Unknown error"));
               showToast(data.message || "Unknown error", "error");

            }
        })
        .catch(err => {
            console.error(err);
            alert("Server error — check console");
        });
    });


function resetWarehouseForm() {

    const form = document.getElementById("warehouseForm");
    const container = document.getElementById("warehouseRows");

    form.reset();
    container.innerHTML = "";

    const firstRow = document.createElement("div");
    firstRow.className = "warehouse-row row mb-2";

    firstRow.innerHTML = `
      <div class="form-group basic  col-md-3">
                            <div class="input-wrapper">
                            <label class="label" for="name2">WarehouseName</label>
                            <input type="text" name="warehouse_name[]" class="form-control"  required>
            </div>
        </div>

        <div class="form-group basic  col-md-3">
            <div class="input-wrapper">
                <label class="label">Location</label>
                <input type="text" name="location[]" class="form-control"  required>
            </div>
        </div>

        <div class="form-group basic  col-md-2">
            <div class="input-wrapper">
                <label class="label">Capacity</label>
                <input type="number" name="capacity[]" class="form-control"  required>
            </div>
        </div>

        <div class="form-group basic  col-md-2">
                    <div class="live-search-wrapper"
                         data-endpoint="fetch_scripts/get_store_managers.php"
                         data-hidden-name="manager_id[]"
                         data-display-fields="firstname,secondname"
                         data-value-field="id">
                    
                        <label class="label">Manager</label>
                    
                        <!-- ❌ REMOVE name from text input -->
                        <input type="text"
                               class="form-control liveSearchInput"
                               placeholder="Search..."
                               autocomplete="off">
                    
                        <!-- ✅ ADD name here instead -->
                        <input type="hidden"
                               class="liveHiddenInput"
                               name="manager_id[]">
                    
                        <div class="liveResults"></div>
                    </div>
        </div>

        <div class="form-group basic col-md-2 d-flex align-items-center">
            <button type="button" class="btn btn-danger btn-sm removeRow" style="display:none;">Remove</button>
        </div>
    `;

    container.appendChild(firstRow);

    
}



</script>