'use strict';
// gift code status filter
var statuses = {
    'Pending': 'Pending',
    'Redeemed': 'Redeemed',
    'Expired': 'Expired',
    'Rejected':'Rejected',
    'Canceled':'Canceled'
};
function ajaxRequestGiftCodes(params) {
    let url = baseURL + "member/my-gift-code-all";
    if (transactionIdFilter != ''){
        var filter = params.data.filter || '{}';
        filter = JSON.parse(filter);
        filter.transaction_id = transactionIdFilter;
        params.data.filter = JSON.stringify(filter);
    }
    $.get(url + '?' + $.param(params.data)).then(function (res) {
        params.success(res)
    })
}

function giftCodeStatusFormat(value, row) {
    if(value === "Pending"){
        value = `<span class="status-info badge-width">${translate('Pending')}</span>`;
    }else if(value === "Redeemed"){
        value = `<span class="status-success badge-width">${translate('Redeemed')}</span>`;
    }else if(value === "Expired"){
        value = `<span class="status-warning badge-width">${translate('Expired')}</span>`;
    }else if(value === "Rejected"){
        value = `<span class="status-danger badge-width">${translate('Rejected')}</span>`;
    }else if(value === "Canceled"){
        value = `<span class="status-orange badge-width">${translate('Canceled')}</span>`;
    }
    return value;
}

$(document).on('keyup','.bootstrap-table-filter-control-transaction_id',function () {
    transactionIdFilter = '';
})

function removeProduct(cartId, url) {
    Swal.fire({
        title: 'Are you sure?',
        text: "You will not be able to revert ",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!',
        showClass: {
            popup: 'animate__animated animate__fadeInUp'
        },
        hideClass: {
            popup: 'animate__animated animate__fadeOutDown'
        }
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: url,
                type: 'DELETE',
                data: {
                    cartId: cartId
                },
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function (response) {
                    if (response.success) {
                        swalMsg('Product removed successfully.','success');
                    } else {
                        swalMsg('Something went wrong try again.','error');
                    }

                    let $showTable = $('#bstable');
                    $showTable.bootstrapTable('showLoading');
                    $showTable.bootstrapTable('refresh');
                    $showTable.bootstrapTable('hideLoading');
                },
            });
        }
    })
}
$(document).on('click', '#purchaseNowBtn', function (e) {
    $.get(baseURL + "member/shop/check-cash-amount", function (response) {
        if (response.success) {
            window.location.href = baseURL + 'member/shop/place-order';
        } else {
            Swal.fire({
                icon: 'error',
                title: 'You cannot place order',
                text: 'You have insufficient amplivo cash amount.',
            })
        }
    });
});
$(document).ready(function () {
    $(document).on('click', 'button[name="clearSearch"]', function () {
        if (transactionIdFilter) {
            window.location.href = baseURL + 'member/gift-codes';
        }
    });
})


/*---- START for cancel gift code ----*/
function cancelGiftCode(btn){
    btn = $(btn);
    var id = btn.data('id');
    var giftcode = btn.data('giftcode');
    $("#cancelGiftCodeModal .gift-code").text(giftcode);
    $("#cancelGiftCode2faForm input[name='gift_code_id']").val(id);

    btn.attr("disabled", true).html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate('Loading...')}`);
    $("#cancelGiftCodeModal").modal('show');

    stopResendOtpTimer();
    checkAndSendOtpIfOnlyEmailOtpVerification('#cancelGiftCode2faForm');
}

$('#cancelGiftCodeModal').on('hidden.bs.modal', function () {
    closeCancelGiftCodeModal();
});

function closeCancelGiftCodeModal(){
    $("#cancelGiftCodeModal").modal('hide');
    $(".custom-error").text('');
    $("#2fa3faValidateForm [name='code[]'],#2fa3faValidateForm [name='otp[]']").val('');

    let $showTable = $('#bstable');
    $showTable.bootstrapTable('refresh');
}

$(document).ready(function () {
    $(document).on('submit', '#cancelGiftCode2faForm', function(e) {
        setTimeout(function () {
            loading2fa3faInputs('show',$('#cancelGiftCode2faForm'));
        });

        $(".custom-error").html('');

        e.preventDefault();
        let formData = new FormData($('#cancelGiftCode2faForm')[0]);
        const url = baseURL + 'member/cancel-gift-code';

        $.ajax({
            url: url,
            type: 'POST',
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            data: formData,
            contentType: false,
            processData: false,
            success: function (response) {
                if (response.success) {
                    closeCancelGiftCodeModal();
                    swalMsg(response.msg,'success');
                } else {
                    swalMsg(response.msg,'error');
                }
                $('#cancelGiftCode2faForm #2fa3faValidateForm .submitBtn').prop('disabled', false);

                loading2fa3faInputs('hide',$('#cancelGiftCode2faForm'));
            },
            error: function (jqXHR) {
                loading2fa3faInputs('hide',$('#cancelGiftCode2faForm'));

                $('#cancelGiftCode2faForm #2fa3faValidateForm .submitBtn').prop('disabled', false);
                if (globalErrorHandler(jqXHR.responseJSON))
                    return false
            }
        });
    });
});
/*---- END for cancel gift code ----*/
/*---- START for transfer gift code ----*/
function transferGiftCode(btn){
    btn = $(btn);
    var id = btn.data('id');
    var giftcode = btn.data('giftcode');
    var productName = btn.data('product-name');
    $("#transferGiftCodeModal .gift-code").text(giftcode);
    $("#transferGiftCodeModal .product-name").text(productName);
    $("#transferGiftCode2faForm input[name='gift_code_id']").val(id);

    btn.attr("disabled", true).html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate('Loading...')}`);
    $("#transferGiftCodeModal").modal('show');
    stopResendOtpTimer();
}

$('.transferred_user_id').on('select2:select', function (e) {
    $('#transferGiftCodeModal .user-details').hide();
    $('.2fa_send_gift_code').hide();

    const selectedUser = e.params.data;
    $.ajax({
        url: baseURL+`member/check-downline-user/${selectedUser.id}`,
        type: "GET",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        success: function(response) {
            if(response.success){
                $("#transferGiftCodeModal .username").text(response.data.user.details.username);
                $("#transferGiftCodeModal .email").text(response.data.user.details.email);
                $("#transferGiftCodeModal .user_message_text").text(response.msg);
                $('#transferGiftCodeModal .user-details').show();
                $('.2fa_send_gift_code').show();
                checkAndSendOtpIfOnlyEmailOtpVerification('#transferGiftCode2FaFormDiv');
            }
        }
    });
});

$(".transferred_user_id").select2({
    placeholder: 'Search User',
    dropdownParent: $('#transferGiftCodeModal'),
    ajax: {
        url: baseURL + "member/get-searched-members",
        dataType: 'json',
        processResults: function (data) {
            return {
                results: data.items
            };
        }
    },
    minimumInputLength: 1,
});

$('#transferGiftCodeModal').on('hidden.bs.modal', function () {
    closeTransferGiftCodeModal();
});

function closeTransferGiftCodeModal(){
    $("#transferGiftCodeModal").modal('hide');
    $(".custom-error").text('');
    $("#2fa3faValidateForm [name='code'],#2fa3faValidateForm [name='otp']").val('');
    $(".transferred_user_id").empty().trigger('change');
    $("#transferGiftCodeModal .username").text('');
    $("#transferGiftCodeModal .email").text('');
    $("#transferGiftCodeModal .user_message_text").text('');
    $('#transferGiftCodeModal .user-details').hide();
    $('.2fa_send_gift_code').hide();
    let $showTable = $('#bstable');
    $showTable.bootstrapTable('refresh');
}

$(document).ready(function () {
    $(document).on('submit', '#transferGiftCode2faForm', function(e) {
        setTimeout(function () {
            loading2fa3faInputs('show',$('#transferGiftCode2faForm'));
        });
        $(".custom-error").html('');

        e.preventDefault();
        let formData = new FormData($('#transferGiftCode2faForm')[0]);
        const url = baseURL + 'member/transfer-gift-code';

        $.ajax({
            url: url,
            type: 'POST',
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            data: formData,
            contentType: false,
            processData: false,
            success: function (response) {
                if (response.success) {
                    closeTransferGiftCodeModal();
                    swalMsg(response.msg,'success');
                } else {
                    swalMsg(response.msg,'error');
                }
                $('#transferGiftCode2faForm #2fa3faValidateForm .submitBtn').prop('disabled', false);

                loading2fa3faInputs('hide',$('#transferGiftCode2faForm'));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                loading2fa3faInputs('hide',$('#transferGiftCode2faForm'));

                $('#transferGiftCode2faForm #2fa3faValidateForm .submitBtn').prop('disabled', false);
                if (globalErrorHandler(jqXHR.responseJSON)) return false;
                if (jqXHR.responseJSON && jqXHR.responseJSON.errors) {
                    $("#transferGiftCode2faForm .error").text("");
                    for (const key in jqXHR.responseJSON.errors) {
                        if ($("#transferGiftCode2faForm ." + key + "_error")) {
                            $("#transferGiftCode2faForm ." + key + "_error").text(
                                jqXHR.responseJSON.errors[key]
                            );
                        }
                    }
                }
            },
        });
    });
});
/*---- END for transfer gift code ----*/
