document.addEventListener("DOMContentLoaded", function () {
    // Format all existing inputs on page load
    document.querySelectorAll(".indianCurrencyFormat").forEach((input) => {
        formatInputFieldIndianCurrency(input);
    });

    // Event delegation: works for dynamically added inputs too
    document.addEventListener("input", function (e) {
        if (e.target.classList.contains("indianCurrencyFormat")) {
            formatInputFieldIndianCurrency(e.target);
        }
    });
});

function formatInputFieldIndianCurrency(input) {
    // Remove any non-digit characters (except for periods) from the input
    let inputVal = input.value.replace(/[^\d]/g, "");

    if (inputVal == "") {
        input.value = "";
        return;
    }

    // Split the input into whole number and decimal parts (if any)
    let [whole, decimal] = inputVal.split(".");

    // Format the whole number part with Indian comma separators
    whole = formatIndianCurrency(whole);

    // Combine the whole number and decimal parts (if any)
    input.value = decimal ? `₹ ${whole}.${decimal}` : `₹${whole}`;
}

function formatIndianCurrency(whole) {
    if (whole == "") {
        return "0";
    }
    let wholeNum = parseInt(whole);
    if (wholeNum == 0) {
        return "0";
    }
    whole = wholeNum.toString();
    let lastThree = whole.slice(-3);
    let otherNumbers = whole.slice(0, -3);
    if (otherNumbers !== "") {
        lastThree = "," + lastThree;
    }
    let result = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
    return result;
}
