<script>
    $(document).ready(function() {
        $(".needs-validation").on("submit", function(e) {
            let form = $(this);
            let valid = true;

            // Remove previous errors
            form.find(".is-invalid").removeClass("is-invalid");
            form.find(".validation-errors").remove();

            // --- TOP LEVEL FIELDS ---
            const topFields = [{
                    id: "#code",
                    msg: "Code is required."
                },
                {
                    id: "#company_id",
                    msg: "Company is required."
                },
                {
                    id: "#product_id",
                    msg: "Product is required."
                },
                {
                    id: "#batch_id",
                    msg: "Batch is required."
                },
            ];

            topFields.forEach(field => {
                let el = $(field.id);
                if (!el.val()) {
                    valid = false;
                    el.addClass("is-invalid");
                    el.after(`<span class="text-danger validation-errors">${field.msg}</span>`);
                }
            });

            // --- ITEM VALIDATION ---
            const items = $(".item-set");
            if (items.length === 0) {
                valid = false;
                $("#item-group").append(
                    '<span class="text-danger validation-errors">At least one item is required.</span>'
                );
            }

            items.each(function(index) {
                const row = $(this);

                const rawMaterial = row.find("select[name*='[raw_material_item]']");
                const sir = row.find("select[name*='[sir_item_id]']");
                const qty = row.find("input[name*='[quantity]']");
                const sirQty = parseFloat(row.find("input[name*='[sir_qty]']").val()) || 0;
                const unitPrice = row.find("input[name*='[unit_price]']");
                const unit = row.find("input[name*='[unit]']");
                const total = row.find("input[name*='[total_amount]']");

                // Raw Material
                if (!rawMaterial.val()) {
                    valid = false;
                    rawMaterial.addClass("is-invalid");
                    rawMaterial.after(
                        '<span class="text-danger validation-errors">Raw Material is required.</span>'
                    );
                }

                // SIR
                if (!sir.val()) {
                    valid = false;
                    sir.addClass("is-invalid");
                    sir.after(
                        '<span class="text-danger validation-errors">Store Issue Requisition is required.</span>'
                    );
                }

                // Quantity validation
                const qtyVal = parseFloat(qty.val());
                const selectedSir = row.find("select[name*='[sir_item_id]'] option:selected");
                const selectedSirQty = parseFloat(selectedSir.data("qty")) || 0;              

                if (!qty.val() || isNaN(qtyVal) || qtyVal < 0.01) {
                    valid = false;
                    qty.addClass("is-invalid");
                    qty.after(
                        '<span class="text-danger validation-errors">Quantity must be ≥ 0.01.</span>'
                    );
                } else if (selectedSirQty > 0 && qtyVal > selectedSirQty) {
                    valid = false;
                    qty.addClass("is-invalid");
                    qty.after(
                        `<span class="text-danger validation-errors">Quantity cannot exceed ${selectedSirQty}.</span>`
                    );
                }


                // Unit Price
                const unitPriceVal = parseFloat(unitPrice.val());
                if (!unitPrice.val() || isNaN(unitPriceVal) || unitPriceVal < 0) {
                    valid = false;
                    unitPrice.addClass("is-invalid");
                    unitPrice.parents('.input-group').after(
                        '<span class="text-danger validation-errors">Unit Price must be ≥ 0.</span>'
                    );
                }

                // Unit
                if (!unit.val()) {
                    valid = false;
                    unit.addClass("is-invalid");
                    unit.parents('.input-group').after(
                        '<span class="text-danger validation-errors">Unit is required.</span>'
                    );
                }

                // Total
                const totalVal = parseFloat(total.val());
                if (!total.val() || isNaN(totalVal) || totalVal < 0) {
                    valid = false;
                    total.addClass("is-invalid");
                    total.after(
                        '<span class="text-danger validation-errors">Total must be ≥ 0.</span>'
                    );
                }
            });

            if (!valid) {
                e.preventDefault();
                e.stopPropagation();
                form.find(".is-invalid").first().focus();
            } else {
                // Prevent infinite loop of submit handler
                form.off("submit").submit();
            }
        });
    });
</script>
