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

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

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

            // Validate PO
            let po = $("#invoice_id");
            if (!po.val()) {
                valid = false;
                po.addClass("is-invalid");
                po.after('<span class="text-danger validation-errors">PO is required.</span>');
            }

            let supplier_name = $("#supplier_name");
            if (!supplier_name.val()) {
                valid = false;
                supplier_name.addClass("is-invalid");
                supplier_name.after(
                    '<span class="text-danger validation-errors">Supplier Name is required.</span>');
            }

            let total_amount = $("#total_amount");
            if (!total_amount.val() || total_amount.val() <= 0) {
                valid = false;
                total_amount.addClass("is-invalid");
                total_amount.after(
                    '<span class="text-danger validation-errors">Grand Amount is required and must be greater than 0.</span>');
            }

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

            // Validate PO Items
            let items = $("#item_id").val();
            if (!items || items.length === 0) {
                valid = false;
                $("#item_id").addClass("is-invalid");
                $("#item_id").after(
                    '<span class="text-danger validation-errors">At least one PO Item must be selected.</span>'
                );
            }

            // --- ITEM LEVEL VALIDATIONS ---
            $("[name*='[supplier_bill_no]']").each(function() {
                let input = $(this);
                if (!input.val()) {
                    valid = false;
                    input.addClass("is-invalid");
                    input.after(
                        '<span class="text-danger validation-errors">Supplier Bill No is required.</span>'
                    );
                }
            });

            $("[name*='[description]']").each(function() {
                let input = $(this);
                if (!input.val()) {
                    valid = false;
                    input.addClass("is-invalid");
                    input.after(
                        '<span class="text-danger validation-errors">Description is required.</span>'
                    );
                }
            });

            $("[name*='[code]']").each(function() {
                let input = $(this);
                if (!input.val()) {
                    valid = false;
                    input.addClass("is-invalid");
                    input.after(
                        '<span class="text-danger validation-errors">Item Code is required.</span>'
                    );
                }
            });

            $("[name*='[quantity_ordered]']").each(function() {
                let input = $(this);
                if (!input.val() || parseFloat(input.val()) <= 0) {
                    valid = false;
                    input.addClass("is-invalid");
                    input.after(
                        '<span class="text-danger validation-errors">Qty Ordered must be greater than 0.</span>'
                    );
                }
            });

            $("[name*='[quantity_received]']").each(function() {
                let input = $(this);
                if (!input.val() || parseFloat(input.val()) < 0) {
                    valid = false;
                    input.addClass("is-invalid");
                    input.after(
                        '<span class="text-danger validation-errors">Qty Received cannot be negative.</span>'
                    );
                }
            });

            // --- BATCH LEVEL VALIDATIONS ---
            $(".grn-row").each(function() {
                let row = $(this);

                let batch = row.find("input[name*='[batch]']");
                let mfg = row.find("input[name*='[mfg_date]']");
                let exp = row.find("input[name*='[exp_date]']");
                let qty = row.find("input[name*='[receiving_qty]']");
                let unitPrice = row.find("input[name*='[unit_price]']");
                let unit = row.find("input[name*='[unit]']");
                let total = row.find("input[name*='[total_amount]']");

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

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

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

                let qtyVal = parseFloat(qty.val());
                if (isNaN(qtyVal) || qtyVal <= 0) {
                    valid = false;
                    qty.addClass("is-invalid");
                    qty.after(
                        '<span class="text-danger validation-errors">Quantity Receiving must be greater than 0.</span>'
                    );
                }

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

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

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

            if (!valid) {
                e.preventDefault();
                e.stopPropagation();

                // Optional: focus first invalid input
                form.find(".is-invalid").first().focus();
            }
        });
    });
</script>
