"use strict";

var wallet_type = {
    1   : "Amplivo Online Cash",
    2   : "Mandatory (Legacy)",
    3   : "Bitcoin",
    4   : "Ethereum wallet",
    5   : "BCH wallet",
    6   : "XRP wallet",
    7   : "ORT wallet",
    8   : "FLP wallet",
    9   : "LTCT wallet",
    10  : "CCW Online Cash Wallet",
    11  : "CCW FLP Wallet",
    12  : "Amplivo ISF Wallet",
    13  : "ISF + Mandatory Wallet",
    14  : "CCW ISF Wallet",
    15  : "Ecovo Online Cash Wallet",
    16  : "Ecovo FLP Wallet",
    17  : "Ecovo ISF Wallet",
    18  : "Amplivo Mandatory Wallet",
    19  : "Amplivo CSR Wallet",
    20  : "Ecovo CSR Wallet",
}

var statusType = {
    "done"   : "Done",
    'pending'   : "Pending",
}
function isStatusFormatter(value, row) {

    if(value === 'done'){
        value = '<span class="status-success badge-width">Done</span>';
    }else if(value === 'pending'){
        value = '<span class="status-danger badge-width">Pending</span>';
    }
    return value;
}

var transaction_type = {
    'credit': 'Credit',
    'debit': 'Debit',
}
let internalCommentStatus = ''

function transactionComment(self) {
    let transactionCommentModal = new bootstrap.Modal(document.getElementById('transactionSUCommentModal'));
    let transactionId = $(self).data('id');
    $.get(baseURL + "admin/transactions/show/" + transactionId, function (response) {
        $('#transaction_id').val(transactionId)
        $('#internal_su_comment').val(response.data.internal_comment)
        transactionCommentModal.show();
    });
}
$(document).on('submit', '#suCommentForm', function(e) {
    e.preventDefault();
    let formId = $('#suCommentForm')[0];
    let formData = new FormData(formId);
    let url = $('#suCommentForm').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 () {
            $('.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(`${translate('Save')}`);
            $('.btn-close').click();
            swalMsg(response.message,"success");
            $('#bstable').bootstrapTable('refresh');
        },
        error: function (errorResponse) {
            $('.submitBtn').prop('disabled', false);
            $('.submitBtn').html(`${translate('Save')}`);
            if (globalErrorHandler(jqXHR.responseJSON))
                return false
            if (errorResponse.responseJSON && errorResponse.responseJSON.errors) {
                $('.lara_error').remove(); // remove old errors

                $.each(errorResponse.responseJSON.errors, function (index, errorMessage) {
                    $("input[name='" + index + "']").next('span').remove();
                    $("select[name='" + index + "']").next('span').remove();
                    $("textarea[name='" + index + "']").next('span').remove();

                    let spanEl = document.createElement('span')
                    $(spanEl).addClass('text-danger lara_error').text(errorMessage).insertAfter($("input[name='" + index + "']"))
                    $(spanEl).addClass('text-danger').text(errorMessage).insertAfter($("select[name='" + index + "']"))
                    $(spanEl).addClass('text-danger').text(errorMessage).insertAfter($("textarea[name='" + index + "']"))
                });
            }
        }
    });
});
$(document).ready(function () {
    if (typeof searched_wallet_list_id != "undefined" && searched_wallet_list_id) {
        $(".bootstrap-table-filter-control-wallet_type option[value='"+searched_wallet_list_id+"']").prop('selected',true).trigger('change');
    }
    if (typeof searched_id != "undefined" && searched_id) {
        $(".bootstrap-table-filter-control-transaction_id").val(searched_id).trigger('change');
    }
    $('#activites').on('change', function () {
        $('#bstable').bootstrapTable('refresh');
    });
});
function ajaxRequestMemberWalletTransaction(params) {
    let url = baseURL + "member/transactions/list/all";
    if (typeof searched_id != "undefined" && searched_id) {
        params.data.data = searched_id;
    }
    if (typeof searched_wallet_list_id != "undefined" && searched_wallet_list_id) {
        params.data.wallet_list_id = searched_wallet_list_id;
    }

    let filter = {};
    if (params.data.filter) {
        filter = JSON.parse(params.data.filter)
    }

    if (typeof filterWalletListId != 'undefined' && filterWalletListId != ''){
        filter['wallet_type'] = filterWalletListId;
        setTimeout(function () {
            $("#bstable .bootstrap-table-filter-control-wallet_type option[value='"+filterWalletListId+"']").prop("selected", true);
            filterWalletListId = '';
        },500)
    }
    params.data.filter = JSON.stringify(filter);

    $.get(url + '?' + $.param(params.data)).then(function (res) {
        params.success(res);
        let currentWalletType = $(".bootstrap-table-filter-control-wallet_type option:selected").val();
        if (!currentWalletType && searched_wallet_list_id) {
            $(".bootstrap-table-filter-control-wallet_type option[value='"+searched_wallet_list_id+"']").prop('selected',true).trigger('change');
        }
        let currentTransactionId = $(".bootstrap-table-filter-control-transaction_id").val();
        if (!currentTransactionId && searched_id) {
            $(".bootstrap-table-filter-control-transaction_id").val(searched_id).trigger('change');
        }

        setTimeout(function () {
            let activityFilter = $('select.bootstrap-table-filter-control-activity');
            if (activityFilter.length) {
                const previousValue = activityFilter.val();
                activityFilter.empty();
                const weekOptions = [
                    { value: 'all', text: 'All' },
                    { value: 'day', text: 'Daily' },
                    { value: 'week', text: 'Weekly' },
                ];

                weekOptions.forEach(opt => {
                    activityFilter.append($('<option>', {
                        value: opt.value,
                        text: opt.text,
                        class: 'text-black'
                    }));
                });
                if (!previousValue) {
                    activityFilter.val('week').trigger('change');
                } else if (previousValue && activityFilter.find(`option[value="${previousValue}"]`).length) {
                    activityFilter.val(previousValue);
                }
            }
        }, 200);
    });
}
$('#internal_comment').change(function () {
    if (this.checked) {
        internalCommentStatus = $(this).val();
    } else {
        internalCommentStatus = '';
    }
    $('#bstable').bootstrapTable('refresh');
});

$(document).on('click', 'button[name="clearSearch"]', function () {
    filterWalletListId = '';
    $(".bootstrap-table-filter-control-wallet_type option[value='"+searched_wallet_list_id+"']").prop('selected',true).trigger('change');

    $('#activites').val('').trigger('change');
    $('#bstable').bootstrapTable('refresh');
});

let lastExpandedIndex = null;

window.detailsEvents = {
    'click .view-details': function (e, value, row, index) {
        const $table = $('#bstable');
        const $clickedRow = $(e.currentTarget).closest('tr');

        // If a nested row already exists after this one, remove it
        const $nextRow = $clickedRow.next('tr.nested-row');
        const isAlreadyExpanded = $nextRow.length > 0;

        // Collapse previously expanded row
        if (lastExpandedIndex !== null && lastExpandedIndex !== index) {
            const $allRows = $table.find('tbody > tr');
            const $prevClickedRow = $allRows.eq(lastExpandedIndex);
            const $prevNestedRow = $prevClickedRow.next('tr.nested-row');
            $prevNestedRow.remove();
            $prevClickedRow.find('.view-details').html(renderIconTag('view')+'Details');
        }

        if (isAlreadyExpanded) {
            $nextRow.remove();
            $(e.currentTarget).html(renderIconTag('view')+'Details');
            lastExpandedIndex = null;
        } else {
            // Insert a new row after current to contain nested table
            const nestedRowId = 'nestedTable-' + row.wallet_id;
            const nestedTableHtml = `
                <tr class="nested-row">
                    <td colspan="${$clickedRow.children().length}">
                        <div class="nested-table-wrapper" id="${nestedRowId}">
                            <table id="nested-${row.wallet_id}"></table>
                        </div>
                    </td>
                </tr>
            `;
            $clickedRow.after(nestedTableHtml);
            $(e.currentTarget).html(renderIconTag('hide')+'Hide');
            lastExpandedIndex = index;

            // Load the nested table
            loadNestedTable(row);
        }
    }
};

function loadNestedTable(row) {
    const nestedId = '#nested-' + row.wallet_id;
    const activity = $('select.bootstrap-table-filter-control-activity').val();

    $(nestedId).bootstrapTable({
        url: baseURL + "member/transactions/sub-transactions",
        method: 'get',
        queryParams: function (params) {
            return {
                ...params,
                mainRowId: row.id,
                wallet_list_id: row.wallet.wallet_list_id,
                created_at: row.created_at,
                action: row.action_key,
                wallet_id: row.wallet_id,
                activity: activity
            };
        },
        sidePagination: 'server',
        pagination: true,
        columns: [
            { field: 'no', title: '#', align: 'center', width: 50 },
            { field: 'created_at', title: 'Week of Year', width: 130 },
            { field: 'action', title: 'Action', width: 70 },
            { field: 'wallet_type', title: 'Wallet', width: 80 },
            { field: 'description', title: 'Description', width: 250 },
            { field: 'amount', title: 'Amount', width: 100 },
        ],
        onLoadSuccess: function (data) {
            console.log('Loaded sub-transactions for row:', row.id);
        },
        onLoadError: function () {
            console.error('Error loading sub-transactions for row:', row.id);
        }
    });
}
