jQuery(document).ready(function($) {

    $('input[type="checkbox"].opl-status-user').change(function() {
        var userId = $(this).data('user-id');
        var isVerified = $(this).is(':checked') ? 'true' : 'false';
        var nonce = $(this).data('nonce');
        var $this = $(this);

        $(this).prop('disabled', true);

        $.ajax({
            url: oplAdmin.ajax_url,
            type: 'POST',
            data: {
                action: 'opl_toggle_user_verification',
                user_id: userId,
                is_verified: isVerified,
                nonce: nonce
            },
            success: function(response) {
                $this.prop('disabled', false);

                if (response.success) {
                   // Do something
                } else {
                   console.log('Something went wrong. Please try again.');
                }
            },
            error: function() {
                $this.prop('disabled', false);
                console.log('Something went wrong. Please try again.');
            }
        });
    });


    $('.opl-verification-link').on('click', function (e) {
        e.preventDefault();

        const $container = $(this).closest('.opl-resend-container');
        const $link = $(this);
        const userId = $(this).data('user-id');
        const nonce = $(this).data('nonce');

        $container.find('.opl-success, .opl-error').hide();
        $container.find('.opl-spinner').show();

        if (!userId || !nonce) {
            alert('Invalid request.');
            return;
        }

        $.ajax({
            url: oplAdmin.ajax_url,
            method: 'POST',
            data: {
                action: 'opl_resend_verification',
                user_id: userId,
                nonce: nonce
            },
            beforeSend: function () {
                $link.text('Sending').addClass('disabled').css('pointer-events', 'none');
            },
            success: function (response) {
               $container.find('.opl-spinner').hide();

                if (response.success) {
                    $container.find('.opl-success').fadeIn();
                    $link.text('Sent').addClass('disabled').css('pointer-events', 'none');

                    const $toggleSwitch = $(`#opl-status-user-${userId}`);
                    console.log($toggleSwitch);
                    if ($toggleSwitch.length > 0) {
                        $toggleSwitch.prop('checked', false);
                    }
                } else {
                    $container.find('.opl-error').fadeIn();
                }
            },
            error: function () {
                $container.find('.opl-spinner').hide();
                $container.find('.opl-error').fadeIn();
            },
        });
    });
});
