jQuery(document).ready(function($) {
    const $btn = $('#ahapay-api-button');
    const $response = $('#ahapay-api-response');
    $btn.on('click', function(e) {
        e.preventDefault(); // ✅ This prevents the page refresh

        var orderId = $(this).data('order-id');

        // $('#ahapay-api-response').text('Calling API...');
        $btn.prop('disabled', true).text('Calling API...');

        $.ajax({
            url: ahapaybuynowpaylater_api_data.ajax_url,
            method: 'POST',
            data: {
                action: 'ahapaybuynowpaylater_call_api',
                order_id: orderId,
                nonce: ahapaybuynowpaylater_api_data.nonce,
            },
            success: function(response) {
                if (response.success) {
                    $('#ahapay-api-response').html(response.data.message).addClass('updated');
                    $response
                        .html(response.data.message)
                        .addClass('ahapay-success');
                    // Add this code to handle refresh
                    if (response.data.refresh) {
                        setTimeout(function() {
                            window.location.reload();
                        }, 2000); // Refresh after 1 second delay to show the message
                    }
                } else {
                    $response
                        .html(response.data.message)
                        .addClass('ahapay-error');
                }
            },
            error: function(xhr) {
                $response
                    .text('AJAX failed')
                    .addClass('ahapay-error');
            }
        });
    });
});