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

            // Reset old errors
            form.find(".is-invalid").removeClass("is-invalid");
            form.find(".validation-errors").remove();

            // --- TOP LEVEL FIELDS ---

            let code = $("#code");
            if (!code.val() || code.val().length > 255) {
                valid = false;
                code.addClass("is-invalid");
                code.after(
                    '<span class="text-danger validation-errors">Code is required (max 255 chars).</span>'
                );
            }

            let batch = $("#batch_id");
            if (!batch.val()) {
                valid = false;
                batch.addClass("is-invalid");
                batch.parent().append(
                    '<span class="text-danger validation-errors">Batch is required.</span>');
            }

            let product = $("#product_variation_id");
            if (!product.val()) {
                valid = false;
                product.addClass("is-invalid");
                product.parent().append(
                    '<span class="text-danger validation-errors">Product is required.</span>');
            }

            let company = $("#company_id");
            console.log("🚀 ~ company:", company.val())
            if (!company.val()) {
                valid = false;
                company.addClass("is-invalid");
                company.after(
                    '<span class="text-danger validation-errors">Company is required.</span>');
            }

            // --- ITEMS VALIDATION ---
            let items = $(".item-set"); // assuming .grn-row = 1 item row
            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() {
                let row = $(this);

                let qty = row.find("input[name*='[quantity]']");
                let max_quantity = row.find("input[name*='[max_quantity]']");
                let unitPrice = row.find("input[name*='[unit_price]']");
                let unit = row.find("input[name*='[unit]']");
                let total = row.find("input[name*='[total]']");
                let raw_material_item = row.find(".raw_material_items_dropdown");
                let batchDropdown = row.find(".batchDropdown");
                let stock = row.find(".stock");

                let qtyVal = parseFloat(qty.val());
                let maxQty = parseFloat(max_quantity.val());

                console.log(qtyVal, maxQty);

                if (raw_material_item.val() == null || raw_material_item.val() == '' ||
                    raw_material_item.val() == 'null') {
                    valid = false;
                    raw_material_item.addClass("is-invalid");
                    raw_material_item.parent().append(
                        '<span class="text-danger validation-errors">Raw Material Item is required.</span>'
                    );
                }

                if (batchDropdown.val() == null || batchDropdown.val() == '' || batchDropdown
                    .val() == 'null') {
                    valid = false;
                    batchDropdown.addClass("is-invalid");
                    batchDropdown.parent().append(
                        '<span class="text-danger validation-errors">GRN Item Batch is required.</span>'
                    );
                }

                // if (stock.val() == null || stock.val() == '' || stock.val() == 'null') {
                //     valid = false;
                //     stock.addClass("is-invalid");
                //     stock.parent().append(
                //         '<span class="text-danger validation-errors">Stock is required.</span>'
                //     );
                // }

                let availableQty = batchDropdown.find('option:selected').attr(
                    'data-available_qty') ?? 0;
                console.log(availableQty);

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

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

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

                let 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 is required (must be ≥ 0).</span>'
                    );
                }
            });

            console.log(valid);

            if (!valid) {
                e.preventDefault();
                form.find(".is-invalid").first().focus();
            } else {
                form.off("submit"); // prevent recursive trigger
                form[0].submit(); // native submit
            }


            // if (!valid) {
            //     e.preventDefault();
            //     // e.stopPropagation();
            //     form.find(".is-invalid").first().focus();
            // }
            // if (valid) {
            //     // form.off("submit").submit(function(e) {
            //     //     e.preventDefault();
            //     //     e.stopPropagation();
            //     //     form.submit();
            //     // });
            //     form.submit();
            // }
        });
    });
</script>
