# Feature Access Control Implementation Guide

## Overview
This guide shows how to apply subscription-based feature access control across your application using the middleware and helper methods we've created.

---

## 1. Route-Level Protection

### Protect Entire Feature Sections

Add middleware to route groups in `routes/web.php`:

```php
// Example 1: Protect Ads Manager (Business+ plans only)
Route::prefix('brand')->middleware(['auth', 'role:brand_admin', 'subscription', 'feature:has_ads_manager'])->group(function () {
    Route::prefix('ads')->group(function () {
        Route::get('/', [AdManagerController::class, 'index'])->name('brand.ads.index');
        Route::get('/create', [AdManagerController::class, 'create'])->name('brand.ads.create');
        // ... rest of ads routes
    });
});

// Example 2: Protect Competitor Insights (Business+ plans only)
Route::prefix('brand')->middleware(['auth', 'role:brand_admin', 'subscription', 'feature:has_competitor_insights'])->group(function () {
    Route::prefix('competitor-insights')->group(function () {
        Route::get('/', [CompetitorInsightsController::class, 'index'])->name('brand.competitor-insights.index');
        // ... rest of competitor routes
    });
});

// Example 3: Protect Localization (Business+ plans only)
Route::prefix('brand')->middleware(['auth', 'role:brand_admin', 'subscription', 'feature:has_localization'])->group(function () {
    Route::prefix('localization')->group(function () {
        Route::get('/', [LocalizationController::class, 'index'])->name('brand.localization.index');
        // ... rest of localization routes
    });
});

// Example 4: Protect Analytics (Pro+ plans)
Route::prefix('brand')->middleware(['auth', 'role:brand_admin', 'subscription', 'feature:has_analytics'])->group(function () {
    Route::get('/analytics', [AnalyticsController::class, 'index'])->name('brand.analytics.index');
    Route::get('/forecasts', [PerformanceForecastController::class, 'index'])->name('brand.forecasts.index');
});
```

---

## 2. Controller-Level Checks

### Check Usage Limits Before Creating Resources

#### Example: Content Ideas Controller

```php
// In app/Http/Controllers/Brand/ContentIdeaController.php

public function store(Request $request)
{
    $user = auth()->user();
    
    // Check if user can create more content ideas
    if (!$user->subscription->canUseFeature('max_content_ideas_per_month')) {
        return redirect()->back()->with('error', 'You have reached your monthly content ideas limit. Please upgrade your plan.');
    }
    
    // Validate and create content idea
    $validated = $request->validate([...]);
    $contentIdea = ContentIdea::create($validated);
    
    // Increment usage counter
    $user->subscription->incrementUsage('max_content_ideas_per_month');
    
    return redirect()->route('brand.content-ideas.index')
        ->with('success', 'Content idea created successfully.');
}
```

#### Example: Campaign Controller

```php
// In app/Http/Controllers/Brand/CampaignController.php

public function store(Request $request)
{
    $user = auth()->user();
    $subscription = $user->subscription;
    
    // Check campaign limit
    $currentCampaigns = $subscription->getCurrentUsage('max_campaigns');
    $plan = $subscription->planModel;
    
    if (!$plan->canUseFeature('max_campaigns', $currentCampaigns)) {
        return redirect()->back()->with('error', 
            'You have reached your campaign limit (' . $plan->max_campaigns . '). Please upgrade to create more campaigns.');
    }
    
    // Create campaign
    $campaign = Campaign::create($request->validated());
    
    // Increment usage
    $subscription->incrementUsage('max_campaigns');
    
    return redirect()->route('brand.campaigns.show', $campaign);
}
```

#### Example: Reels Controller

```php
// In app/Http/Controllers/Brand/ReelController.php

public function store(Request $request)
{
    $user = auth()->user();
    
    // Check reel limit
    if (!$user->subscription->canUseFeature('max_reels_per_month')) {
        $plan = $user->subscription->planModel;
        $limit = $plan->max_reels_per_month;
        
        return redirect()->back()->with('error', 
            "You have reached your monthly reel limit ({$limit}). Upgrade to create more reels.");
    }
    
    // Create reel
    $reel = ReelRequest::create($request->validated());
    
    // Increment usage
    $user->subscription->incrementUsage('max_reels_per_month');
    
    return redirect()->route('brand.reels.show', $reel);
}
```

#### Example: Social Accounts

```php
// In app/Http/Controllers/Brand/SocialController.php

public function manualStore(Request $request)
{
    $user = auth()->user();
    $plan = $user->currentPlan();
    
    // Check social account limit
    $currentAccounts = $user->socialAccounts()->count();
    
    if ($plan->max_social_accounts !== -1 && $currentAccounts >= $plan->max_social_accounts) {
        return redirect()->back()->with('error', 
            "You have reached your social account limit ({$plan->max_social_accounts}). Please upgrade your plan.");
    }
    
    // Create social account
    $account = SocialAccount::create($request->validated());
    
    return redirect()->route('brand.connections.index');
}
```

---

## 3. View-Level Checks

### Hide/Show Features Based on Plan

#### In Blade Templates

```blade
{{-- Check if user has feature access --}}
@if(auth()->user()->currentPlan()?->has_ads_manager)
    <a href="{{ route('brand.ads.index') }}" class="nav-link">
        <i class="fas fa-ad"></i> Ads Manager
    </a>
@else
    <div class="nav-link text-muted" title="Upgrade to access Ads Manager">
        <i class="fas fa-lock"></i> Ads Manager
        <span class="badge bg-warning">Pro+</span>
    </div>
@endif

{{-- Check usage limits --}}
@php
    $subscription = auth()->user()->subscription;
    $limits = $subscription ? $subscription->getPlanLimits() : [];
@endphp

@if(isset($limits['content_ideas']))
    <div class="usage-indicator">
        <span>Content Ideas: {{ $limits['content_ideas']['used'] }} / 
            {{ $limits['content_ideas']['unlimited'] ? '∞' : $limits['content_ideas']['limit'] }}
        </span>
        
        @if(!$limits['content_ideas']['unlimited'] && $limits['content_ideas']['used'] >= $limits['content_ideas']['limit'])
            <a href="{{ route('subscription.plans') }}" class="btn btn-sm btn-warning">
                Upgrade
            </a>
        @endif
    </div>
@endif

{{-- Disable button if limit reached --}}
<button type="submit" 
        class="btn btn-primary"
        @if(!auth()->user()->subscription->canUseFeature('max_campaigns'))
            disabled
            title="Campaign limit reached. Upgrade your plan."
        @endif>
    Create Campaign
</button>
```

---

## 4. Specific Routes to Protect

### Apply These Changes to `routes/web.php`

```php
// Brand Routes - Apply feature middleware
Route::prefix('brand')->middleware(['auth', 'role:brand_admin', 'IdentifyTenant'])->group(function () {
    
    // Basic routes (all plans)
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('brand.dashboard');
    Route::get('/connections', [SocialController::class, 'index'])->name('brand.connections.index');
    
    // Ads Manager (Pro+ plans) - ADD MIDDLEWARE
    Route::middleware(['subscription', 'feature:has_ads_manager'])->prefix('ads')->group(function () {
        Route::get('/', [AdManagerController::class, 'index'])->name('brand.ads.index');
        Route::get('/create', [AdManagerController::class, 'create'])->name('brand.ads.create');
        Route::post('/', [AdManagerController::class, 'store'])->name('brand.ads.store');
        // ... rest of ads routes
    });
    
    // Analytics (Pro+ plans) - ADD MIDDLEWARE
    Route::middleware(['subscription', 'feature:has_analytics'])->group(function () {
        Route::get('/analytics', [AnalyticsController::class, 'index'])->name('brand.analytics.index');
        Route::get('/forecasts', [PerformanceForecastController::class, 'index'])->name('brand.forecasts.index');
    });
    
    // Competitor Insights (Business+ plans) - ADD MIDDLEWARE
    Route::middleware(['subscription', 'feature:has_competitor_insights'])->prefix('competitor-insights')->group(function () {
        Route::get('/', [CompetitorInsightsController::class, 'index'])->name('brand.competitor-insights.index');
        // ... rest of competitor routes
    });
    
    // Localization (Business+ plans) - ADD MIDDLEWARE
    Route::middleware(['subscription', 'feature:has_localization'])->prefix('localization')->group(function () {
        Route::get('/', [LocalizationController::class, 'index'])->name('brand.localization.index');
        // ... rest of localization routes
    });
    
    // Messaging (Pro+ plans) - ADD MIDDLEWARE
    Route::middleware(['subscription', 'feature:has_messaging'])->group(function () {
        Route::get('/messages', [MessageController::class, 'index'])->name('brand.messages.index');
        // ... rest of messaging routes
    });
    
    // Support Bot (Business+ plans) - ADD MIDDLEWARE
    Route::middleware(['subscription', 'feature:has_messaging'])->prefix('support')->group(function () {
        Route::get('/dashboard', [SupportDashboardController::class, 'index'])->name('brand.support.dashboard');
        // ... rest of support routes
    });
});
```

---

## 5. Usage Tracking Integration

### Add to Existing Controllers

#### Content Ideas
File: `app/Http/Controllers/Brand/ContentIdeaController.php`
```php
public function store(Request $request)
{
    // Add before creating
    if (!auth()->user()->subscription->canUseFeature('max_content_ideas_per_month')) {
        return redirect()->back()->with('error', 'Monthly limit reached');
    }
    
    // ... create content idea ...
    
    // Add after creating
    auth()->user()->subscription->incrementUsage('max_content_ideas_per_month');
}
```

#### Campaigns
File: `app/Http/Controllers/Brand/CampaignController.php`
```php
public function store(Request $request)
{
    // Check limit
    if (!auth()->user()->subscription->canUseFeature('max_campaigns')) {
        return redirect()->back()->with('error', 'Campaign limit reached');
    }
    
    // ... create campaign ...
    
    // Increment usage
    auth()->user()->subscription->incrementUsage('max_campaigns');
}
```

#### Proposals
File: `app/Http/Controllers/Brand/ProposalController.php`
```php
public function store(Request $request)
{
    // Check limit
    if (!auth()->user()->subscription->canUseFeature('max_proposals')) {
        return redirect()->back()->with('error', 'Monthly proposal limit reached');
    }
    
    // ... create proposal ...
    
    // Increment usage
    auth()->user()->subscription->incrementUsage('max_proposals');
}
```

#### Reels
File: `app/Http/Controllers/Brand/ReelController.php`
```php
public function store(Request $request)
{
    // Check limit
    if (!auth()->user()->subscription->canUseFeature('max_reels_per_month')) {
        return redirect()->back()->with('error', 'Monthly reel limit reached');
    }
    
    // ... create reel ...
    
    // Increment usage
    auth()->user()->subscription->incrementUsage('max_reels_per_month');
}
```

---

## 6. Sidebar Conditional Display

### Update Sidebar Navigation

```blade
{{-- In brand-sidebar.blade.php --}}

{{-- Only show if plan has feature --}}
@if(auth()->user()->currentPlan()?->has_ads_manager)
    <a href="{{ route('brand.ads.index') }}">
        <i class="fas fa-ad"></i> Ads Manager
    </a>
@endif

@if(auth()->user()->currentPlan()?->has_competitor_insights)
    <a href="{{ route('brand.competitor-insights.index') }}">
        <i class="fas fa-chart-line"></i> Competitor Insights
    </a>
@endif

@if(auth()->user()->currentPlan()?->has_localization)
    <a href="{{ route('brand.localization.index') }}">
        <i class="fas fa-globe"></i> Localization
    </a>
@endif

{{-- Show with upgrade prompt if not available --}}
@if(!auth()->user()->currentPlan()?->has_ads_manager)
    <div class="nav-item-locked" title="Upgrade to Pro to access">
        <i class="fas fa-lock"></i> Ads Manager
        <span class="badge badge-warning">Pro</span>
    </div>
@endif
```

---

## 7. Dashboard Widgets

### Show Usage Statistics

```blade
{{-- In dashboard.blade.php --}}

@php
    $subscription = auth()->user()->subscription;
    $limits = $subscription ? $subscription->getPlanLimits() : [];
@endphp

<div class="row">
    @foreach($limits as $featureName => $limit)
        <div class="col-md-4 mb-3">
            <div class="card">
                <div class="card-body">
                    <h6>{{ ucwords(str_replace('_', ' ', $featureName)) }}</h6>
                    <div class="progress">
                        <div class="progress-bar" 
                             style="width: {{ $limit['unlimited'] ? 100 : min(100, ($limit['used'] / max(1, $limit['limit'])) * 100) }}%">
                        </div>
                    </div>
                    <small class="text-muted">
                        {{ $limit['used'] }} / {{ $limit['unlimited'] ? '∞' : $limit['limit'] }}
                    </small>
                    
                    @if(!$limit['unlimited'] && $limit['used'] >= $limit['limit'])
                        <a href="{{ route('subscription.plans') }}" class="btn btn-sm btn-warning mt-2">
                            Upgrade
                        </a>
                    @endif
                </div>
            </div>
        </div>
    @endforeach
</div>
```

---

## 8. Quick Implementation Checklist

### Step 1: Update Routes (HIGH PRIORITY)
- [ ] Wrap Ads Manager routes with `feature:has_ads_manager`
- [ ] Wrap Analytics routes with `feature:has_analytics`
- [ ] Wrap Competitor Insights routes with `feature:has_competitor_insights`
- [ ] Wrap Localization routes with `feature:has_localization`
- [ ] Wrap Messaging routes with `feature:has_messaging`
- [ ] Wrap Support Bot routes with `feature:has_messaging`

### Step 2: Add Usage Tracking (HIGH PRIORITY)
- [ ] Content Ideas: Check and increment `max_content_ideas_per_month`
- [ ] Campaigns: Check and increment `max_campaigns`
- [ ] Proposals: Check and increment `max_proposals`
- [ ] Reels: Check and increment `max_reels_per_month`
- [ ] Social Accounts: Check `max_social_accounts` limit

### Step 3: Update Sidebars (MEDIUM PRIORITY)
- [ ] Brand sidebar: Show/hide features based on plan
- [ ] Creator sidebar: Show/hide features based on plan
- [ ] Agency sidebar: Show/hide features based on plan
- [ ] Add upgrade prompts for locked features

### Step 4: Update Dashboards (MEDIUM PRIORITY)
- [ ] Show usage statistics widget
- [ ] Show plan information
- [ ] Add upgrade prompts when limits reached

---

## 9. Helper Methods Available

### In Controllers
```php
// Check if user has active subscription
if (!auth()->user()->hasActiveSubscription()) {
    return redirect()->route('subscription.plans');
}

// Check if user can use a feature
if (!auth()->user()->canUseFeature('max_campaigns')) {
    return redirect()->back()->with('error', 'Limit reached');
}

// Get current plan
$plan = auth()->user()->currentPlan();

// Get subscription
$subscription = auth()->user()->subscription;

// Check specific feature access
if ($subscription->canUseFeature('max_content_ideas_per_month')) {
    // User can create more content ideas
}

// Increment usage
$subscription->incrementUsage('max_campaigns');

// Get current usage
$usage = $subscription->getCurrentUsage('max_campaigns');

// Get all limits
$limits = $subscription->getPlanLimits();
```

### In Blade Views
```blade
{{-- Check if user has subscription --}}
@if(auth()->user()->hasActiveSubscription())
    {{-- Show content --}}
@endif

{{-- Check specific feature --}}
@if(auth()->user()->currentPlan()?->has_ads_manager)
    {{-- Show ads manager link --}}
@endif

{{-- Get plan name --}}
{{ auth()->user()->currentPlan()?->name }}

{{-- Check if on trial --}}
@if(auth()->user()->subscription?->onTrial())
    <span class="badge badge-info">Trial: {{ auth()->user()->subscription->trialDaysRemaining() }} days left</span>
@endif
```

---

## 10. Testing Checklist

### Manual Testing
- [ ] Create account and subscribe to Starter plan
- [ ] Verify only Starter features are accessible
- [ ] Try to access Pro features (should be blocked)
- [ ] Upgrade to Pro plan
- [ ] Verify Pro features are now accessible
- [ ] Test usage limits (create items until limit reached)
- [ ] Verify limit enforcement
- [ ] Test upgrade/downgrade flows
- [ ] Test cancellation
- [ ] Test invoice generation

### Automated Testing
Create tests in `tests/Feature/SubscriptionFeatureAccessTest.php`:
```php
public function test_starter_plan_cannot_access_ads_manager()
{
    $user = User::factory()->create();
    $starterPlan = Plan::where('slug', 'starter')->first();
    
    Subscription::create([
        'user_id' => $user->id,
        'plan_id' => $starterPlan->id,
        'status' => 'active',
        // ...
    ]);
    
    $response = $this->actingAs($user)->get(route('brand.ads.index'));
    $response->assertRedirect();
    $response->assertSessionHas('error');
}
```

---

## 11. Example: Complete Feature Protection

### Ads Manager (Complete Example)

#### 1. Route Protection
```php
// routes/web.php
Route::middleware(['subscription', 'feature:has_ads_manager'])->prefix('ads')->group(function () {
    Route::get('/', [AdManagerController::class, 'index'])->name('brand.ads.index');
    Route::post('/', [AdManagerController::class, 'store'])->name('brand.ads.store');
});
```

#### 2. Controller Check
```php
// AdManagerController.php
public function store(Request $request)
{
    $user = auth()->user();
    $plan = $user->currentPlan();
    
    // Check ad variant limit
    $currentVariants = $request->variants_count ?? 2;
    if ($plan->max_ad_variants !== -1 && $currentVariants > $plan->max_ad_variants) {
        return redirect()->back()->with('error', 
            "Your plan allows maximum {$plan->max_ad_variants} ad variants. Upgrade for more.");
    }
    
    // Create ad
    $ad = Ad::create($request->validated());
    
    return redirect()->route('brand.ads.show', $ad);
}
```

#### 3. Sidebar Display
```blade
@if(auth()->user()->currentPlan()?->has_ads_manager)
    <a href="{{ route('brand.ads.index') }}">Ads Manager</a>
@else
    <div class="locked-feature">
        <i class="fas fa-lock"></i> Ads Manager
        <span class="badge">Pro+</span>
    </div>
@endif
```

---

## 12. Summary

**Total Changes Needed:**
- ~10 route groups to wrap with middleware
- ~5-7 controllers to add usage tracking
- ~3 sidebars to update with conditional display
- ~3 dashboards to add usage widgets

**Estimated Time:** 2-3 hours

**Priority Order:**
1. Route protection (prevents unauthorized access)
2. Usage tracking (enforces limits)
3. Sidebar updates (improves UX)
4. Dashboard widgets (shows usage stats)