/* globals jQuery:true, ajaxurl:true, secnin_vl:true */
/*
* Security Ninja PRO
* (c) 2021 WP SECURITY NINJA 
*/

jQuery(document).ready(function ($) {
    const visitorTable = $('#secnin-visitor-log').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: ajaxurl,
            type: 'POST',
            data: function(d) {
                d.action = 'secnin_get_visitor_data';
                d.nonce = secnin_vl.vl_nonce;
                return d;
            },
            error: function(xhr, error, code) {
                const errorMsg = "<strong>"+ secnin_vl.text.errorloadingdata + "</strong><br>" +
                secnin_vl.text.status + xhr.status + " (" + xhr.statusText + ")<br>" +
                secnin_vl.text.error + error + "<br>" +
                secnin_vl.text.code + code + "<br>" +
                secnin_vl.text.response + xhr.responseText;
                $('#datatable-error').html(errorMsg).show();
            },
            dataSrc: function(json) {
                return json.data || [];
            }
        },
        columns: [
            { data: 'timestamp', title: secnin_vl.text.event },
            { data: 'url', title: secnin_vl.text.url },
            { data: 'details', title: secnin_vl.text.details, orderable: false },
            { data: 'actions', title: secnin_vl.text.action, orderable: false }
        ],
        order: [[0, 'desc']],
        pageLength: 25,
        dom: '<"top"<"left"l><"right"f>p>rt<"bottom"ip><"clear">'
    });

    // Add refresh button handler
    $('#refresh-visitor-log').on('click', function() {
        const button = $(this);

        button.prop('disabled', true);

        // Reload the data
        visitorTable.ajax.reload(function() {
            button.prop('disabled', false);
        });
    });

    // Ban IP functionality
    $(document).on('click', '.secnin-banip', function(e) {
        e.preventDefault();
        if (!confirm(secnin_vl.text.areyousureblockip)) {
            return false;
        }

        $.post(secnin_vl.ajaxurl, {
            action: 'secnin_vl_banip',
            _ajax_nonce: $(this).data('nonce'),
            banip: $(this).data('banip')
        }, function(response) {
            if (response.success) {
                visitorTable.ajax.reload();
            }
        });
    });
});