let data = {
    start_date: null,
    end_date: null,
    log_user: null,
    log_module: null,
    activity_key: null
};

let currentDate = new Date();
let firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
let lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);

let formatDate = (date) => date.toISOString().split('T')[0];

$(document).ready(function () {
    data.start_date = formatDate(firstDay);
    data.end_date = formatDate(lastDay);

    $('.input-daterange input').first().val(data.start_date);
    $('.input-daterange input').last().val(data.end_date);

    activityLogDataTable();
});

$(function () {
    $('.input-daterange input').last().datepicker().on('changeDate', function () {
        data.start_date = $('.input-daterange input').first().val();
        data.end_date = $(this).val();

        data.log_user = null;
        data.log_module = null;
        data.activity_key = null;

        $('#log_user').val('all');
        $('#log_module').val('all');
        $('#activity_key').val('all');

        // Hide module and activity dropdowns initially
        $('#log_module').closest('li').addClass('d-none');

        $.get("/activity-logs/users", data, response => {
            updateSelectElement($('#log_user'), response.logUsers.map(user => ({
                value: user.user?.uuid,
                text: user.user?.full_name
            })));
            $('#activity_key').closest('li').addClass('d-none');
            activityLogDataTable();
        });
    });

    $('#log_user').on('change', function () {
        data.log_user = $(this).val();

        // Reset log_module and activity_key to null and update dropdowns to 'all'
        data.log_module = null;
        data.activity_key = null;
        $('#log_module').val('all');
        $('#activity_key').val('all');

        $('#activity_key').closest('li').addClass('d-none');

        $.get("/activity-logs/modules", data, response => {
            updateSelectElement($('#log_module'), response.modules.map(mod => ({
                value: mod.module,
                text: mod.module
            })));
            activityLogDataTable();
        });
    });

    $('#log_module').on('change', function () {
        data.log_module = $(this).val();
        data.activity_key = null;

        $.get("/activity-logs/keys", data, response => {
            updateSelectElement($('#activity_key'), response.logKeys.map(key => ({
                value: key.activity,
                text: key.activity
            })));
            activityLogDataTable();
        });
    });

    $('#activity_key').on('change', function () {
        data.activity_key = $(this).val();
        activityLogDataTable();
    });
});

function buildUrl() {
    let baseUrl = "/activity-logs/data-table";
    let params = new URLSearchParams();

    if (data.start_date && data.end_date) {
        params.append('start_date', data.start_date);
        params.append('end_date', data.end_date);

        if (data.log_user) {
            params.append('log_user', data.log_user);

            // Reset log_module and activity_key if log_user is selected
            if (!data.log_module || data.log_module === 'all') {
                data.log_module = null;
            }
            if (!data.activity_key || data.activity_key === 'all') {
                data.activity_key = null;
            }
        }

        if (data.log_module) params.append('log_module', data.log_module);
        if (data.activity_key) params.append('activity_key', data.activity_key);
    }

    return `${baseUrl}?${params.toString()}`;
}

function updateSelectElement(selectElement, dataList, placeholder) {
    selectElement.empty().append($('<option>', {
        value: 'all',
        text: filterModuleSelectOption
    }));
    $.each(dataList, (index, item) => selectElement.append($('<option>', {
        value: item.value,
        text: item.text
    })));
    selectElement.closest('li').removeClass('d-none');
}

function activityLogDataTable() {
    let url = buildUrl();

    var table = $('#activity-logs-dt').DataTable({
        destroy: true,
        processing: true,
        scrollX: false,
        ordering: false,
        autoWidth: true,
        paging: true,
        "pageLength": 20, // Number of rows per page
        "lengthChange": true,
        "lengthMenu": [ // Custom page length menu
            [20, 40, 60, 80, 100], // Actual page lengths
            [20, 40, 60, 80, 100] // Display text for the page lengths
        ],
        ajax: {
            url
        },
        columns: [{
            data: 'user',
            name: 'user'
        },
        {
            data: 'role',
            name: 'role'
        },
        {
            data: 'module',
            name: 'module'
        },
        {
            data: 'activity',
            name: 'activity'
        },
        {
            data: 'ip',
            name: 'ip'
        },
        {
            data: 'meta',
            name: 'meta',
            visible: false
        },
        {
            data: 'description',
            name: 'description'
        },
        {
            data: 'activity_performed_at',
            name: 'activity_performed_at'
        },
        ],
        createdRow: function (row, data, index) {
            $(row).addClass('nk-tb-item');
        }
    });

    // Button click event to toggle the visibility of the 3rd column (index 2)
    $('#toggleColumn').off('click').on('click', function () {
        let column = table.column(5); // Change the index to target a different column
        let isVisible = column.visible();
        column.visible(!isVisible);

        // Update button text based on column visibility
        isVisible ? $('#toggleColumn').html('<em class="icon ni ni-eye"></em><span>' + showUserAgent + '</span>') : $('#toggleColumn').html('<em class="icon ni ni-eye"></em><span>' + hideUserAgent + '</span>');
    });
}
