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

var customerid = "";
var customername = "";
var customeremail = "";
var customerphone = "";

$(document).ready(function () {
    if ($("#edit_customerid").length) {
        customerid = $("#edit_customerid").val();
    }
});

function showCustomerList(search) {
    if (search == "") {
        return;
    }
    $.get('action.php', {
        action: 'customersearch',
        q: search
    }, function (data) {
        var html = "";
        if (data['customers'].length > 0) {
            for (var i = 0; i < data['customers'].length; i++) {
                var id = data['customers'][i]['id'];
                var name = data['customers'][i]['name'];
                var email = "";
                if (typeof data['customers'][i]['email'] == 'string' && data['customers'][i]['email'].includes("@")) {
                    email = data['customers'][i]['email'];
                }
                var phone = "";
                if (typeof data['customers'][i]['phone'] == 'string') {
                    phone = data['customers'][i]['phone'];
                }
                html += '<div class="list-group-item customer d-flex justify-content-between flex-wrap" data-id="' + id + '" data-name="' + name + '" data-email="' + email + '" data-phone="' + phone + '">'
                        + '<div>' + name + '</div>'
                        + '<div>' + email + '</div>'
                        + '<div>' + phone + '</div>'
                        + '</div>';
            }
        } else {
            html = '<div class="list-group-item"><i class="fas fa-search-minus"></i> No results.</div>';
        }
        $("#customerselection").html(html);
    });
}

$("#addcustomerbtn").click(function () {
    $("#customermodal").modal();
});

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

$("#customersearchbtn").on("click", function () {
    showCustomerList($("#customersearch").val());
    $("#customersearch").val("");
});

$("#customermodal").on("shown.bs.modal", function () {
    $("#customersearch").focus();
})

$("#customerselection").on("click", ".list-group-item.customer", function () {
    customerid = $(this).data("id");
    customername = $(this).data("name");
    customeremail = $(this).data("email");
    customerphone = $(this).data("phone");
    $("#customerbtnlabel").text(customername);
    console.log(customername);
    $("#customermodal").modal('hide');
    loadGridView();
});