(function($) {
    'use strict';

    var PCMembershipAdmin = {
        init: function() {
            this.bindEvents();
            this.loadStats();
            this.initPlanModal();
            this.initAccessForm();
        },

        bindEvents: function() {
            $(document).on('click', '.pc-membership-add-plan-btn', $.proxy(this.openPlanModal, this));
            $(document).on('click', '.pc-membership-edit-plan', $.proxy(this.editPlan, this));
            $(document).on('click', '.pc-membership-delete-plan', $.proxy(this.deletePlan, this));
            $(document).on('click', '.pc-membership-modal-close, .pc-membership-modal-cancel', $.proxy(this.closePlanModal, this));
            $(document).on('submit', '#pc-membership-plan-form', $.proxy(this.savePlan, this));
            $(document).on('change', '#plan_type', $.proxy(this.toggleBillingInterval, this));
            $(document).on('click', '.pc-membership-delete-rule', $.proxy(this.deleteAccessRule, this));
            $(document).on('submit', '#pc-membership-access-form', $.proxy(this.saveAccessRule, this));
            $(document).on('change', '#access_redirect', $.proxy(this.toggleCustomRedirect, this));
            $(document).on('change', '#access_content_type', $.proxy(this.loadContentOptions, this));
        },

        loadStats: function() {
            $.ajax({
                url: pcMembershipAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'pc_membership_get_stats',
                    nonce: pcMembershipAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        var data = response.data;
                        $('#pc-members-count').text(data.active_members);
                        $('#pc-subscriptions-count').text(data.active_subscriptions);
                        $('#pc-revenue').text(data.revenue);
                        $('#pc-plans-count').text(data.total_plans);

                        if (data.recent_subscriptions && data.recent_subscriptions.length > 0) {
                            var tbody = $('#pc-recent-subscriptions tbody');
                            tbody.empty();
                            $.each(data.recent_subscriptions, function(i, sub) {
                                var display_name = sub.display_name || sub.user_login || 'User #' + sub.user_id;
                                tbody.append(
                                    '<tr>' +
                                    '<td>' + display_name + '</td>' +
                                    '<td>' + sub.plan_name + '</td>' +
                                    '<td>' + sub.status + '</td>' +
                                    '<td>' + sub.started_at.substring(0, 10) + '</td>' +
                                    '</tr>'
                                );
                            });
                        }
                    }
                }
            });
        },

        initPlanModal: function() {
            $('#pc-membership-plan-modal').dialog({
                autoOpen: false,
                modal: true,
                width: '90%',
                maxWidth: 600,
                closeText: ''
            });
        },

        openPlanModal: function(e) {
            if (e) e.preventDefault();
            $('#pc-membership-plan-form')[0].reset();
            $('#plan_id').val('');
            $('#pc-membership-plan-modal').dialog('open');
            this.toggleBillingInterval();
        },

        editPlan: function(e) {
            e.preventDefault();
            var planId = $(e.currentTarget).data('plan-id');

            $.ajax({
                url: pcMembershipAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'pc_membership_get_plan',
                    plan_id: planId,
                    nonce: pcMembershipAdmin.nonce
                },
                success: $.proxy(function(response) {
                    if (response.success && response.data.plan) {
                        var plan = response.data.plan;
                        $('#plan_id').val(plan.id);
                        $('#plan_name').val(plan.name);
                        $('#plan_description').val(plan.description || '');
                        $('#plan_price').val(plan.price);
                        $('#plan_type').val(plan.is_subscription);
                        $('#plan_billing_interval').val(plan.billing_interval || 'month');
                        $('#plan_trial_days').val(plan.trial_days || 0);
                        $('#plan_benefits').val(plan.benefits || '');
                        $('#plan_role').val(plan.role || 'subscriber');
                        $('#pc-membership-plan-modal').dialog('open');
                        this.toggleBillingInterval();
                    }
                }, this)
            });
        },

        savePlan: function(e) {
            e.preventDefault();
            var $form = $('#pc-membership-plan-form');
            var formData = $form.serialize();

            $.ajax({
                url: pcMembershipAdmin.ajax_url,
                type: 'POST',
                data: formData + '&action=pc_membership_save_plan&nonce=' + pcMembershipAdmin.nonce,
                success: function(response) {
                    if (response.success) {
                        $('#pc-membership-plan-modal').dialog('close');
                        window.location.reload();
                    } else {
                        alert(pcMembershipAdmin.i18n.error + ': ' + (response.data || 'Unknown error'));
                    }
                },
                error: function() {
                    alert(pcMembershipAdmin.i18n.error);
                }
            });
        },

        deletePlan: function(e) {
            e.preventDefault();
            if (!confirm(pcMembershipAdmin.i18n.confirmDelete)) return;

            var planId = $(e.currentTarget).data('plan-id');

            $.ajax({
                url: pcMembershipAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'pc_membership_delete_plan',
                    plan_id: planId,
                    nonce: pcMembershipAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        window.location.reload();
                    } else {
                        alert(pcMembershipAdmin.i18n.error);
                    }
                }
            });
        },

        closePlanModal: function(e) {
            if (e) e.preventDefault();
            $('#pc-membership-plan-modal').dialog('close');
        },

        toggleBillingInterval: function() {
            var isSubscription = $('#plan_type').val() === '1';
            $('#billing_interval_row').toggle(isSubscription);
        },

        initAccessForm: function() {
            this.loadContentOptions();
        },

        loadContentOptions: function() {
            var contentType = $('#access_content_type').val();
            var $select = $('#access_content_id');

            $select.html('<option value="">Loading...</option>');

            var data = {
                action: 'pc_membership_get_content_for_rule',
                content_type: contentType,
                nonce: pcMembershipAdmin.nonce
            };

            $.ajax({
                url: pcMembershipAdmin.ajax_url,
                type: 'POST',
                data: data,
                success: function(response) {
                    $select.empty();
                    $select.append('<option value="">-- Select --</option>');
                    if (response.success && response.data.items) {
                        $.each(response.data.items, function(i, item) {
                            $select.append('<option value="' + item.id + '">' + item.title + '</option>');
                        });
                    }
                }
            });
        },

        saveAccessRule: function(e) {
            e.preventDefault();
            var $form = $('#pc-membership-access-form');

            $.ajax({
                url: pcMembershipAdmin.ajax_url,
                type: 'POST',
                data: $form.serialize() + '&action=pc_membership_save_access_rule&nonce=' + pcMembershipAdmin.nonce,
                success: function(response) {
                    if (response.success) {
                        window.location.reload();
                    } else {
                        alert(pcMembershipAdmin.i18n.error + ': ' + (response.data || 'Unknown error'));
                    }
                }
            });
        },

        deleteAccessRule: function(e) {
            e.preventDefault();
            if (!confirm('Are you sure you want to delete this rule?')) return;

            var ruleId = $(e.currentTarget).data('rule-id');

            $.ajax({
                url: pcMembershipAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'pc_membership_delete_access_rule',
                    rule_id: ruleId,
                    nonce: pcMembershipAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        window.location.reload();
                    } else {
                        alert(pcMembershipAdmin.i18n.error);
                    }
                }
            });
        },

        toggleCustomRedirect: function() {
            var redirect = $('#access_redirect').val();
            $('#custom_redirect_row').toggle(redirect === 'custom');
        }
    };

    $(document).ready(function() {
        PCMembershipAdmin.init();
    });

})(jQuery);
