/* 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();
        var $btn = $(this);
        SnDialog.confirm({
            message: secnin_vl.text.areyousureblockip,
            danger: true
        }).then(function(ok) {
            if (!ok) {
                return;
            }

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