'use strict';
function goToCartPage(btn){
    $(btn).attr('disabled', true).html(`<i class='fa fa-spinner fa-spin'></i>&nbsp;&nbsp;${translate('loading')}...`);
    window.location.href=baseURL+'member/shop/confirm-your-order';
}

$(document).ready(function () {
    $(document).on('submit', '#productForm', function(e) {
        e.preventDefault();
        submitForm('#productForm');
    })
    $(document).on('submit', '#LicenceForm', function(e) {
        e.preventDefault();
        submitForm('#LicenceForm');
    })

    function submitForm(formId) {
        let formData = new FormData($(formId)[0]);
        let url = $('#productForm').prop('action')
        let submitBtn = $(formId+' [type="submit"]');
        let submitBtnText = submitBtn.html();
        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            contentType: false,
            processData: false,
            beforeSend: function () {
                submitBtn.prop('disabled', true);
                submitBtn.html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
            },
            success: function (response) {
                submitBtn.prop('disabled', false);
                submitBtn.html(submitBtnText);
                if (response.success){
                    swalMsg(response.message,'success');
                } else {
                    swalMsg(response.message,'error');
                }
                updateHeaderCartInfo();
            },
            error: function (errorResponse) {
                submitBtn.prop('disabled', false);
                submitBtn.html(submitBtnText);
                if (globalErrorHandler(errorResponse.responseJSON))
                    return false
            }
        });
    }


    setPriceAndKg();
    $(document).on('change','#product_id',function () {
        setPriceAndKg();
    });

    $('#product_id').select2({
        minimumResultsForSearch: Infinity
    });
});

function setPriceAndKg() {
    setTimeout(function () {
        var selectedOption = $('#product_id option:selected');
        var price = selectedOption.attr('data-price');
        var kg = selectedOption.attr('data-kg');
        $("#productPrice").text(formatDisplayNumber(price));
        $("#productKg").text(formatDisplayNumber(kg));
    },200);
}
