/* Transfer balance js  */

let current_fs, next_fs, previous_fs; // Fieldsets
let current = 1;

$(document).ready(function () {
    $(".amount-validation").bind("input", function () {
        var c = this.selectionStart,
            r = /[^0-9.]/gi,  // Regular expression to match characters other than word characters, @, dot, and dash
            v = $(this).val();
        if (r.test(v)) {
            $(this).val(v.replace(r, ""));  // Replace invalid characters with an empty string
            c--;  // Adjust cursor position if necessary
        }

        // Check for multiple dots
        if ((v.match(/\./g) || []).length > 1) {
            $(this).val(v.substring(0, v.length - 1));
            c--;  // Adjust cursor position if necessary
        }

        // Check for more than two decimal places
        if (v.indexOf('.') !== -1 && v.split('.')[1].length > 2) {
            $(this).val(v.substring(0, v.length - 1));
            c--;  // Adjust cursor position if necessary
        }

        this.setSelectionRange(c, c);  // Set the cursor position
    });

    $(document).on('submit', '#transactionForm', function(e) {
        e.preventDefault();
        current_fs = $('.transfer-2fa-validate').closest('fieldset');
        var last_fs = $('.transfer-2fa-validate').closest('fieldset').next();
        fetchStep2Data(null, last_fs);
    });

    setProgressBar(current);
    $(".next").click(function () {
        current_fs = $(this).closest('fieldset')
        next_fs = $(this).closest('fieldset').next();

        let currentStep = $("fieldset").index(current_fs) + 1;
        fetchStepData(currentStep, current_fs, next_fs);
    });

    $(".previous").click(function () {
        current_fs = $(this).closest('fieldset');
        previous_fs = $(this).closest('fieldset').prev();

        // Remove class active
        $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

        showFieldset(previous_fs);
        setProgressBar(--current);
    });

    $(document).on('change', '#reason', function () {
        let reason =  $('#reason option:selected').val();
        if (reason == "Other") {
            $('#otherReason').show();
        } else {
            $('#otherReason').hide();
            $("input[name = 'other_reason']").val('');
        }
    })
});



function fetchStepData(step, current_fs, next_fs) {
    switch (step) {
        case 1:
            fetchStep1Data(current_fs, next_fs);
            break;
        case 2:
            fetchStep2Data(current_fs, next_fs);
            break;
        default:
            console.log('Step not defined');
    }
}

function showFieldset(next_fs) {
    $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");
    next_fs.show();
    current_fs.animate({
        opacity: 0
    }, {
        step: function (now) {
            let opacity = 1 - now;
            current_fs.css({
                'display': 'none',
                'position': 'relative'
            });
            next_fs.css({
                'opacity': opacity
            });
        },
        duration: 500
    });
}

function setProgressBar(curStep) {
    let steps = $("fieldset").length
    let percent = parseFloat(100 / steps) * curStep;
    percent = percent.toFixed();
    $(".progress-bar")
        .css("width", percent + "%")
}

const transferBalanceModal = new bootstrap.Modal(document.getElementById('transferBalanceModal'));
function amountTransfer(self) {
    $('#otherReason').hide();
    $("#progressbar li").removeClass('active');
    current = 1;
    current_fs = $('fieldset:not(.first_fieldset)').closest('fieldset');
    next_fs = $('.first_fieldset').closest('fieldset');
    showFieldset(next_fs);
    setProgressBar(current);
    transferBalanceModal.show();
    $('#transactionForm')[0].reset();
    $(".search_user").empty().trigger('change');
    const walletBalance = $('.btn-transfer').data('wallet-balance');
    $("input[name = 'wallet_balance']").val(walletBalance);
    $('.max_balance').html(`${walletBalance} EUR`);
}

$('#transferBalanceModal').on('hide.bs.modal',function(){
    window.location.href = baseURL + "member/dashboard";
})

$(".search_user").select2({
    delay: 250,
    placeholder: 'Search User',
    dropdownParent: $('#transferBalanceModal .modal-content'),
    ajax: {
        url: baseURL + "member/get-all-members",
        dataType: 'json',
        processResults: function (data) {
            return {
                results: data.items
            };
        }
    },
    minimumInputLength: 1,
});

function fetchStep1Data(current_fs, next_fs) {
    let amount = $("input[name = 'amount']").val();
    let username = $('#member_searchid').val();
    let reason = $('#reason').val();
    let reasonForOther = $("input[name = 'other_reason']").val();
    let is_error = false;
    $('.error').text('');

    if (username == null) {
        $('.member_searchid_error').text('please choose User for transfer amount.');
        is_error = true;
    }
    if (amount === '') {
        $('.amount_error').text('The Transfer Amount field is required.');
        is_error = true;
    }
    if (reason === '') {
        $('.reason_error').text('Please provide a reason for the transfer.');
        is_error = true;
    }
    if (reason === 'Other' && reasonForOther === '') {
        $('.other_reason_error').text('Please provide a reason for the transfer.');
        is_error = true;
    }
    if(is_error == true){
        return;
    }
     //for send otp
     checkAndSendOtpIfOnlyEmailOtpVerification('#transferAmount2FaFormDiv');
    showFieldset(next_fs);
    setProgressBar(++current);
}

function fetchStep2Data(current_fs, next_fs) {
    let saveBtn = $("#2fa3faValidateForm .submitBtn");
    let saveBtnText = saveBtn.html();
    let formId = $('#transactionForm')[0];
    let formData = new FormData(formId);
    let url = $('#transactionForm').prop('action')
    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        contentType: false,
        processData: false,
        beforeSend: function () {
            $("#2fa3faValidateForm .action-button-previous").prop('disabled', true);
            saveBtn.prop('disabled', true);
            saveBtn.html(`<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;${translate("loading")}...`);
        },
        success: function (response) {
                swalMsg(response.message,"success");
                showFieldset(next_fs);
                setProgressBar(++current);
                $('#transactionForm')[0].reset();
                $("#2fa3faValidateForm .action-button-previous").prop('disabled', false);
                saveBtn.prop('disabled', false);
                saveBtn.html(saveBtnText);
        },
        error: function (jqXHR) {
            $("#2fa3faValidateForm .action-button-previous").prop('disabled', false);
            saveBtn.prop('disabled', false);
            saveBtn.html(saveBtnText);
            if (globalErrorHandler(jqXHR.responseJSON)){
                return false
            }
        }
    });
}



