"use strict";
$table = $("#bstable");
var withdrawal_status = {
    "Pending" : "Pending",
    "Approved" : "Approved",
    "Rejected" : "Rejected",
}

var blockchain = {
    "ERC20" : "ERC20",
    "BSC" : "BSC",
    "Tron" : "Tron",
}

let activeTab = '';
let currencyTab = '';
let currencyType = '';
let currencyAbbreviation = '';

$('#myTab .nav-link').on('click', function (e) {
    e.preventDefault();

    $('#myTab .nav-link').removeClass('active bg-primary text-white').attr('aria-selected', 'false');
    $('#myTab .notification-count').removeClass('bg-white text-primary');

    // Add active class to the clicked tab
    $(this).addClass('active bg-primary text-white').attr('aria-selected', 'true');
    $(this).find('.notification-count').addClass('bg-white text-primary');

    $('#bstable').bootstrapTable('resetSearch');
});

function ajaxRequestWithdrawal(params) {
    let url = $('#withdrawalAll').val();
    activeTab = $('#myTab .nav-link[aria-selected="true"]');
    currencyTab = activeTab.data('id');
    currencyType = activeTab.data('type');
    currencyAbbreviation = activeTab.data('abbreviation');

    if(currencyTab != ""){
        params.data.currency_id = currencyTab;
    }
    $.get(url + '?' + $.param(params.data)).then(function(res) {
        params.success(res);

        const fieldsShowCrypto = ['transaction_hash', 'blockchain_address','blockchain'];
        const fieldsShowFiat = [
            'account_holder',
            'account_detail',
            'bank_name',
            'iban_number',
            'bank_branch_name',
            'bic_swift_number',
            'bank_address'
        ];
        const fieldExchangeAmount = 'exchange_amount';

        const lsname = UID + '-hideColumn-' + $table.attr('table-for');
        let hideColumn = [];

        const fieldsToHide = currencyType === 'Fiat' ? fieldsShowCrypto : fieldsShowFiat;
        const fieldsToShow = currencyType === 'Fiat' ? fieldsShowFiat : fieldsShowCrypto;

        // Hide fields
        fieldsToHide.forEach(field => {
            const $checkbox = $(`input[type="checkbox"][data-field="${field}"]`);
            if ($checkbox.prop('checked')) {
                $checkbox.click(); // Trigger uncheck
            }

            if (!hideColumn.includes(field)) {
                hideColumn.push(field);
            }
        });

        // Show fields
        fieldsToShow.forEach(field => {
            const $checkbox = $(`input[type="checkbox"][data-field="${field}"]`);
            if (!$checkbox.prop('checked')) {
                $checkbox.click(); // Trigger check
            }

            // Remove from hideColumn if already there
            const index = hideColumn.indexOf(field);
            if (index > -1) {
                hideColumn.splice(index, 1);
            }
        });

        const $exchangeCheckbox = $(`input[type="checkbox"][data-field="${fieldExchangeAmount}"]`);
        if (currencyAbbreviation === 'EUR') {
            if ($exchangeCheckbox.prop('checked')) {
                $exchangeCheckbox.click(); // Hide
            }
            if (!hideColumn.includes(fieldExchangeAmount)) {
                hideColumn.push(fieldExchangeAmount);
            }
        } else {
            if (!$exchangeCheckbox.prop('checked')) {
                $exchangeCheckbox.click(); // Show
            }
            const index = hideColumn.indexOf(fieldExchangeAmount);
            if (index > -1) {
                hideColumn.splice(index, 1);
            }
        }

        // Save updated column visibility to localStorage
        localStorage.setItem(lsname, JSON.stringify(hideColumn));
    })
}

function withdrawalStatusFormat(value, row){
    if (value == "Pending") {
        value = '<span class="status-info badge-width">Pending</span>';
    } else if(value == "Approved"){
        value = '<span class="status-success badge-width">Approved</span>';
    } else if(value == "Rejected"){
        value = '<span class="status-danger badge-width">Rejected</span>';
    }
    return value;
}

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

$(document).ready(function () {
    $('body').on('click', ".btnNewRecord", function () {
        $('.error').text('');
        window.location.href = '/member/withdrawal/create';
    });

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


    $(document).on('submit', '#withdrawalAmount', function(e) {
        e.preventDefault();
        current_fs = $('#withdrawal2FaFormDiv').closest('fieldset');
        var last_fs = $('#withdrawal2FaFormDiv').closest('fieldset').next();
        fetchStep4Data(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);
    });

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

    $('.fund_send_account_radio').hide();

    $('.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_2_next_btn').hide();
        else $('.step_2_next_btn').show();
    });

    $(document).on('click', '.withdrawal_btn', function(e) {
        e.preventDefault();
        $('.withdrawal-form-section').show();
        $('.withdrawal-form').show();
        $('.withdrawal-type-section').hide();
    });
});


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;
        case 3:
            fetchStep3Data(current_fs, next_fs);
        break;
        case 4:
            fetchStep4Data(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 + "%")
}

//when first previous click need to show dropdown of currency
function showWithdrawalIndex(){
    $(".withdrawal-type-section").show();
    $(".withdrawal-form-section").hide();
}

/* get currency GuideLine data for first screen */
function currencyGuideLine() {
    currencyId = $('#currency_id').val();
        var currencyAbbreviation = $('#currency_id option:selected').attr('data-value');
        $('.currency_desc').text(currencyAbbreviation);
        $.ajax({
            url: baseURL + 'member/withdrawal/blockchain/' + currencyId,
            type: "GET",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function (data) {
                var items = '<option value="">Select Your Blockchain</option>';
                if(Object.keys(data).length) {
                    data.forEach(function(blockchain) {
                        items += `<option value="${blockchain.name}">${blockchain.name}</option>`;
                    });
                }
                $('#blockchain').html(items);

            },
            error: function(response) {
                swalMsg(response.responseJSON.msg, 'error');
            }
        });
        $.ajax({
            url: baseURL + 'member/withdrawal/currency-guideline/' + currencyId,
            type: "GET",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function (data) {
                var items = '';
                if(Object.keys(data).length) {
                    data.description.forEach(function(desc) {
                        items += '<li>' + desc + '</li>';
                    });
                } else {
                    items += '<li>No withdrawal Guideline set for this currency</li>';
                }
                $('.withdrawal_btn').show();
                $('.withdrawal-guidance-notes-lists').html(items);
            },
            error: function(response) {
                swalMsg(response.responseJSON.msg, 'error');
            }
        });
}

/* get currency data for step 1 screen */
let currency = null;
async function getCurrencyForStep1()
{
    $('input[name="amount"]').val('');
    $('input[name="exchange_amount"]').val('');
    $('input[name="exchange_rate"]').val('');

    $.ajax({
        url: baseURL + 'member/withdrawal/currency/' + currencyId,
        type: 'GET',
        success: async function (data) {
            if (Object.keys(data).length) {
                currency = data;
                $('.currency_description').html(`Amount (${currency.abbreviation}) <span class="text-danger">*</span>`);
                if(currency.type === 'Crypto'){
                    $(".fiat_section").hide();
                    $(".crypto_section").show();
                } else{
                    $(".fiat_section").show();
                    $(".crypto_section").hide();
                }
                if(currency.abbreviation == 'EUR'){
                    $('.exchangeAmount').hide();
                    $('.exchangeAmountDesc').hide();
                } else{
                    $('.exchangeAmount').show();
                    $('.exchangeAmountDesc').show();
                    let from = 'EUR';
                    let to = currency.abbreviation;
                    let EurAmount = await convertCurrency(from,to);
                    EurAmount = Math.floor(EurAmount * 100) / 100;

                    $('input[name="exchange_rate"]').val(parseFloat(EurAmount).toFixed(2));
                }
                $('input[name="currency_id"]').val(data.id);
                if(withdrawal_fee == 0){
                    $('.withdrawal-fee').hide();
                }
            } else {
                swalMsg('Currency data not found.', 'error');
            }
        },
        error: function () {
            swalMsg(response.responseJSON.msg, 'error');
        }
    });
}

async function convertCurrency(from, to) {
    try {
        const url = `https://api.coinbase.com/v2/exchange-rates?currency=${from}`;
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`Failed to fetch exchange rates: ${response.statusText}`);
        }
        const currencyRates = await response.json();
        const toValue = currencyRates.data.rates[to] ?? 0;
        return toValue;
    } catch (error) {
        console.error('Error fetching exchange rates:', error);
        return 0;
    }
}

$('input[name="amount"]').on('input', async function(){
    const amountInput = $('input[name="amount"]');
    $('.error').text('');
    let amount = amountInput.val();
    if (!amount) {
        $('input[name="exchange_amount"]').val('');
        $('input[name="received_amount"]').val('');
        return;
    }
    if(parseFloat(amount) > parseFloat(max_withdrawal) && max_withdrawal != -1) {
        $('.amount_error').text(`The Withdrawal Amount must be between ${min_withdrawal} Euros and ${max_withdrawal} Euros.`);
        amount = max_withdrawal;
        amountInput.val(max_withdrawal);
    }
    const withdrawal_fee = $('input[name="withdrawal_fee"]').val();
    const received_amount = parseFloat(amount) - parseFloat(withdrawal_fee);
    $('input[name="received_amount"]').val(received_amount);

    const exchange_rate = $('input[name="exchange_rate"]').val();
    let convertedEurAmount = received_amount * exchange_rate;
    $('input[name="exchange_amount"]').val(parseFloat(convertedEurAmount).toFixed(2));
    $('.withdrawal_amount').text(amount);
});

let is_valid = false;
const web3 = new Web3();
// Validate Ethereum/BSC Address
async function isValidEthereumAddress(address) {
    let response = await web3.utils.isAddress(address);
    if (response == true) {
        is_valid = true;
    } else{
        is_valid = false;
    }
    return is_valid;
}

// Validate Tron address
async function isValidTronAddress(address) {
    let url = '';
    let response = '';
    let headers = '';
    let data = '';

    try {
        if(ApiMode ==  "live"){
        url = `https://apilist.tronscanapi.com/api/account?address=${address}`;

            response = await fetch(url);
            let responseData = await response.json();
            if (responseData.hasOwnProperty("address") && responseData.address === address) {
                is_valid = true;
                return is_valid;
            } else {
                is_valid = false;
                return is_valid;
            }
        } else{
            url = "https://api.shasta.trongrid.io/wallet/validateaddress";
            headers = {
                "Accept": "application/json",
                "Content-Type": "application/json"
            };
            data = {
                address: address,
                visible: true
            };
            response = await fetch(url, {
                method: "POST",
                headers: headers,
                body: JSON.stringify(data)
            });
            let responseData = await response.json();
            if (responseData.result == true) {
                is_valid = true;
                return is_valid;
            } else {
                is_valid = false;
                return is_valid;
            }
        }

    } catch (error) {
        console.error("Error validating address:", error);
        is_valid = false;
        return is_valid;
    }
}

// Combined Logic
async function isValidBlockchainAddress(address, blockchain) {
    $('.step_2_next_btn').prop('disabled', true);
    $('.step_2_prev_btn').prop('disabled', true);
    if (blockchain === 'Tron') {
        return await isValidTronAddress(address);
    } else if (blockchain === 'ERC20' || blockchain === 'BSC') {
        return await isValidEthereumAddress(address);
    }
    return is_valid;
}

function fetchStep1Data(current_fs, next_fs) {
    getCurrencyForStep1();
    showFieldset(next_fs);
    setProgressBar(++current);
}

async function fetchStep2Data(current_fs, next_fs) {
    let main_error = false;
    $('.error').text('');
    const amount = $('input[name="amount"]').val();
    const exchange_amount = $('input[name="exchange_amount"]').val();
    const accountType = $('input[name="account_type"]:checked').val();
    const account_holder = $('input[name="account_holder"]').val();
    const bank_name = $('input[name="bank_name"]').val();
    const iban_number = $('input[name="iban_number"]').val();
    const bank_branch_name = $('input[name="bank_branch_name"]').val();
    const bic_swift_number = $('input[name="bic_swift_number"]').val();
    const bank_address = $('input[name="bank_address"]').val();
    const blockchain = $('#blockchain option:selected').val();
    const blockchain_address = $('input[name="blockchain_address"]').val();

    if (amount == '') {
        $('.amount_error').text(`The Withdrawal Amount field is required.`);
        main_error = true;
    }
    if (parseFloat(amount) > parseFloat(OCAbalance)) {
        $('.amount_error').text(`You have insufficient balance for withdrawal.`);
        main_error = true;
    }
    if(parseFloat(amount) < parseFloat(min_withdrawal) || parseFloat(amount) > parseFloat(max_withdrawal) ) {
        $('.amount_error').text(`The Withdrawal Amount must be between ${formatDisplayNumber(min_withdrawal)} Euros and ${formatDisplayNumber(max_withdrawal)} Euros.`);
        main_error = true;
    }

    if(currency.type == 'Crypto'){
        if (!blockchain) {
            $('.blockchain_error').text(`The Blockchain field is required.`);
            main_error = true;
        }
        if (blockchain_address == '') {
            $('.blockchain_address_error').text(`The Blockchain Address field is required.`);
            main_error = true;
        }
        let is_error = false;
        await isValidBlockchainAddress(blockchain_address,blockchain);
        $('.step_2_next_btn').prop('disabled', false);
        $('.step_2_prev_btn').prop('disabled', false);

        if(is_valid == false){
            $('.blockchain_address_error').text(`The Blockchain Address is not valid.`);
            is_error = true;
            main_error = true;
        }
        if(is_error == true || main_error ==  true){
            return;
        }
        var formData = new FormData();
        formData.append('blockchain', blockchain);
        formData.append('blockchain_address', blockchain_address);
        await $.ajax({
            url: baseURL + 'member/withdrawal/duplicate-withdrawal-data',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function (response) {
                if (response.status == false) {
                    $('.step_2_next_btn').prop('disabled', false);
                    $('.step_2_prev_btn').prop('disabled', false);
                    is_error = true;
                    swalMsg(response.msg,'error')
                } else{
                    is_error = false;
                }
            },
            error: function (response) {
                $('.step_2_next_btn').prop('disabled', false);
                $('.step_2_prev_btn').prop('disabled', false);
                swalMsg(response.responseJSON.msg, 'error')
                is_error = true;
            }
        });
        if(is_error == false){
            showFieldset(next_fs);
            setProgressBar(++current);
        }

    }

    if(currency.type != 'Crypto'){
        if(!accountType){
            $('.account_type_error').text(`Please choose, are you withdraw the funds from your own account?`);
            main_error = true;
        }
        if(accountType=='joint_account'){
            if(!$('input[name="joint_account_first_name"]').val()){
                $('.joint_account_first_name_error').text(`The Second Account Holder First Name field is required.`);
                main_error = true;
            }
            if(!$('input[name="joint_account_last_name"]').val()){
                $('.joint_account_last_name_error').text(`The Second Account Holder Last Name field is required.`);
                main_error = true;
            }
        }
        if(accountType=='business_account' && !$('input[name="business_name"]').val()){
            $('.business_name_error').text(`The Business Name field is required.`);
            main_error = true;
        }
        if (account_holder === '') {
            $('.account_holder_error').text(`The Account Holder field is required.`);
            main_error = true;
        }
        if (bank_name === '') {
            $('.bank_name_error').text(`The Bank Name field is required.`);
            main_error = true;
        }
        if (iban_number === '') {
            $('.iban_number_error').text(`The Bank IBAN Number field is required.`);
            main_error = true;
        }
        if (bank_branch_name === '') {
            $('.bank_branch_name_error').text(`The Bank Branch Name field is required.`);
            main_error = true;
        }
        if (bic_swift_number === '') {
            $('.bic_swift_number_error').text(`The Bank BIC/SWIFT field is required.`);
            main_error = true;
        }
        if (bank_address === '') {
            $('.bank_address_error').text(`The Bank Address field is required.`);
            main_error = true;
        }

        if(main_error == true){
            return;
        }
        let bank_detail='<p>to</p>';
        bank_detail += 'Account Holder: ' + account_holder +'<br>';
        bank_detail += 'IBAN Number: '+ iban_number +'<br>';
        bank_detail += 'BIC/SWIFT: '+ bic_swift_number +'<br>';
        bank_detail += 'Bank Name: '+ bank_name +'<br>';
        bank_detail += 'Branch Name: '+ bank_branch_name +'<br>';
        bank_detail += 'Bank Address: ' + bank_address;
        $('.bankDetail').html(`${bank_detail}`);
        showFieldset(next_fs);
        setProgressBar(++current);
    }

    $('.withdrawal_amount').html(`${formatDisplayNumber(amount)}`);
    if(currency.abbreviation != 'EUR'){
    $('.exchangeAmountDesc').html(`Estimated amount of ${formatDisplayNumber(exchange_amount)} ${currency.abbreviation}.`);
    }
}

function fetchStep3Data(current_fs, next_fs) {
    var checkboxValue = $('#confirm').prop('checked');
    if(!checkboxValue) {
        $('#2fa3faValidateForm .submitBtn').prop('disabled', false);
        $('#2fa3faValidateForm .submitBtn').html('Authenticate');
        $('.confirm_error').text(`Please agree to terms.`);
        return;
    }
    //for send otp
    checkAndSendOtpIfOnlyEmailOtpVerification('#withdrawalAmount');
    showFieldset(next_fs);
    setProgressBar(++current);
}

function fetchStep4Data(current_fs, next_fs) {
    const fid = 'withdrawalAmount';
    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')
                showFieldset(next_fs);
                setProgressBar(++current);
                setTimeout(function () {
                    window.location.href = '/member/withdrawal/withdrawals-list';
                }, 5000);
            } else {
                swalMsg(data.msg, 'error');
            }
        },
        error: function (response) {
            $('#2fa3faValidateForm .submitBtn').prop('disabled', false);
            $('#2fa3faValidateForm .submitBtn').html('Authenticate');
            swalMsg(response.responseJSON.msg,'error')
        }
    });
}
