// "use strict";
$table = $("#bstable");

$(document).ready(function () {

    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);
    });

    /* validation for step 1 */
    $('.fund_send_account_radio').hide();
    // Manage radio button changes
    $('.account-type-radio').change(function() {
        $('.fund_send_account_radio input[type="text"]:not([readonly])').val('');
        $('.fund_send_account_radio').hide();
        if ($('#personal').is(':checked')) {
            $('.yes_account_section').show();
        } else if ($('#joint_account').is(':checked')) {
            $('.joint_account_section').show();
        } else if ($('#business_account').is(':checked')) {
            $('.business_account_section').show();
        } else if ($('#someone_account').is(':checked')) {
            $('.someone_account_section').show();
        }
    });

    $('input[type=radio][name=account_type]').change(function() {
        if (this.value == 'someone_account') $('.step_1_next_btn').hide();
        else $('.step_1_next_btn').show();
    });

    $(".submit").click(function () {
        return false;
    })

    $(".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
    });
});

window.FiatScript = (function () {
    function init() {
        $(document).on('submit', '#depositAmount', function(e) {
            e.preventDefault();
            current_fs = $('.deposit-2fa-validate').closest('fieldset');
            var last_fs = $('.deposit-2fa-validate').closest('fieldset').next();
            fetchStep6Data(null, last_fs);
        });
    }

    function destroy() {
         $(document).off('submit', '#depositAmount');
    }

    return { init, destroy };
})();

function fetchStepData(step, current_fs, next_fs) {
    if(isFileRequire && isShowNote) {//file and show note both show
        switch (step) {
            case 1:
                fetchStep1Data(current_fs, next_fs);
                break;
            case 2:
                fetchStep2Data(current_fs, next_fs);
                break;
            case 3:
                fetchStep3Data(current_fs, next_fs);
                break;
            case 4:
                fetchStep4Data(current_fs, next_fs);
                break;
            case 5:
                fetchStep5Data(current_fs, next_fs);
                break;
            case 6:
                fetchStep6Data(current_fs, next_fs);
                break;
            default:
                console.log('Step not defined');
        }
    } else if(isFileRequire && !isShowNote) {//file show and note not show
        switch (step) {
            case 1:
                fetchStep1Data(current_fs, next_fs);
                break;
            case 2:
                fetchStep2Data(current_fs, next_fs);
                break;
            case 3:
                fetchStep3Data(current_fs, next_fs);
                break;
            case 4:
                fetchStep5Data(current_fs, next_fs);
                break;
            case 5:
                fetchStep6Data(current_fs, next_fs);
                break;
            default:
                console.log('Step not defined');
        }
    } else if(!isFileRequire && isShowNote) {//file not show and note show
        switch (step) {
            case 1:
                fetchStep1Data(current_fs, next_fs);
                break;
            case 2:
                fetchStep2Data(current_fs, next_fs);
                break;
            case 3:
                fetchStep3Data(current_fs, next_fs);
                break;
            case 4:
                fetchStep4Data(current_fs, next_fs);
                break;
            case 5:
                fetchStep6Data(current_fs, next_fs);
                break;
            default:
                console.log('Step not defined');
        }
    } else {//both not show
        switch (step) {
            case 1:
                fetchStep1Data(current_fs, next_fs);
                break;
            case 2:
                fetchStep2Data(current_fs, next_fs);
                break;
            case 3:
                fetchStep3Data(current_fs, next_fs);
                break;
            case 4:
                fetchStep6Data(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 + "%")
}

async function getCurrencyForStep1()
{
    $.ajax({
        url: baseURL + 'member/deposit/currency/' + currencyId,
        type: 'GET',
        success: async function (data) {
            if (Object.keys(data).length) {
                $('.currency_description').html(`${data.abbreviation} Amount  <span class="text-danger">*</span>`);
                $('input[name="currency_id"]').val(data.id);
                currency = data;
                if(currency.abbreviation != 'EUR'){
                    let from = currency.abbreviation;
                    let to = 'EUR';
                    let EurAmount = await convertCurrency(from,to);
                    $('input[name="exchange_rate"]').val(EurAmount);
                }
                $('.deposit-form').show();
                $('.deposit-type-section').hide();
                const minValue = parseFloat(deposit_option.min_value);
                const maxValue = parseFloat(deposit_option.max_value);

                // Format values
                const formattedMin = (minValue === -1 ? 0 : formatDisplayNumber(minValue)) + ` ${currency.abbreviation}`;
                const formattedMax = (maxValue === -1 ? 'Unlimited' : formatDisplayNumber(maxValue)) + ` ${currency.abbreviation}`;

                let amountLimitHtml = '';

                if (maxValue === -1) {
                    amountLimitHtml = `Minimum deposit amount is <span class="fw-bold minimum_deposit_limit">${formattedMin}</span>. Lesser amounts cannot be processed.`;
                } else {
                    amountLimitHtml = `Deposit amount must be between <span class="fw-bold minimum_deposit_limit">${formattedMin}</span> and <span class="fw-bold maximum_deposit_limit">${formattedMax}</span>.`;
                }
                $('.amount-limit').html(amountLimitHtml);

            } else {
                swalMsg('Currency data not found.', 'error');
            }
        },
        error: function () {
            swalMsg(response.responseJSON.msg, 'error');
        }
    });
}

function fetchStep1Data(current_fs, next_fs) {
    $(".error").text('');
    let is_error = false;
    var checkboxValue = $('#confirm').prop('checked');
    if (!checkboxValue) {
        $('.fiat_confirm_error').text('Please read content and agree with guideline.');
        is_error = true;
    }
    if(is_error == true){
        return;
    }
    getCurrencyForStep1();
    showFieldset(next_fs);
    setProgressBar(++current);
}

$('input[name="amount"]').on('input', async function(){
    const amountInput = $('input[name="amount"]');
    let amount = amountInput.val();
    const minValue = parseFloat(deposit_option.min_value);
    const maxValue = parseFloat(deposit_option.max_value);

   if (maxValue !== -1 && parseFloat(amount) > parseFloat(maxValue)) {
        $('.fiat_amount_error').text(`Please enter a deposit amount between ${formatDisplayNumber(minValue)} ${currency.abbreviation} and ${formatDisplayNumber(maxValue)} ${currency.abbreviation}.`);
        amountInput.val(maxValue);
        amount = maxValue;
    } else if (minValue !== -1 && parseFloat(amount) < parseFloat(minValue)) {
        if (maxValue === -1) {
            $('.fiat_amount_error').text(`Minimum deposit amount is ${formatDisplayNumber(minValue)} ${currency.abbreviation} required.`);
        } else {
            $('.fiat_amount_error').text(`Please enter a deposit amount between ${formatDisplayNumber(minValue)} ${currency.abbreviation} and ${formatDisplayNumber(maxValue)} ${currency.abbreviation}.`);
        }
    } else {
        $('.fiat_amount_error').text('');
    }
    const exchange_rate = $('input[name="exchange_rate"]').val();
    let convertedEurAmount = amount * exchange_rate;
    $('input[name="exchange_amount"]').val(parseFloat(convertedEurAmount).toFixed(2));
    $('.bank_amount').html(`${formatDisplayNumber(amount)} ${currency.abbreviation}`);
});

function fetchStep2Data(current_fs, next_fs) {
    $(".error").text('');
    let is_error = false;
    const amount = $('input[name="amount"]').val();
    const accountType = $('input[name="account_type"]:checked').val();
    const username = $('input[name="username"]').val();
    const decryptUserId = $('input[name="decryptUserId"]').val();
    if (amount === '') {
        $('.fiat_amount_error').text(`The Deposit Amount field is required.`);
        is_error = true;
    }
    const minValue = parseFloat(deposit_option.min_value);
    const maxValue = parseFloat(deposit_option.max_value);

   if (minValue !== -1 && parseFloat(amount) < minValue) {
        if (maxValue === -1) {
            $('.fiat_amount_error').text(`Minimum deposit amount is ${minValue} ${currency.abbreviation} required.`);
        } else {
            $('.fiat_amount_error').text(`Please enter a deposit amount between ${minValue} ${currency.abbreviation} and ${maxValue} ${currency.abbreviation}.`);
        }
        is_error = true;
    } else if (maxValue !== -1 && parseFloat(amount) > maxValue) {
        $('.fiat_amount_error').text(`Please enter a deposit amount between ${minValue !== -1 ? minValue : 0} ${currency.abbreviation} and ${maxValue} ${currency.abbreviation}.`);
        is_error = true;
    }
    if(!accountType){
        $('.fiat_account_type_error').text(`Please choose, are you sending the funds from your own account?`);
        is_error = true;
    }
    if(accountType=='joint_account'){
        if(!$('input[name="joint_account_first_name"]').val()){
            $('.joint_account_first_name_error').text(`The First Name field is required.`);
            is_error = true;
        }
        if(!$('input[name="joint_account_last_name"]').val()){
            $('.joint_account_last_name_error').text(`The Last Name field is required.`);
            is_error = true;
        }
    }
    if(accountType=='business_account' && !$('input[name="business_name"]').val()){
        $('.business_name_error').text(`The Business Name field is required.`);
        is_error = true;
    }

    $('.send_cad_amount,.deposit_amount').html(`${formatDisplayNumber(amount)} ${currency.abbreviation}`);

    const { titles, entries } = deposit_option
    $('.deposit-details').empty();
    let row = '';
    if(titles.length){
        row += '<h5>Transfer Information:</h5><ul style="list-style: disc !important;">';
        for (var j = 0; j < titles.length; j++) {
            row += '<li class="fw-bold">' + titles[j] + ': <span class="fw-normal">' + entries[j] + '</span></li>';
        }
        row += '</ul>';
    }
     if(deposit_option.reference_with_username){
        let refNumber = username;
        refNumber += "-CSR-";
        refNumber += decryptUserId;

        row += `<div class="">
                    <h5>Important:</h5>
                    <p>When making the transfer, please ensure that you include the following reference number to correctly <br> allocate your payment: <b> ${refNumber}</b>. </p>
                    <p>Thank you for your prompt attention to this matter. </p>
            </div>`;
    }
    if(deposit_option.notes){
        row += `<div class="">
                    <p>${deposit_option.notes} </p>
                </div>`;
    }

    if(row != '') {
        $('.deposit-details').append(row);
    } else {
        $('.deposit-details-access').hide();
    }
    if(is_error == true){
        return;
    }
    var formData = new FormData();
    formData.append('deposit_option_id', depositOptionId);
    formData.append('amount', amount);

    $.ajax({
        url: baseURL + 'member/deposit/fiat-deposit',
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function (response) {
            let depositData = '';

            if(Object.keys(response).length) {
                depositData += '<br><table class="table table-bordered mt-2 p-0">';
                depositData += '<thead><tr><th class="w-50">Date</th><th class="w-50">Amount</th></tr></thead><tbody>';
                response.forEach(function(deposit) {
                    const dateStr = deposit.created_at;
                    const [day, month, year] = dateStr.split(" ")[0].split("-");
                    depositData += `<tr><td>${ moment(`${year}-${month}-${day}`).format("DD-MM-YYYY") }</td><td>${ deposit.amount}</td></tr>`;
                });
                depositData += '</tbody></table>';
                showConfirmationModal(
                    'Duplicate deposit request found.',
                    `Have you made multiple deposits for the same amount? ${depositData}` ,
                    renderIconTag('confirmyes')+'Yes' ,
                    function() {
                        setTimeout(() => {
                            showConfirmationModal('A second deposit request will be created.', 'Submitting multiple deposit requests for a single transaction will cause processing delays.<br>If you have already submitted this deposit request please press Cancel.','Continue' , function() {
                                if (deposit_option.content) {
                                    $('.note-detail').html(deposit_option.content);
                                } else {
                                    $('.note-detail-access').hide();
                                }
                                showFieldset(next_fs);
                                setProgressBar(++current);
                            });
                        }, 400);
                    },
                    renderIconTag('cancel')+'No',
                    function() {
                        swalMsg('This deposit request has already been submitted. You should not submit again.Submitting multiple deposit requests will cause processing delays.','error');
                });
            } else{
                if (deposit_option.content) {
                    $('.note-detail').html(deposit_option.content);
                } else {
                    $('.note-detail-access').hide();
                }
                showFieldset(next_fs);
                setProgressBar(++current);
            }
        },
        error: function (response) {
            swalMsg(response.responseJSON.msg, 'error')
        }
    });
}

function fetchStep3Data(current_fs, next_fs) {
    if(!isFileRequire && !isShowNote){
        //for send otp
        checkAndSendOtpIfOnlyEmailOtpVerification('#depositAmount');
    }
    showFieldset(next_fs);
    setProgressBar(++current);
}

function fetchStep4Data(current_fs, next_fs) {
    if(!isFileRequire){
        //for send otp
        checkAndSendOtpIfOnlyEmailOtpVerification('#depositAmount');
    }
    showFieldset(next_fs);
    setProgressBar(++current);
}

function fetchStep5Data(current_fs, next_fs) {
    $(".error").text('');
    let is_error = false;
    const fileInput = $('input[name="file"]');
    const file = fileInput[0].files[0];
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];
    const maxSize = 10 * 1024 * 1024;
    if(deposit_option.require_file_upload == 'yes'){
        if (!file) {
            $('.file_error').text(`Proof of payment is required.`);
            is_error = true;
        }
        if (file && !allowedTypes.includes(file.type)) {
            $('.file_error').text(`Invalid file type. Only JPG, JPEG, PNG, and PDF files are allowed.`);
            is_error = true;
        }
        if (file && file.size > maxSize) {
            $('.file_error').text(`File size should not exceed 10MB.`);
            is_error = true;
        }
    }
    if(is_error == true){
        return;
    }
    //for send otp
    checkAndSendOtpIfOnlyEmailOtpVerification('#depositAmount');
    showFieldset(next_fs);
    setProgressBar(++current);
}

function fetchStep6Data(current_fs, next_fs) {
    const fid = 'depositAmount';
    let form = $('#' + fid);
    let formData = $('#' + fid)[0];
    let fd = new FormData(formData);

    $.ajax({
        url: form.attr('action'),
        type: "POST",
        data: fd,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        },
        processData: false,
        contentType: false,
        success: function (data, textStatus, jqXHR) {
            if (data.success == true) {
                swalMsg(data.msg, 'success')
                $table.bootstrapTable('refresh');
                $table.bootstrapTable('hideLoading');
                showFieldset(next_fs);
                setProgressBar(++current);
                setTimeout(function () {
                    window.location.href = '/member/deposit/deposits-list';
                }, 5000);
            } else {
                swalMsg(data.msg, 'error')
            }
        },
        error: function (response) {
            $('#2fa3faValidateForm .submitBtn').prop('disabled', false);
            $('#2fa3faValidateForm .submitBtn').html('Authenticate');
            swalMsg(response.responseJSON.msg,'error')
        }
    });
}
