<?php

namespace App\Services;

use App\Models\SiteSetting;
use App\Models\User;

class FeatureAccessService
{
    public function allowed(User $user, string $feature): bool
    {
        if (! SiteSetting::paymentModeEnabled()) {
            return true;
        }

        if ($user->isAdmin() || SiteSetting::allowFreeAccess()) {
            return true;
        }

        if (
            $user->isWithinFreeTrial(SiteSetting::freeTrialDays())
            || $user->hasSubscriptionGracePeriod(SiteSetting::subscriptionGraceDays())
        ) {
            return true;
        }

        $subscription = $user->subscriptions()
            ->with('plan')
            ->active()
            ->latest('starts_at')
            ->first();

        if (! $subscription?->plan) {
            return false;
        }

        return $subscription->plan->allowsFeature($feature);
    }

    public function tradeLimitReached(User $user): bool
    {
        if (! SiteSetting::paymentModeEnabled()) {
            return false;
        }

        if ($user->isAdmin() || SiteSetting::allowFreeAccess()) {
            return false;
        }

        if (
            $user->isWithinFreeTrial(SiteSetting::freeTrialDays())
            || $user->hasSubscriptionGracePeriod(SiteSetting::subscriptionGraceDays())
        ) {
            return false;
        }

        $subscription = $user->subscriptions()
            ->with('plan')
            ->active()
            ->latest('starts_at')
            ->first();

        $maxTrades = $subscription?->plan?->max_trades;

        if ($maxTrades === null) {
            return false;
        }

        return $user->trades()->count() >= $maxTrades;
    }
}
