<?php

if (! defined('ABSPATH')) {
    die('You are not allowed to call this page directly.');
}

class MeprOnboardingHelper
{
    /**
     * Set the steps completed in the onboarding process.
     *
     * @param integer $step The step number to set as completed.
     *
     * @return void
     */
    public static function maybe_set_steps_completed($step)
    {
        $steps_completed = (int) self::get_steps_completed();
        if ($step > $steps_completed) {
            self::set_steps_completed($step);
        }

        if ($steps_completed === 7) {
            update_option('mepr_onboarding_complete', '1');
        }
    }

    /**
     * Set the number of steps completed in the onboarding process.
     *
     * @param integer $step The step number to set as completed.
     *
     * @return void
     */
    public static function set_steps_completed($step)
    {
        update_option('mepr_onboarding_steps_completed', $step, false);

        if ($step === 0) {
            self::unmark_content_steps_skipped();
        }
    }

    /**
     * Get the number of steps completed in the onboarding process.
     *
     * @return integer The number of steps completed.
     */
    public static function get_steps_completed()
    {
        return get_option('mepr_onboarding_steps_completed', 0);
    }

    /**
     * Set the selected features for the onboarding process.
     *
     * @param array $features The features to set as selected.
     *
     * @return void
     */
    public static function set_selected_features($features)
    {
        update_option('mepr_onboarding_features', $features, false);
    }

    /**
     * Get the selected features data from the onboarding process.
     *
     * @return array The selected features data.
     */
    public static function get_selected_features_data()
    {
        $metadata = get_option('mepr_onboarding_features', true);
        $data     = is_array($metadata) ? $metadata : [];
        return $data;
    }

    /**
     * Get the selected features from the onboarding process.
     *
     * @return array The selected features.
     */
    public static function get_selected_features()
    {
        $data     = self::get_selected_features_data();
        $features = (isset($data['features']) && is_array($data['features'])) ? $data['features'] : [];
        return $features;
    }

    /**
     * Check if an addon is selectable.
     *
     * @param string $plugin_slug The slug of the plugin to check.
     *
     * @return boolean True if the addon is selectable, false otherwise.
     */
    public static function is_addon_selectable($plugin_slug)
    {
        $plugins          = get_plugins();
        $plugin_file_slug = $plugin_slug . '.php';
        $is_installed     = ! empty($plugins[$plugin_file_slug]);
        $selectable       = true;
        if ($is_installed) {
            if (is_plugin_active($plugin_file_slug)) { // If addon is already installed and active, it must not be selectable.
                $selectable = false;
            }
        }

        return $selectable;
    }

    /**
     * Get a list of selectable addons for features.
     *
     * @return array The list of selectable addons.
     */
    public static function features_addons_selectable_list()
    {
        $addons = [
            'memberpress-courses'         => [
                'selectable'  => MeprOnboardingHelper::is_addon_selectable('memberpress-courses/main'),
                'title'       => __('Course Creator', 'memberpress'),
                'description' => __('Sell what you know. Create memorable online courses, including quizzes and progress tracking.', 'memberpress'),
            ],
            'memberpress-coachkit'        => [
                'selectable'  => MeprOnboardingHelper::is_addon_selectable('memberpress-coachkit/main'),
                'title'       => __('CoachKit™', 'memberpress'),
                'description' => __('Seamlessly integrates with your existing Members, Memberships and Courses to provide a dynamic platform to sell an Unlimited number of coaching programs.', 'memberpress'),
            ],
            'memberpress-circles'         => [
                'selectable'  => MeprOnboardingHelper::is_addon_selectable('memberpress-circles/main'),
                'title'       => __('ClubCircles™', 'memberpress'),
                'description' => __('Build a thriving, private community! Create unlimited discussion forums and private sub-groups (we call them Circles). Fully integrated with your members and rules, this is the perfect tool to boost engagement and build a loyal tribe.', 'memberpress'),
            ],
            'memberpress-directory'       => [
                'selectable'  => MeprOnboardingHelper::is_addon_selectable('memberpress-directory/main'),
                'title'       => __('ClubDirectory™', 'memberpress'),
                'description' => __('Foster member connections! Launch a beautiful, searchable member directory. Allow members to create rich, customizable profiles to network and connect with each other, all within your private site.', 'memberpress'),
            ],
            'memberpress-downloads'       => [
                'selectable'  => MeprOnboardingHelper::is_addon_selectable('memberpress-downloads/main'),
                'title'       => __('Digital Downloads', 'memberpress'),
                'description' => __('Add value to your memberships by giving users access to downloadable files like white papers, guides, checklists, and videos – the sky’s the limit.', 'memberpress'),
            ],
            'memberpress-buddypress'      => [
                'selectable'  => MeprOnboardingHelper::is_addon_selectable('memberpress-buddypress/main'),
                'title'       => __('Member Community', 'memberpress'),
                'description' => __('Keep users coming back for more with a VIP forum or chat room they can access based on membership level. Available with MemberPress Growth or Scale.', 'memberpress'),
            ],
            'memberpress-developer-tools' => [
                'selectable'  => MeprOnboardingHelper::is_addon_selectable('memberpress-developer-tools/main'),
                'title'       => __('Zapier Integration', 'memberpress'),
                'description' => __('Work smarter not harder. Connect MemberPress with thousands of your favorite productivity and functionality apps and services. Available with MemberPress Scale.', 'memberpress'),
            ],
            'memberpress-gifting'         => [
                'selectable'  => MeprOnboardingHelper::is_addon_selectable('memberpress-gifting/memberpress-gifting'),
                'title'       => __('Gifting', 'memberpress'),
                'description' => __('Expand your audience and sell more memberships. With Gifting, you can market to people who know people who could use your membership. Available with MemberPress Scale.', 'memberpress'),
            ],
            'memberpress-corporate'       => [
                'selectable'  => MeprOnboardingHelper::is_addon_selectable('memberpress-corporate/main'),
                'title'       => __('Corporate Accounts', 'memberpress'),
                'description' => __('Allow your members to add sub-accounts to their memberships based on subscription level. Great for families and groups. Available with MemberPress Scale.', 'memberpress'),
            ],
            'easy-affiliate'             => [
                'selectable'  => MeprOnboardingHelper::is_addon_selectable('easy-affiliate/easy-affiliate'),
                'title'       => __('Affiliate Program', 'memberpress'),
                'description' => __('Create your own non-salaried sales team, and make up to 30% more in membership sales with referral marketing.', 'memberpress'),
            ],
        ];

        return MeprHooks::apply_filters('mepr_onboarding_selectable_addons', $addons);
    }

    /**
     * Get purchase links for feature addons.
     *
     * @return array The purchase links for feature addons.
     */
    public static function features_addons_purchase_links()
    {
        return [
            'easy-affiliate'      => MeprUtils::get_link_url('login_redirect_ea'),
            'memberpress-coachkit' => MeprUtils::get_link_url('login_redirect_coachkit'),
        ];
    }

    /**
     * Prepare a purchase message with a link.
     *
     * @param string $purchase_link The purchase link to include in the message.
     *
     * @return string The prepared purchase message.
     */
    public static function prepare_purchase_message($purchase_link)
    {
        return sprintf(
            // Translators: %1$s: opening anchor tag, %2$s: closing anchor tag.
            esc_html__('Unable to install. You can %1$spurchase it here%2$s, afterwards you can install it from the add-ons page.', 'memberpress'),
            '<a href="' . esc_url($purchase_link) . '">',
            '</a>'
        );
    }

    /**
     * Set the content post ID for the onboarding process.
     *
     * @param integer $id The content post ID to set.
     *
     * @return void
     */
    public static function set_content_post_id($id)
    {
        update_option('mepr_onboarding_content_post_id', $id, false);

        if (count(self::get_skipped_steps())) {
            self::unmark_content_steps_skipped();
            self::set_steps_completed(3);
        }
    }

    /**
     * Get the content post ID for the onboarding process.
     *
     * @return integer The content post ID.
     */
    public static function get_content_post_id()
    {
        return get_option('mepr_onboarding_content_post_id', 0);
    }

    /**
     * Mark content steps as skipped in the onboarding process.
     *
     * @return void
     */
    public static function mark_content_steps_skipped()
    {
        update_option('mepr_onboarding_content_steps_skipped', 1, false);
    }

    /**
     * Unmark content steps as skipped in the onboarding process.
     *
     * @return void
     */
    public static function unmark_content_steps_skipped()
    {
        update_option('mepr_onboarding_content_steps_skipped', 0, false);
    }

    /**
     * Set the membership post ID for the onboarding process.
     *
     * @param integer $id The membership post ID to set.
     *
     * @return void
     */
    public static function set_membership_post_id($id)
    {
        update_option('mepr_onboarding_membership_post_id', $id, false);

        if (count(self::get_skipped_steps()) && $id > 0) {
            self::unmark_content_steps_skipped();
            $content_id = self::get_content_post_id();
            if ($content_id > 0) {
                self::set_steps_completed(3);
            }
        }
    }

    /**
     * Get the membership post ID for the onboarding process.
     *
     * @return integer The membership post ID.
     */
    public static function get_membership_post_id()
    {
        return get_option('mepr_onboarding_membership_post_id', 0);
    }

    /**
     * Get the skipped steps in the onboarding process.
     *
     * @return array The skipped steps.
     */
    public static function get_skipped_steps()
    {
        $is_skipped = get_option('mepr_onboarding_content_steps_skipped', 0);
        if ($is_skipped) {
            return [3,4,5];
        }
        return [];
    }

    /**
     * Get the payment gateway data for the onboarding process.
     *
     * @return array|false The payment gateway data or false if not set.
     */
    public static function get_payment_gateway_data()
    {
        $gateway_id = get_option('mepr_onboarding_payment_gateway');

        if (empty($gateway_id)) {
            return false;
        }

        $mepr_options = MeprOptions::fetch();
        $gateway      = $mepr_options->payment_method($gateway_id, true, true);

        if ($gateway instanceof MeprStripeGateway) {
            return [
                'id'        => $gateway->id,
                'key'       => 'stripe',
                'logo_url'  => MEPR_IMAGES_URL . '/stripe-logo.png',
                'connected' => !empty($gateway->get_public_key()) && !empty($gateway->get_secret_key()),
                'account'   => $gateway->service_account_name,
            ];
        } elseif ($gateway instanceof MeprPayPalCommerceGateway) {
            return [
                'id'        => $gateway->id,
                'key'       => 'paypal',
                'logo_url'  => MEPR_IMAGES_URL . '/PayPal_with_Tagline.svg',
                'connected' => !empty($gateway->settings->test_client_id) || !empty($gateway->settings->live_client_id),
                'account'   => '',
            ];
        } elseif ($gateway instanceof MeprAuthorizeGateway) {
            return [
                'id'        => $gateway->id,
                'key'       => 'authorize',
                'logo_url'  => MEPR_IMAGES_URL . '/onboarding/authorize.net.svg',
                'connected' => !empty($gateway->settings->login_name) && !empty($gateway->settings->transaction_key) && !empty($gateway->settings->signature_key),
                'account'   => '',
            ];
        } elseif ($gateway_id === 'MeprAuthorizeGateway') {
            return [
                'id'        => 'MeprAuthorizeGateway',
                'key'       => 'authorize',
                'logo_url'  => MEPR_IMAGES_URL . '/onboarding/authorize.net.svg',
                'connected' => false,
                'account'   => '',
            ];
        }

        return false;
    }

    /**
     * Get the HTML for the payment gateway in the onboarding process.
     *
     * @return string The HTML for the payment gateway.
     */
    public static function get_payment_gateway_html()
    {
        $data = self::get_payment_gateway_data();

        if (empty($data)) {
            return '';
        }

        $mepr_db           = MeprDb::fetch();
        $transaction_count = (int) $mepr_db->get_count($mepr_db->transactions, ['gateway' => $data['id']]);

        ob_start();
        ?>
    <div class="mepr-wizard-payment-gateway mepr-wizard-payment-gateway-<?php echo esc_attr($data['key']); ?>" data-gateway-id="<?php echo esc_attr($data['id']); ?>">
      <div>
        <div class="mepr-wizard-payment-gateway-logo">
          <img src="<?php echo esc_url($data['logo_url']); ?>" alt="">
        </div>
      </div>
      <div>
        <?php if ($data['connected']) : ?>
          <div class="mepr-wizard-payment-gateway-status">
            <?php
            if (!empty($data['account'])) {
                printf(
                    // Translators: %s: account name.
                    esc_html__('Connected to: %s', 'memberpress'),
                    '<span>' . esc_html($data['account']) . '</span>'
                );
            } else {
                esc_html_e('Connected', 'memberpress');
            }
            ?>
          </div>
        <?php endif; ?>
          <?php if ($data['id'] === 'MeprAuthorizeGateway') : ?>
          <div class="mepr-wizard-payment-gateway-status">
                <?php esc_html_e('Pro feature', 'memberpress'); ?>
          </div>
          <?php endif; ?>
          <?php if ($transaction_count === 0) : ?>
          <div id="mepr-wizard-payment-gateway-expand-menu">
            <img src="<?php echo esc_url(MEPR_IMAGES_URL . '/onboarding/expand-menu.svg'); ?>" alt="">
          </div>
          <div id="mepr-wizard-payment-gateway-menu" class="mepr-hidden">
            <div id="mepr-wizard-payment-gateway-delete"><?php esc_html_e('Remove', 'memberpress'); ?></div>
          </div>
          <?php endif; ?>
      </div>
    </div>
        <?php

        return ob_get_clean();
    }

    /**
     * Prepare product data for the onboarding process.
     *
     * @param object $product The product to prepare data for.
     *
     * @return array The prepared product data.
     */
    public static function prepare_product_data($product)
    {
        $billing_types = [
            'lifetime' => esc_html__('One-time', 'memberpress'),
            'months'   => esc_html__('Recurring (Monthly)', 'memberpress'),
            'years'    => esc_html__('Recurring (Anually)', 'memberpress'),
        ];

        return [
            'title'        => $product->post_title,
            'billing'      => $billing_types[$product->period_type],
            'price_string' => MeprAppHelper::format_price_string($product, $product->price),
        ];
    }

    /**
     * Get the rules step data for the onboarding process.
     *
     * @return array The rules step data.
     */
    public static function get_rules_step_data()
    {

        $membership_id = self::get_membership_post_id();
        $content_id    = self::get_content_post_id();

        $content    = get_post($content_id);
        $membership = get_post($membership_id);

        $data = [
            'content_title'    => '',
            'content_id'       => '',
            'membership_title' => '',
            'membership_id'    => '',
            'mepr_type'        => '',
            'content_type'     => '',
        ];

        if (! $content && ! $membership) {
            return $data;
        }

        if ($content) {
            $data['content_title'] = $content->post_title;
            $data['content_id']    = $content_id;
            $data['mepr_type']     = $content->post_type === 'mpcs-course' ? 'single_mpcs-course' : 'single_page';
            $data['content_type']  = $content->post_type === 'mpcs-course' ? esc_html__('Course', 'memberpress') : esc_html__('Page', 'memberpress');
        }

        if ($membership) {
            $data['membership_title'] = $membership->post_title;
            $data['membership_id']    = $membership_id;
        }

        return $data;
    }

    /**
     * Set the rule post ID for the onboarding process.
     *
     * @param integer $id The rule post ID to set.
     *
     * @return void
     */
    public static function set_rule_post_id($id)
    {
        update_option('mepr_onboarding_rule_post_id', $id, false);
    }

    /**
     * Get the rule post ID for the onboarding process.
     *
     * @return integer The rule post ID.
     */
    public static function get_rule_post_id()
    {
        return get_option('mepr_onboarding_rule_post_id', 0);
    }

    /**
     * Get the list of features for the onboarding process.
     *
     * @return array The list of features.
     */
    public static function features_list()
    {
        return [
            'memberpress-courses'         => esc_html__('Course Creator', 'memberpress'),
            'memberpress-downloads'       => esc_html__('Digital Downloads', 'memberpress'),
            'memberpress-buddypress'      => esc_html__('Member Community', 'memberpress'),
            'memberpress-developer-tools' => esc_html__('Zapier Integration', 'memberpress'),
            'memberpress-gifting'         => esc_html__('Gifting', 'memberpress'),
            'memberpress-corporate'       => esc_html__('Corporate Accounts', 'memberpress'),
            'easy-affiliate'             => esc_html__('Affiliate Program', 'memberpress'),
            'memberpress-coachkit'        => esc_html__('CoachKit™', 'memberpress'),
            'memberpress-circles'         => esc_html__('ClubCircles™', 'memberpress'),
            'memberpress-directory'       => esc_html__('ClubDirectory™', 'memberpress'),
        ];
    }

    /**
     * Check if the license is a developer license.
     *
     * @return boolean True if the license is a developer license, false otherwise.
     */
    public static function is_developer_license()
    {
        $li = get_site_transient('mepr_license_info');
        if ($li) {
            if (in_array($li['product_slug'], ['developer'], true)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Check if the license is a pro license.
     *
     * @return boolean True if the license is a pro license, false otherwise.
     */
    public static function is_pro_license()
    {
        $li     = get_site_transient('mepr_license_info');
        $is_pro = false;

        if ($li) {
            $is_pro = self::is_pro_edition($li['product_slug']);
        }

        return $is_pro;
    }

    /**
     * Is the given product slug a Pro edition of MemberPress?
     *
     * @param  string $product_slug The product slug.
     * @return boolean
     */
    public static function is_pro_edition($product_slug)
    {
        if (empty($product_slug)) {
            return false;
        }

        return in_array($product_slug, ['memberpress-pro', 'memberpress-pro-5'], true) || self::is_oem_edition($product_slug);
    }

    /**
     * Is the given product slug an OEM/reseller edition of MemberPress?
     *
     * @param  string $product_slug The product slug.
     * @return boolean
     */
    public static function is_oem_edition($product_slug)
    {
        if (empty($product_slug)) {
            return false;
        }

        return in_array($product_slug, ['memberpress-oem', 'memberpress-reseller-nhw', 'memberpress-reseller-sng'], true);
    }

    /**
     * Is the given product slug an Elite edition of MemberPress?
     *
     * @param  string $product_slug The product slug.
     * @return boolean
     */
    public static function is_elite_edition($product_slug)
    {
        if (empty($product_slug)) {
            return false;
        }

        return 'memberpress-elite' === $product_slug;
    }

    /**
     * Is the given product slug a Scale edition of MemberPress?
     *
     * @param  string $product_slug The product slug.
     * @return boolean
     */
    public static function is_scale_edition($product_slug)
    {
        return 'memberpress-scale' === $product_slug;
    }

    /**
     * Check if the license is a Scale license.
     *
     * @return boolean True if the license is a Scale license, false otherwise.
     */
    public static function is_scale_license()
    {
        $li = get_site_transient('mepr_license_info');
        if ($li) {
            return self::is_scale_edition($li['product_slug']);
        }

        return false;
    }

    /**
     * Is the given product slug a Growth edition of MemberPress?
     *
     * @param  string $product_slug The product slug.
     * @return boolean
     */
    public static function is_growth_edition($product_slug)
    {
        return 'memberpress-growth' === $product_slug;
    }

    /**
     * Get the license type for the onboarding process.
     *
     * @return string|false The license type or false if not set.
     */
    public static function get_license_type()
    {
        $li = get_site_transient('mepr_license_info');
        if ($li) {
            if (self::is_elite_edition($li['product_slug'])) {
                return 'memberpress-elite';
            }

            if (self::is_pro_edition($li['product_slug'])) {
                return 'memberpress-pro-5';
            }

            if (in_array($li['product_slug'], ['memberpress-plus','memberpress-plus-2'], true)) {
                return 'memberpress-plus';
            }

            return $li['product_slug'];
        }

        return false;
    }

    /**
     * Get the completed step URLs HTML for the onboarding process.
     *
     * @return string The completed step URLs HTML.
     */
    public static function get_completed_step_urls_html()
    {
        ob_start();
        ?>
        <?php
        $membership_post_id = MeprOnboardingHelper::get_membership_post_id();
        $mepr_options       = MeprOptions::fetch();

        // Auto genrate required page.
        if (!is_numeric($mepr_options->login_page_id) || $mepr_options->login_page_id === 0) {
            $mepr_options->login_page_id = MeprAppHelper::auto_add_page(__('Login', 'memberpress'));
        }

        if (!is_numeric($mepr_options->thankyou_page_id) || $mepr_options->thankyou_page_id === 0) {
            $mepr_options->thankyou_page_id = MeprAppHelper::auto_add_page(__('Thank You', 'memberpress'), esc_html__('Your subscription has been set up successfully.', 'memberpress'));
        }

        if (!is_numeric($mepr_options->account_page_id) || $mepr_options->account_page_id === 0) {
            $mepr_options->account_page_id = MeprAppHelper::auto_add_page(__('Account', 'memberpress'));
        }

        ?>
      <div class="mepr-wizard-selected-content-column">
        <div class="mepr-wizard-notification-warning">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
            <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
          </svg>
          MemberPress ReadyLaunch™ is currently enabled. It controls page styling and allows you to create beautiful pages effortlessly. If you'd rather use your own theme, just go to MemberPress > Settings > ReadyLaunch™, and disable the templates there.</div>
      </div>
      <hr>
        <?php

        if ($membership_post_id > 0) :
            $membership_url = get_the_permalink($membership_post_id);
            ?>
      <div class="mepr-wizard-selected-content-column">
        <div class="mepr-wizard-selected-content-heading"><?php esc_html_e('Membership registration', 'memberpress'); ?></div>
        <div class="mepr-wizard-selected-content-name"><a href="<?php echo esc_url($membership_url); ?>"><?php echo esc_html($membership_url); ?></a></div>
      </div>
      <hr>
        <?php endif; ?>

        <?php if ($mepr_options->login_page_id > 0) :
            $login_page_url = get_the_permalink($mepr_options->login_page_id);
            ?>
      <div class="mepr-wizard-selected-content-column">
        <div class="mepr-wizard-selected-content-heading"><?php esc_html_e('MemberPress login', 'memberpress'); ?></div>
        <div class="mepr-wizard-selected-content-name"><a href="<?php echo esc_url($login_page_url); ?>"><?php echo esc_html($login_page_url); ?></a></div>
      </div>
      <hr>
        <?php endif; ?>

        <?php if ($mepr_options->account_page_id > 0) :
            $account_page_url = get_the_permalink($mepr_options->account_page_id);
            ?>
      <div class="mepr-wizard-selected-content-column">
        <div class="mepr-wizard-selected-content-heading"><?php esc_html_e('Manage account', 'memberpress'); ?></div>
        <div class="mepr-wizard-selected-content-name"><a href="<?php echo esc_url($account_page_url); ?>"><?php echo esc_html($account_page_url); ?></a></div>
      </div>
        <?php endif; ?>
        <?php
        return ob_get_clean();
    }

    /**
     * Check if an upgrade is required based on the provided attributes.
     *
     * @param array $atts The attributes to check for upgrade requirements.
     *
     * @return string|false The required upgrade type or false if no upgrade is required.
     */
    public static function is_upgrade_required($atts)
    {

        $addons_installed     = isset($atts['addons_installed']) ? $atts['addons_installed'] : [];
        $addons_not_installed = isset($atts['addons_not_installed']) ? $atts['addons_not_installed'] : [];
        $payment_gateway      = isset($atts['payment_gateway']) ? $atts['payment_gateway'] : '';
        $license_type         = self::get_license_type();

        if (!is_array($addons_installed)) {
            $addons_installed = [];
        }

        if (!is_array($addons_not_installed)) {
            $addons_not_installed = [];
        }

        // Check if license type is not pro or developer and Auth.net payment gateway selected.
        if (
            !(
                self::is_pro_edition($license_type)
                || self::is_scale_edition($license_type)
                || $license_type === 'developer'
            )
            && $payment_gateway === 'MeprAuthorizeGateway'
        ) {
            return 'memberpress-scale'; // Upgrade to Scale required (new plan).
        }

        // If there are no addons required installation bail out.
        if (empty($addons_not_installed)) {
            return false;
        }

        foreach ($addons_not_installed as $k => $addon_slug) {
            if (in_array($addon_slug, $addons_installed, true)) {
                unset($addons_not_installed[$k]); // Already installed.
            }
        }

        // No more addons instalation required? Bailout.
        if (empty($addons_not_installed)) {
            return false;
        }

        if (in_array($license_type, ['developer','memberpress-plus','memberpress-plus-2','memberpress-growth'], true)) {
            return 'memberpress-scale'; // Upgrade to Scale required (new plan).
        }

        $pro_addons   = self::get_edition_addons('memberpress-pro-5');
        $plus_addons  = self::get_edition_addons('memberpress-plus-2');
        $elite_addons = self::get_edition_addons('memberpress-elite');
        $scale_addons = self::get_edition_addons('memberpress-scale');
        $growth_addons = self::get_edition_addons('memberpress-growth');

        // Time to check what kind of plan we should offer based on features selection.
        $pro_count   = 0;
        $plus_count  = 0;
        $elite_count = 0;
        $scale_count = 0;
        $growth_count = 0;
        foreach ($addons_not_installed as $addon_slug) {
            if (in_array($addon_slug, $pro_addons, true)) {
                $pro_count++;
            }

            if (in_array($addon_slug, $plus_addons, true)) {
                $plus_count++;
            }

            if (in_array($addon_slug, $elite_addons, true)) {
                $elite_count++;
            }

            if (in_array($addon_slug, $scale_addons, true)) {
                $scale_count++;
            }

            if (in_array($addon_slug, $growth_addons, true)) {
                $growth_count++;
            }
        }

        if (
            $elite_count > $scale_count
            && $elite_count > $pro_count
        ) {
            return 'memberpress-elite'; // Upgrade to Elite required (legacy, kept for OEM/reseller).
        } elseif (
            $scale_count > $growth_count
            && $scale_count > $pro_count
            && $scale_count > $plus_count
        ) {
            return 'memberpress-scale'; // Upgrade to Scale required (new plan).
        } elseif ($pro_count > $plus_count) {
            return 'memberpress-scale'; // Upgrade to Scale required (new plan, replaces Pro).
        } elseif ($growth_count > $plus_count) {
            return 'memberpress-growth'; // Upgrade to Growth required (new plan).
        } else {
            return 'memberpress-growth'; // Upgrade to Growth required (new plan, replaces Plus).
        }
    }

    /**
     * Returns the addons for a specific edition.
     *
     * @param string $edition The edition to get addons for.
     *
     * @return array The list of addons for the specified edition.
     */
    public static function get_edition_addons(string $edition): array
    {
        $editions = MeprUtils::get_editions();
        return $editions[$edition]['addons'] ?? [];
    }

    /**
     * Get the upgrade CTA data for a specific type.
     *
     * @param string $type The type of upgrade to get data for.
     *
     * @return array The upgrade CTA data.
     */
    public static function get_upgrade_cta_data($type)
    {
        $data = [
            'memberpress-scale' => [
                'token'   => esc_html__('Scale', 'memberpress'),
                'url'     => MeprUtils::get_link_url('onboarding_upgrade_scale'),
                'label'   => esc_html__('Upgrade to Scale', 'memberpress'),
                'heading' => esc_html__('To unlock selected features, upgrade to Scale.', 'memberpress'),
            ],

            'memberpress-growth' => [
                'token'   => esc_html__('Growth', 'memberpress'),
                'url'     => MeprUtils::get_link_url('onboarding_upgrade_growth'),
                'label'   => esc_html__('Upgrade to Growth', 'memberpress'),
                'heading' => esc_html__('To unlock selected features, upgrade to Growth.', 'memberpress'),
            ],

            /*
             * Elite tier configuration is currently disabled.
             * Will be enabled in a future release.
             *
                'memberpress-elite' => array(
                    'token' => esc_html__('Elite','memberpress'),
                    'url' => MeprUtils::get_link_url('onboarding_upgrade_elite'),
                    'label' => esc_html__('Upgrade to Elite','memberpress'),
                    'heading' => esc_html__('To unlock selected features, upgrade to Elite.', 'memberpress')
                )
             */
        ];

        $data = MeprHooks::apply_filters('mepr_onboarding_cta_data', $data);

        $cta_data = [];
        if (isset($data[$type])) {
            $cta_data = $data[$type];
        }

        return $cta_data;
    }
}
