jQuery(document).ready(function($) {
    // Handle survey submission
    $('form.survey-form').on('submit', function(e) {
        e.preventDefault();
        var form = $(this);
        var surveyId = form.find('input[name="survey_id"]').val();
        var responses = form.find('input[name="responses"]:checked').serialize();

        $.post(surveys_ajax_object.ajax_url, {
            action: 'submit_survey_answers',
            survey_id: surveyId,
            responses: responses
        }, function(response) {
            if (response.success) {
                alert(response.data.message);
                location.href = location.href + '?refresh=' + new Date().getTime(); // Force reload with timestamp
            } else {
                alert(response.data.message);
            }
        }).fail(function(xhr, status, error) {
            alert('Error: ' + error + '. Details: ' + xhr.responseText);
            console.log('AJAX Error:', xhr.responseText);
        });
    });

    // Handle withdrawal request
    $('button[name="withdraw"]').on('click', function(e) {
        e.preventDefault();
        let userConfirmed = confirm('Are you sure you want to request a withdrawal?');
        if (userConfirmed) {
            $.post(surveys_ajax_object.ajax_url, {
                action: 'process_withdrawal',
                user_id: surveys_ajax_object.user_id,
                _ajax_nonce: $('input[name="withdraw_nonce"]').val()
            }, function(response) {
                if (response.success) {
                    alert(response.data.message);
                    location.href = location.href + '?refresh=' + new Date().getTime(); // Force reload
                } else {
                    alert(response.data.message);
                    $('#withdrawal-status').html(response.data.status);
                }
            }).fail(function() {
                alert('Something went wrong. Please try again.');
            });
        }
    });
});