/*
 * 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 sendTransactionToServer(callback) {
    var items = [];
    var payments = [];
    var customer = customerid;
    var register = $("#register").data('id');
    var discountpercent = $("#discountpercentbtn").data("percent");
    if (discountpercent <= 0) {
        discountpercent = 0.0;
    }
    var txid = "";
    if ($("#txid").length) {
        txid = $("#txid").val();
    }
    $("#pos-lines-box .list-group-item").each(function () {
        var each = $(".item-price", this).val() * 1.0;
        var qty = $(".item-qty", this).val() * 1.0;
        var code = $(this).data("code");
        var id = $(this).data("itemid");
        items.push({
            each: each,
            qty: qty,
            code: code,
            id: id
        });
    });
    $("#payment-lines .list-group-item").each(function () {
        var amount = $(".payment-entry", this).val() * 1.0;
        var type = $(".payment-entry", this).data("type");
        var code = '';
        if ($(".giftcard-number", this).length) {
            code = $(".giftcard-number", this).val();
        }
        payments.push({
            amount: amount,
            type: type,
            code: code
        });
    });

    console.log(payments);

    $.post("action.php", {
        action: "finish_transaction",
        items: items,
        payments: payments,
        customer: customer,
        register: register,
        discountpercent: discountpercent,
        txid: txid
    }, function (data) {
        if (data.status == "OK") {
            callback(data);
        } else {
            bsalert("Error", "The transaction could not be completed:<br />" + data.message);
        }
    }).fail(function () {
        bsalert("Error", "The transaction could not be completed due to an unknown error.");
    });
}

function sendReturnToServer(callback) {
    var items = [];
    var payments = [];
    var customer = customerid;
    var register = $("#register").data('id');

    $("#pos-lines-box .list-group-item").each(function () {
        var each = $(".item-price", this).val() * 1.0;
        var qty = $(".item-qty", this).val() * 1.0;
        var code = $(this).data("code");
        var id = $(this).data("itemid");
        items.push({
            each: each,
            qty: qty,
            code: code,
            id: id
        });
    });
    $("#payment-lines .list-group-item").each(function () {
        var amount = $(".payment-entry", this).val() * 1.0;
        var type = $(".payment-entry", this).data("type");
        var code = '';
        if ($(".giftcard-number", this).length) {
            code = $(".giftcard-number", this).val();
        }
        payments.push({
            amount: amount,
            type: type,
            code: code
        });
    });

    console.log(payments);

    $.post("action.php", {
        action: "finish_return",
        items: items,
        payments: payments,
        customer: customer,
        register: register
    }, function (data) {
        if (data.status == "OK") {
            callback(data);
        } else {
            bsalert("Error", "The return could not be completed: " + data.message);
        }
    }).fail(function () {
        bsalert("Error", "The return could not be completed due to an unknown error.");
    });
}

function showReceipt(txid) {
    $("#receiptchangediv").removeClass("d-none");
    $("#receiptframe").data("txid", txid);
    $("#receiptframe").attr("src", 'action.php?action=getreceipt&txid=' + txid);
    $("#receiptmodal").modal();
}

function finishTransaction() {
    sendTransactionToServer(function (data) {
        if (nickelbridge) {
            var opendrawer = false;
            if ($("#change-amount").text() * 1.0 != 0) {
                opendrawer = true;
            }
            $("#payment-lines .list-group-item").each(function () {
                var type = $(".payment-entry", this).data("type");
                if (type == 'cash' || type == 'check') {
                    opendrawer = true;
                }
            });
            if (opendrawer) {
                $.ajax("http://127.0.0.1:64269/opendrawer", {
                    contentType: 'application/json',
                    type: 'POST',
                    success: function (resp) {

                    }
                }).fail(function (resp) {
                    alert("Error: " + JSON.stringify(resp));
                });
            }
        }
        showReceipt(data.txid);
    });
}

$("#finishbtn").click(function () {
    recalculate();
    var owed = $("#owed-amount").text() * 1.0;
    if ($("#return").length) {
        if (owed > 0) {
            bsalert("Incomplete Transaction", "The customer is still owed $" + owed.toFixed(2) + ".  Add a payment or remove items until the customer is not owed anything.");
        } else if ($("#change-amount").text() * 1.0 > 0) {
            bsalert("Incomplete Transaction", "The customer would need to pay you $" + ($("#change-amount").text() * 1.0).toFixed(2) + " for the refund.  Adjust payments until the change is zero.");
        } else {
            sendReturnToServer(function (data) {
                if (nickelbridge) {
                    var opendrawer = false;
                    $("#payment-lines .list-group-item").each(function () {
                        var type = $(".payment-entry", this).data("type");
                        if (type == 'cash' || type == 'check') {
                            opendrawer = true;
                        }
                    });
                    if (opendrawer) {
                        $.ajax("http://127.0.0.1:64269/opendrawer", {
                            contentType: 'application/json',
                            type: 'POST',
                            success: function (resp) {

                            }
                        }).fail(function (resp) {
                            alert("Error: " + JSON.stringify(resp));
                        });
                    }
                }
                showReceipt(data.txid);
            });
        }
    } else {
        if (owed > 0) {
            bsalert("Incomplete Transaction", "The customer still owes $" + owed.toFixed(2) + ".  Add a payment or remove items until everything is paid for.");
        } else {
            finishTransaction();
        }
    }
});

$("#receiptprintbtn").click(function () {
    if (nickelbridge) {
        $.get('action.php', {
            action: 'getreceipt',
            format: 'json',
            width: receiptwidth,
            txid: $("#receiptframe").data('txid')
        }, function (receipt) {
            $.ajax("http://127.0.0.1:64269/print", {
                data: JSON.stringify(receipt),
                contentType: 'application/json',
                type: 'POST',
                success: function (resp) {

                }
            }).fail(function (resp) {
                alert("Error: " + JSON.stringify(resp));
            });
        });
    } else {
        document.getElementById("receiptframe").contentWindow.print();
    }
});

$("#receiptmodal").on("hide.bs.modal", function () {
    window.location.href = "app.php?page=pos";
});