/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

function addPayment(type, icon, text) {
    var extrafield = "";
    if (type == "giftcard") {
        extrafield = ''
                + '        <div class="input-group-prepend input-group-append">'
                + '            <span class="input-group-text">'
                + '                #'
                + '            </span>'
                + '        </div>'
                + '        <input class="form-control giftcard-number" type="number" />'
                + '        <div class="input-group-prepend input-group-append">'
                + '            <span class="btn btn-outline-primary open-number-pad-btn" data-gc="1">'
                + '                <i class="fas fa-keyboard"></i>'
                + '            </span>'
                + '        </div>';
    }
    var amount = "";
    // Autofill the exact due amount for payment methods that are flexible like that
    if (type == "check" || type == "card" || type == "crypto") {
        if ($("#owed-amount").text() * 1.0 > 0) {
            amount = ($("#owed-amount").text() * 1.0).toFixed(2);
        }
    }

    $("#payment-lines").append(''
            + '<div class="list-group-item">'
            + '    <div class="input-group">'
            + '        <div class="input-group-prepend">'
            + '            <span class="input-group-text">'
            + '                <i class="' + icon + ' fa-fw mr-1"></i> '
            + text
            + '            </span>'
            + '        </div>'
            + '        <div class="input-group-prepend">'
            + '            <span class="input-group-text">'
            + '                $'
            + '            </span>'
            + '        </div>'
            + '        <input class="form-control payment-entry" type="money" data-type="' + type + '" value="' + amount + '" />'
            + '        <div class="input-group-prepend input-group-append">'
//            + '            <span class="btn btn-outline-primary open-number-pad-btn" data-gc="0">'
//            + '                <i class="fas fa-keyboard"></i>'
//            + '            </span>'
            + '            <span class="btn btn-outline-success open-money-pad-btn">'
            + '                <i class="fas fa-calculator"></i>'
            + '            </span>'
            + '        </div>'
            + extrafield
            + '        <div class="input-group-append">'
            + '            <span class="btn btn-outline-danger remove-payment-btn">'
            + '                <i class="fas fa-trash"></i>'
            + '            </span>'
            + '        </div>'
            + '    </div>'
            + '</div>');
    $("#payment-lines .payment-entry").last().focus();

    if (type == "cash") {
        bsmoneypad("Currency Calculator", 0.0, "Save", "Cancel", null, function (answer) {
            $("#payment-lines .payment-entry").last().val(answer);
            recalculate();
        });
    }
}

function checkGiftCardBalance() {
    $("#payment-lines .list-group-item:has(.giftcard-number)").each(function () {
        var paymentbox = $(".payment-entry", this);
        var cardnumberbox = $(".giftcard-number", this);
        var amount = paymentbox.val() * 1.0;
        var cardnumber = cardnumberbox.val();
        if (cardnumber == "") {
            return;
        }
        $.get("action.php", {
            action: "giftcard_lookup",
            code: cardnumber
        }, function (json) {
            if (json.status == "OK") {
                if (json.cards.length == 0) {
                    bsalert("Invalid Gift Card", "Gift card #" + cardnumber + " does not exist.  Remove it to finish the transaction.");
                    cardnumberbox.addClass('is-invalid');
                } else if (json.cards.length == 1) {
                    if (json.cards[0].balance < amount) {
                        bsalert("Insufficient Gift Card Balance", "Gift card #" + cardnumber + " does not contain enough funds.  The amount has been set to the full amount remaining on the card ($" + json.cards[0].balance + ").");
                        paymentbox.val(json.cards[0].balance);
                    }
                    cardnumberbox.removeClass('is-invalid');
                } else {
                    bsalert("Invalid Gift Card", "Unable to determine which gift card #" + cardnumber + " is referring to.  Remove it to finish the transaction.");
                    cardnumberbox.addClass('is-invalid');
                }
            } else {
                bsalert("Invalid Gift Card", "Unable to determine which gift card #" + cardnumber + " is referring to.  Remove it to finish the transaction.");
                cardnumberbox.addClass('is-invalid');
            }
        });
    });
}

$("#payment-lines").on("change keyup blur", ".payment-entry", function () {
    recalculate();
});

$("#payment-lines").on("blur", ".giftcard-number,.payment-entry[data-type=giftcard]", function () {
    checkGiftCardBalance();
});

$("#payment-lines").on("keypress", ".giftcard-number,.payment-entry[data-type=giftcard]", function (e) {
    if (e.which === 13) {
        checkGiftCardBalance();
    }
});

$("#payment-lines").on("click", ".remove-payment-btn", function () {
    $(this).closest(".list-group-item").remove();
    recalculate();
});

$("#payment-lines").on("click", ".open-money-pad-btn", function () {
    var inputbox = $(this).parents('.input-group').children(".payment-entry");
    var value = inputbox.val();
    if (isNaN(value)) {
        value = 0.0;
    }
    bsmoneypad("Currency Calculator", value * 1.0, "Save", "Cancel", null, function (answer) {
        inputbox.val(answer);
        recalculate();
    });
});

$("#payment-lines").on("click", ".open-number-pad-btn", function () {
    if ($(this).data('gc') == '1') {
        var inputbox = $(this).parents('.input-group').children(".giftcard-number");
    } else {
        var inputbox = $(this).parents('.input-group').children(".payment-entry");
    }
    var value = inputbox.val();
    if (isNaN(value)) {
        value = '';
    }
    bsnumpad("Keyboard", value, "Save", "Cancel", function (answer) {
        inputbox.val(answer);
        recalculate();
    });
});

$("#paymentbtn").click(function () {
    $("#paymentui").removeClass("d-none");
});

$(".payment-method-button").click(function () {
    addPayment($(this).data("payment-method"), $(this).data("icon"), $(this).data("text"));
});

$("#discountpercentbtn").click(function () {
    bsprompt("Sale Discount",
            "Enter a percentage to discount the transaction",
            "Discount",
            "Cancel",
            "number",
            function (result) {
                if (result <= 0 || result >= 100) {
                    $("#discountpercentbtn").data("percent", 0.0);
                    $("#discountpercentbtnlabel").text("");
                    recalculate();
                    return;
                }
                $("#discountpercentbtn").data("percent", result);
                $("#discountpercentbtnlabel").text(result);
                recalculate();
            });
})