/*
 * 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/.
 */


$('#name').on('input propertychange paste', function () {
    $('#name_title').text($('#name').val());
});

var pricingtable = $('#pricingtable').DataTable({
    responsive: {
        details: {
            display: $.fn.dataTable.Responsive.display.modal({
                header: function (row) {
                    var data = row.data();
                    return "<i class=\"fas fa-box fa-fw\"></i> " + data[2];
                }
            }),
            renderer: $.fn.dataTable.Responsive.renderer.tableAll({
                tableClass: 'table'
            }),
            type: "column"
        }
    },
    columnDefs: [
        {
            targets: 0,
            className: 'control',
            orderable: false
        },
        {
            targets: 1,
            orderable: false
        }
    ],
    order: [
        [2, 'asc']
    ]
});

$("#pricingtable").on("click", ".deletepricebtn", function () {
    pricingtable.row($("#pricingtable tr[data-itemid=" + $(this).data("itemid") + "]")).remove();
    pricingtable.draw();
});

function findItem(q) {
    function decodeThenSetItem(item) {
        var name = item['name'];
        var id = item['id'];
        var price = item['price'];
        var cost = item['price'];

        $("#pricemodal").data("itemid", id);
        $("#pricemodalitemname").text(name);
        $("#pricemodalitemcost").text(cost);
        $("#pricemodalitemprice").text(price);
        $("#pricemodalcustomerprice").val(price);
    }
    if (q == "") {
        return;
    }
    $.get("action.php", {
        action: "itemsearch",
        q: q
    }, function (data) {
        if (data['items'].length == 1) {
            decodeThenSetItem(data['items'][0]);
        } else if (data['items'].length > 1) {
            var options = [];
            for (var i = 0; i < data['items'].length; i++) {
                var text = data['items'][i]['name'];
                if (data['items'][i]['price'] != null) {
                    text += " <span class=\"ml-auto\">$" + data['items'][i]['price'] + "</span>";
                }
                options.push({"text": text, "val": data['items'][i]['id']});
            }
            bschoices(
                    "Multiple Results",
                    "More than one item match the query.  Pick the correct one:",
                    options,
                    "Cancel",
                    function (result) {
                        for (var i = 0; i < data['items'].length; i++) {
                            if (data['items'][i]['id'] == result) {
                                decodeThenSetItem(data['items'][i]);
                                break;
                            }
                        }
                    }
            );
        }
    }).fail(function () {
        alert("Error");
    });
}

$("#pricemodalitem").on('keypress', function (e) {
    if (e.which === 13) {
        findItem($("#pricemodalitem").val());
        $("#pricemodalitem").val("");
    }
});

$("#pricemodalsearch").on("click", function () {
    findItem($("#pricemodalitem").val());
    $("#pricemodalitem").val("");
});

$("#addcustomerpricebtn").click(function () {
    $("#pricemodal").data("itemid", "");
    $("#pricemodal").modal();
});

$("#pricemodalsave").click(function () {
    var itemid = $("#pricemodal").data("itemid");
    var name = $("#pricemodalitemname").text();
    var cost = $("#pricemodalitemcost").text();
    var price = $("#pricemodalitemprice").text();
    var custprice = $("#pricemodalcustomerprice").val();
    var rownumber = $("#pricingtable tbody tr").length;
    var html = ''
            + '<tr data-itemid="' + itemid + '">'
            + '    <td></td>'
            + '    <td>'
            + '        <div class="btn btn-sm btn-danger deletepricebtn" data-itemid="' + itemid + '"><i class="fas fa-trash"></i> Delete</div>'
            + '    </td>'
            + '    <td>'
            + '        <input type="hidden" name="pricing[' + rownumber + '][item]" value="' + itemid + '" />'
            + '        ' + name
            + '    </td>'
            + '    <td>' + cost + '</td>'
            + '    <td>' + price + '</td>'
            + '    <td>'
            + '        <input type="hidden" name="pricing[' + rownumber + '][price]" value="' + custprice + '" />'
            + '        ' + custprice
            + '    </td>'
            + '</tr>';
    pricingtable.row.add($(html));
    pricingtable.draw();
    $("#pricemodal").modal("hide");
})