<?php

namespace SoftminalB2B\Support;

if (!defined('ABSPATH')) {
    exit;
}

use SoftminalB2B\Models\Group;

/**
 * What the installed tier allows. Core ships the Free limits and the Pro
 * add-on raises them through filters — core never checks a licence itself.
 */
class Tier
{
    /**
     * Customer groups are unlimited in Free. 0 means "no cap" (see
     * canCreateGroup / maxGroups). Group management is a core feature and its
     * engine runs entirely in Free, so it is never limited — Pro sells company
     * accounts and the rest of the B2B suite, not "more groups".
     */
    public const FREE_MAX_GROUPS = 0;

    public static function isPro(): bool
    {
        return (bool) apply_filters('smb2b_is_pro', false);
    }

    public static function maxGroups(): int
    {
        return (int) apply_filters('smb2b_max_groups', self::FREE_MAX_GROUPS);
    }

    public static function canCreateGroup(): bool
    {
        $max = self::maxGroups();

        if ($max <= 0) {
            return true;
        }

        return count(Group::all()) < $max;
    }

    /**
     * A group-limit notice, only meaningful when a cap is actually in force.
     * Free has no cap (maxGroups() === 0), so this returns an empty string and
     * the UI shows nothing.
     */
    public static function groupLimitMessage(): string
    {
        $max = self::maxGroups();

        if ($max <= 0) {
            return '';
        }

        return sprintf(
            /* translators: %d: number of groups included */
            _n(
                'The free version includes %d customer group. Upgrade to Pro to add more.',
                'The free version includes %d customer groups. Upgrade to Pro to add more.',
                $max,
                'softminal-b2b-wholesale-for-woocommerce'
            ),
            $max
        );
    }

    /**
     * @return array<string, mixed>
     */
    public static function toArray(): array
    {
        return [
            'is_pro'            => self::isPro(),
            'max_groups'        => self::maxGroups(),
            'can_create_group'  => self::canCreateGroup(),
            'group_limit_message' => self::groupLimitMessage(),
        ];
    }
}
