/**
 * Admin JavaScript for Stripe Subscription Manager
 */

(function($) {
    'use strict';

    if (typeof strp_sub_admin_params === 'undefined') { return; }

    /**
     * Show an inline admin notice near the action trigger.
     */
    function showNotice(message, type) {
        var cssClass = type === 'error' ? 'notice-error' : 'notice-success';
        var $notice = $('<div class="notice ' + cssClass + ' is-dismissible" role="alert" style="margin:10px 0;"><p></p></div>');
        $notice.find('p').text(message);
        $('.wrap h1').first().after($notice);
        setTimeout(function () { $notice.fadeOut(400, function () { $(this).remove(); }); }, 5000);
    }

    $(document).ready(function() {
        // Handle admin cancel subscription button click
        $(document).on('click', '.strp-sub-admin-cancel-subscription', function(e) {
            e.preventDefault();

            if (!confirm(strp_sub_admin_params.i18n_confirm_cancel || 'Are you sure you want to cancel this subscription?')) {
                return;
            }

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

            // Disable button and show loading state
            $button.prop('disabled', true).text(strp_sub_admin_params.i18n_cancelling || 'Cancelling...');

            // Cancel subscription
            $.ajax({
                url: strp_sub_admin_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'strp_sub_admin_cancel_subscription',
                    nonce: strp_sub_admin_params.nonce,
                    subscription_id: subscriptionId,
                    order_id: orderId
                },
                success: function(response) {
                    if (response.success) {
                        showNotice(response.data.message || strp_sub_admin_params.i18n_cancelled || 'Subscription cancelled successfully', 'success');
                        setTimeout(function () { location.reload(); }, 1500);
                    } else {
                        showNotice(response.data.message || strp_sub_admin_params.i18n_error || 'An error occurred', 'error');
                        $button.prop('disabled', false).text(strp_sub_admin_params.i18n_cancel || 'Cancel');
                    }
                },
                error: function() {
                    showNotice(strp_sub_admin_params.i18n_error || 'An error occurred. Please try again.', 'error');
                    $button.prop('disabled', false).text(strp_sub_admin_params.i18n_cancel || 'Cancel');
                }
            });
        });
    });

})(jQuery);
