$(document).ready(function () {
    $('#add-tool-modal').on('hidden.bs.modal', function () {
        clearSelections();
    });

    $('#save-tool-btn').click(function () {
        saveNewTool();
    });

    $('#b_dQuantity').click(function () {
        let quantity = $('#quantity');
        let currentValue = parseInt(quantity.val(), 10);

        if (currentValue > 0) {
            quantity.val(currentValue - 1);
        }
    });

    $('#b_iQuantity').click(function () {
        let quantity = $('#quantity');
        let currentValue = parseInt(quantity.val(), 10);
        quantity.val(currentValue + 1);
    });

    $('#selected-tool').change(function () {
        let selectedOption = $(this).find('option:selected');
        let table = selectedOption.data('table');
        $('#table').val(table);
    });
});

function clearSelections() {
    $('#table').val('');
    $('#quantity').val(0);
    $("#selected-tool").prop('selectedIndex', 0);
    $('.selectpicker').selectpicker('refresh');
}

function saveNewTool() {
    var formData = new FormData();
    formData.append('toolId', $('#selected-tool').val());
    formData.append('acKey', $('#acKey').val());
    formData.append('quantity', $('#quantity').val());
    formData.append('table', $('#table').val());

    $.ajax({
        cache: false,
        type: "POST",
        url: $('#AddNewToolUrl').val(),
        processData: false,
        contentType: false,
        data: formData,
        success: function () {
            $('#add-tool-modal').modal('hide');
            window.location.reload();
        },
        error: function (error) {
            console.error(error);
        }
    });
}
