jQuery(document).ready(function ($) {
    function loadEvents(page = 1, search = '', status = '', display = '', limit = 10) {
        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: {
                action: "eventbookings_load_events",
                page: page,
                search: search,
                status: status,
                display: display,
                limit: limit,
                nonce: eventbookings_wp_global_object.nonce,
            },
            beforeSend: function () {
                $('#pagination').html('');
                $('#event-table-body').html('<tr><td colspan="8"><div style="height: 200px; text-align: center; display: flex; align-items: center; justify-content: center;"><div class="eventbookings-loader"><div></div><div></div><div></div></div></div></td></tr>');
            },
            success: function (response) {
                $('#event-table-body').html(response.html);
                $('#pagination').html(response.pagination);
            }
        });
    }

    // Load events on page load
    loadEvents();

    $('#sync-event-action').click(function () {
        $('#search-events').val('');
        $('#filter-status').val('');
        $('#filter-display').val('');
        $('#filter-limit').val('10');

        loadEvents();
    })

    // Pagination click event
    $(document).on("click", ".pagination-link", function (e) {
        e.preventDefault();
        let page = $(this).data("page");
        loadEvents(page, $('#search-events').val(), $('#filter-status').val(), $('#filter-display').val(), $('#filter-limit').val());
    });

    // Define a debounce function
    function debounce(func, delay) {
        let timeoutId;
        return function (...args) {
            const context = this;
            clearTimeout(timeoutId);
            timeoutId = setTimeout(function () {
                func.apply(context, args);
            }, delay);
        };
    }

// Bind the keyup event with the debounce function
    $('#search-events').on('input', debounce(function () {
        console.log($(this).val())
        loadEvents(1, $('#search-events').val().trim(), $('#filter-status').val(), $('#filter-display').val(), $('#filter-limit').val());
    }, 1000)); // 300ms delay

    // Filter by event status
    $('#filter-status').on("change", function () {
        loadEvents(1, $('#search-events').val(), $(this).val(), $('#filter-display').val(), $('#filter-limit').val());
    });

    $('#filter-limit').on("change", function () {
        loadEvents(1, $('#search-events').val(), $('#filter-status').val(), $('#filter-display').val(), $('#filter-limit').val());
    });

    // Filter by event display
    $('#filter-display').on("change", function () {
        loadEvents(1, $('#search-events').val(), $('#filter-status').val(), $(this).val(), $('#filter-limit').val());
    });

    // Select all checkboxes
    $(document).on('change', '#select-all', function () {
        $('.event-checkbox').prop('checked', $(this).prop('checked'));
    });

    // Bulk actions apply
    $('#apply-bulk-action').on('click', function () {
        let action = $('#bulk-action').val();
        if (!action) {
            alert("Please select an action.");
            return;
        }

        $('.event-checkbox:checked').each(function () {
            let row = $(this).closest('tr'); // Get the parent row
            let toggleSwitch = row.find('.toggle-status'); // Find the toggle switch

            if (action === "activate" && !toggleSwitch.prop('checked')) {
                toggleSwitch.click(); // Click to activate
            } else if (action === "deactivate" && toggleSwitch.prop('checked')) {
                toggleSwitch.click(); // Click to deactivate
            }
        });
        $('.event-checkbox').removeAttr('checked');
        $('#select-all').removeAttr('checked');
    });
    $('#apply-clear-action').on('click', function () {
        // Clear input and select fields
        $('#search-events').val('');
        $('#filter-status').val('');
        $('#filter-display').val('');

        // Trigger event reload (you might have a function for this)
        loadEvents(1); // Assuming loadEvents is your function for loading events
    });

    // Toggle event status
    $(document).on('change', '.toggle-status', function () {
        let event_uuid = $(this).data('id');
        let status = $(this).prop('checked') ? 1 : 0;

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'eventbookings_save_event_status',
                event_uuid: event_uuid,
                status: status,
                event_status_nonce: eventbookings_wp_global_object.nonce,
            },
            success: function (response) {
                console.log(response);
            },
            error: function (xhr, status, error) {
                console.error('Error:', error);
            }
        });
    });

    $(document).on('change', '.toggle-feature-status', function () {
        let event_uuid = $(this).data('id');
        let status = $(this).prop('checked') ? 1 : 0;

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'eventbookings_save_featured_event_status',
                event_uuid: event_uuid,
                status: status,
                event_status_nonce: eventbookings_wp_global_object.nonce,
            },
            success: function (response) {
                console.log(response);
            },
            error: function (xhr, status, error) {
                console.error('Error:', error);
            }
        });
    });
});
jQuery(document).ready(function ($) {
    $(".js-copy-button").click(function () {
        var input = $(this).siblings(".event_shortcode"); // grab input in same box
        var temp = $("<input>");
        $("body").append(temp);
        temp.val(input.val()).select();
        document.execCommand("copy");
        temp.remove();

        // show success message inside same box
        var successMsg = $(this).siblings('.js-copy-success');
        successMsg.show();
        setTimeout(function () {
            successMsg.hide();
        }, 3000);
    });

});
