/**
 * Handles all AJAX interactions for the Visitors admin page using event delegation.
 * This is the final, managed version.
 * @param {object} jQuery - jQuery
 */
jQuery(function (jQuery) {

    // The static wrapper for the entire visitors page
    var pageWrapper = jQuery('#em-visitors-page-wrapper');

    // If the wrapper doesn't exist on this page, do nothing.
    if (!pageWrapper.length) {
        return;
    }

    // --- EVENT LISTENERS using DELEGATION from the static wrapper ---

    // Listener for the DELETE button
    pageWrapper.on('click', '.visitor-delete-btn', function () {
        if (!confirm('Are you sure?')) return;

        var visitor_id = jQuery(this).data('id');
        var nonce = em_visitor_ajax_object.delete_nonce;

        jQuery.post(em_visitor_ajax_object.ajax_url, {
            action: 'em_delete_visitor', nonce: nonce, id: visitor_id
        }).done(function (response) {
            if (response.success) {
                jQuery('#record-' + visitor_id).fadeOut(500, function () { jQuery(this).remove(); });
            } else {
                alert('Error: ' + (response.data.message || 'Could not delete visitor.'));
            }
        });
    });

    // Listener for the VIEW button
    pageWrapper.on('click', '.visitor-view-btn', function () {
        var visitor_id = jQuery(this).data('id');
        var nonce = em_visitor_ajax_object.view_nonce;
        jQuery('#em_input_load').show();

        jQuery.post(em_visitor_ajax_object.ajax_url, {
            action: 'em_view_visitor', nonce: nonce, id: visitor_id
        }).done(function (response) {
            jQuery('#em_input_load').hide();
            if (response.success) {
                jQuery('#modal-view-visitor').html(response.data.html).show();
            } else {
                alert('Error: ' + (response.data.message || 'Could not get details.'));
            }
        });
    });

    // Listener for the EDIT STATUS button (pencil icon)
    pageWrapper.on('click', '.status-edit-btn', function () {
        var id = jQuery(this).data('id');
        jQuery(this).hide();
        jQuery('#span_status_' + id).hide();
        jQuery('.status-select-dropdown[data-id="' + id + '"]').show();
        jQuery('.status-close-btn[data-id="' + id + '"]').show();
    });

    // Listener for the CLOSE STATUS button (X icon)
    pageWrapper.on('click', '.status-close-btn', function () {
        var id = jQuery(this).data('id');
        jQuery(this).hide();
        jQuery('.status-select-dropdown[data-id="' + id + '"]').hide();
        jQuery('.status-edit-btn[data-id="' + id + '"]').show();
        jQuery('#span_status_' + id).show();
    });

    // Listener for when a new status is selected
    pageWrapper.on('change', '.status-select-dropdown', function () {
        var item_id = jQuery(this).data('id');
        var new_status = jQuery(this).val();
        var nonce = em_visitor_ajax_object.status_nonce;

        jQuery('#status-updating-msg-' + item_id).show();

        jQuery.post(em_visitor_ajax_object.ajax_url, {
            action: 'em_update_visitor_status', nonce: nonce, id: item_id, status: new_status
        }).done(function (response) {
            jQuery('#status-updating-msg-' + item_id).hide();
            if (response.success) {
                jQuery('#span_status_' + item_id).text(new_status);
                jQuery('.status-close-btn[data-id="' + item_id + '"]').click();
            } else {
                alert('Error updating status.');
            }
        });
    });



    // --- BULK ACTION JAVASCRIPT ---

    // Listener for the main "Select All" checkbox in the header
    pageWrapper.on('click', '#select-all-checkbox', function () {
        // Find all checkboxes in the table body and set their 'checked' state
        // to match the header checkbox's state.
        pageWrapper.find('.table-item-checkbox').prop('checked',jQuery(this).is(':checked'));
    });

    // Listener for the "Delete Selected" button in the footer
    pageWrapper.on('click', '#bulk-delete-button', function () {
        var selected_ids = [];
        // Create an array of all the selected visitor IDs
        pageWrapper.find('.table-item-checkbox:checked').each(function () {
            selected_ids.push(jQuery(this).val());
        });

        if (selected_ids.length === 0) {
            alert('Please select at least one item to delete.');
            return;
        }

        if (!confirm('Are you sure you want to delete all selected items?')) {
            return;
        }

        // Use the nonce provided by our PHP localization
        var nonce = em_visitor_ajax_object.delete_all_nonce;

       jQuery.post(em_visitor_ajax_object.ajax_url, {
            action: 'em_delete_all_visitors', // This will be our new PHP method
            nonce: nonce,
            ids: selected_ids // Send the array of IDs
        }).done(function (response) {
            if (response.success) {
                // Fade out and remove each deleted row
               jQuery.each(selected_ids, function (index, id) {
                   jQuery('#record-' + id).fadeOut(500, function () {jQuery(this).remove(); });
                });
            } else {
                alert('Error: ' + (response.data.message || 'Could not delete items.'));
            }
        });
    });

    // --- OTHER LISTENERS ---

    // Download Visitor List
    pageWrapper.on('click', '#download_visitor', function () {
        var filter = jQuery('#select_event').val();
        var button = jQuery(this);
        button.html('<i class="fa fa-spinner fa-spin"></i> Generating...');

        jQuery.post(em_visitor_ajax_object.ajax_url, {
            action: 'em_download_visitor_list',
            nonce: em_visitor_ajax_object.download_nonce,
            filter: filter
        }).done(function (response) {
            button.html('<i class="fa fa-download"></i> Download Visitor List');
            if (response.success) {
                window.location.href = response.data.fileurl;
            } else {
                alert('Error: ' + (response.data.message || 'Could not generate file.'));
            }
        });
    });

    // Hide the modal when the close button is clicked
    jQuery('body').on('click', '#modal-view-visitor .close, #modal-view-visitor .btn-success', function () {
        jQuery('#modal-view-visitor').hide().html('');
    });
});