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

$(document).on("click", ".openProductModal", function () {

    // Close action sheet first
    $("#pdtModalBasic").modal("show");
    

    // Wait until it's closed, then open product modal
    setTimeout(function () {
        $("#productActionSheet").modal("hide");
    }, 400);

});

$(document).on("click", ".openProductcatModal", function () {

    // Close action sheet first
    $("#pdtcatModalBasic").modal("show");
    

    // Wait until it's closed, then open product modal
    setTimeout(function () {
        $("#productActionSheet").modal("hide");
    }, 400);

});

/* Add Product Row (Event Delegation) */

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

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

    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">Product Category Name</label>
                <input type="text" name="pdt_categname[]" class="form-control"  required>
            </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);
});

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

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

    const newRow = document.createElement("div");
    newRow.className = "warehouse-row row mb-2";
         // container.appendChild(newRow);
            
            const newSelect = newRow.querySelector(".managerSelect");
            populateSingleManagerDropdown(newSelect);
});



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


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

        e.preventDefault();

        const formData = new FormData(this);

        fetch('../includes/save_product_category.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            $("#pdtcatModalBasic").modal("hide");

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

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


                this.reset();
                document.getElementById("productscatRows").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");
        });
    });


document.getElementById("productsForm")
    .addEventListener("submit", function (e) {

        e.preventDefault();

        const formData = new FormData(this);

        fetch('../includes/save_products.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
             $("#pdtModalBasic").modal("hide");
             
            if (data.status === "success") {

                //alert("Warehouses saved successfully");
                showToast("Product added successfully", "success");
                refreshProducts(); // reload table

                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");
        });
    });

let limit = 10;
let offset = 0;
let loading = false;
let finished = false;

$(document).ready(function () {

    loadProducts();

    $("#productScroll").on("scroll", function () {

        if (loading || finished) return;

        let container = $(this);

        let scrollTop = container.scrollTop();
        let scrollHeight = container[0].scrollHeight;
        let height = container.height();

        if (scrollTop + height >= scrollHeight - 50) {
            loadProducts();
        }

    });

});

function loadProducts() {

    if (loading || finished) return;

    loading = true;

    showLoader();

    $.ajax({
        url: "fetch_scripts/fetch_productlist.php",
        type: "GET",
        data: {
            limit: limit,
            offset: offset
        },
        dataType: "json",
        success: function (response) {

            hideLoader();

            if (response.length === 0) {

                finished = true;

                $("#productlist").append(`
                <tr>
                    <td colspan="4" class="text-center text-muted p-3">
                        No more products
                    </td>
                </tr>
                `);

                return;
            }

            let rows = "";

            response.forEach(function (product) {

                let badge = product.status.toLowerCase() === "active"
                    ? '<span class="badge badge-success">Active</span>'
                    : '<span class="badge badge-danger">Inactive</span>';
                    
                let salePrice = Number(product.p_sale_px).toLocaleString();
                let purchasePrice = Number(product.p_prch_px).toLocaleString();

                rows += `
                <tr class="product-row" data-id="${product.id}">
                    <td>${product.p_name}</td>
                    <td>${salePrice}</td>
                    <td>${purchasePrice}</td>
                    <td>${badge}</td>
                </tr>
                `;
            });

            $("#productlist").append(rows);

            offset += limit;
            loading = false;
        }
    });
}

function refreshProducts() {

    offset = 0;
    finished = false;
    loading = false;

    $("#productlist").html("");

    loadProducts();
}

function showLoader() {

    let loader = `
    <tr id="loadingRow">
        <td colspan="4" class="text-center p-3">
            <div class="spinner-border spinner-border-sm text-primary"></div>
            Loading products...
        </td>
    </tr>
    `;

    $("#productlist").append(loader);
}

function hideLoader() {
    $("#loadingRow").remove();
}


$(document).on("click", ".product-row", function () {

    let productId = $(this).data("id");

    $.ajax({
        url: "fetch_scripts/get_single_product.php",
        type: "POST",
        data: { id: productId },
        dataType: "json",
        success: function (product) {

            $("#edit_id").val(product.id);
            $("#product_name_edit").val(product.p_name);
            $("#sku_edit").val(product.sku);
            $("#product_type_edit").val(product.pdt_type);
            $("#status_edit").val(product.status);
            $("#category_id_edit").val(product.pdt_categ);
            $("#sales_rep_edit").val(product.sale_count);
            $("#rep_sort_edit").val(product.reporting_order);
            $("#selling_price_edit").val(product.p_sale_px);
            $("#sale_comm_edit").val(product.sale_comm);
            $("#sale_tax_rate_edit").val(product.sale_vat);
            $("#admin_comm_edit").val(product.admin_fee);
            $("#prch_price_edit").val(product.p_prch_px);
            $("#prch_comm_edit").val(product.prch_comm);
            $("#prch_tax_rate_edit").val(product.inp_vat);
            $("#margin_edit").val(product.margin);

            $("#editProductModal").modal("show");
        }
    });
});


$("#editProductForm").submit(function (e) {
    e.preventDefault();

    $.ajax({
        url: "fetch_scripts/update_product.php",
        type: "POST",
        data: $(this).serialize(),
        success: function (response) {

            $("#editProductModal").modal("hide");
            refreshProducts(); // reload table
        }
    });
});
</script>