
# Agency Admin Sidebar Navigation

Complete documentation for the Agency Admin left sidebar navigation system.

## Overview

The Agency Admin sidebar is a comprehensive navigation system designed specifically for agency administrators who manage multiple brands, oversee campaigns, and coordinate between brands and creators. It provides quick access to all agency-level management features, multi-brand oversight, and reporting tools.

## Features

### ✅ Core Features
- **12 Navigation Items** in logical order (as specified)
- **Role-Based Access** - Only visible to `agency_admin` role
- **Collapsible/Expandable** sidebar with persistent state
- **Badge System** for real-time notifications
- **Quick Search** (Ctrl+K) for fast navigation
- **Mobile Responsive** with hamburger menu
- **Keyboard Navigation** support
- **Accessibility Compliant** (ARIA roles, focus states)
- **Tooltip Support** in collapsed mode

### 🎨 UI/UX Features
- Smooth animations and transitions
- Active menu item highlighting (purple accent color)
- Hover effects and visual feedback
- Gradient background design (purple to indigo)
- Icon-based navigation
- Submenu support (Settings)
- Quick actions on hover

## Installation

### 1. Files Created

```
resources/views/components/agency-sidebar.blade.php
resources/views/layouts/agency-admin.blade.php
app/Http/Controllers/Agency/SidebarController.php
docs/AGENCY_ADMIN_SIDEBAR.md
```

### 2. Routes Added

```php
// In routes/web.php - Agency panel routes
Route::prefix('agency')->middleware(['auth', 'role:agency'])->group(function () {
    // Sidebar API routes
    Route::get('/api/sidebar/badges', [SidebarController::class, 'getBadges'])
        ->name('agency.sidebar.badges');
    Route::get('/api/sidebar/search', [SidebarController::class, 'quickSearch'])
        ->name('agency.sidebar.search');
    Route::get('/api/sidebar/kpis', [SidebarController::class, 'getDashboardKPIs'])
        ->name('agency.sidebar.kpis');
    Route::get('/api/sidebar/activity', [SidebarController::class, 'getRecentActivity'])
        ->name('agency.sidebar.activity');
    
    // ... other agency routes
});
```

## Usage

### Basic Usage

To use the sidebar in your agency admin pages, use the `agency-admin` layout:

```blade
<x-agency-admin-layout>
    <x-slot name="header">
        Dashboard
    </x-slot>

    <x-slot name="breadcrumbs">
        <li><a href="{{ route('agency.dashboard') }}">Home</a></li>
        <li>Dashboard</li>
    </x-slot>

    <!-- Your page content here -->
    <div class="container">
        <h1>Welcome to Agency Dashboard</h1>
    </div>
</x-agency-admin-layout>
```

### Direct Component Usage

If you need more control, use the component directly:

```blade
<x-agency-sidebar />

<div class="main-content" style="margin-left: 280px;">
    <!-- Your content -->
</div>
```

## Navigation Structure

### Main Navigation Items (in order)

1. **Dashboard** - KPI cards: total managed brands, active campaigns, proposals pending, revenue share
2. **Managed Brands** - List of all brands under agency with quick filters, status indicators (with badge)
3. **Campaigns** - Agency can create, assign creators, manage milestones, budget allocation (with badge)
4. **Proposals** - Oversee proposals between brands and creators, approve/reject workflows (with badge)
5. **Creators** - Access to marketplace directory, shortlist potential influencers, send invites
6. **Messaging** - Multi-thread chat with brands and creators, attach files (with badge)
7. **Analytics & Reports** - Campaign performance, creator engagement, ROI reports (export CSV/PDF)
8. **Billing** - Invoices, revenue sharing with brands, track payments
9. **Notifications** - Alerts for campaign updates, proposal approvals, payment reminders (with badge)
10. **Support** - Access to support bot, FAQs, escalate to Super Admin if needed
11. **Settings** (expandable submenu):
    - Agency Profile
    - Team Members
    - API Keys
12. **Account Menu** (bottom):
    - Profile
    - Audit Logs
    - Logout

## Badge System

### Real-Time Badges

The sidebar displays real-time notification badges for:

- **Total Brands** (purple badge) - Number of managed brands
- **Pending Proposals** (yellow badge) - Proposals awaiting approval
- **Active Campaigns** (green badge) - Currently running campaigns
- **Unread Messages** (red badge) - Unread messages from brands/creators
- **Notifications** (red badge) - System notifications

### Badge API

Badges are fetched from:
```
GET /agency/api/sidebar/badges
```

Response format:
```json
{
    "success": true,
    "badges": {
        "totalBrands": 15,
        "pendingProposals": 8,
        "activeCampaigns": 12,
        "unreadMessages": 23,
        "notifications": 5
    }
}
```

Badges auto-refresh every 30 seconds.

## Dashboard KPIs API

Get comprehensive dashboard metrics:
```
GET /agency/api/sidebar/kpis
```

Response format:
```json
{
    "success": true,
    "kpis": {
        "totalBrands": 15,
        "activeCampaigns": 12,
        "pendingProposals": 8,
        "revenueShare": "125000.00",
        "totalCreators": 45,
        "completedCampaigns": 28
    }
}
```

## Recent Activity API

Get recent activity feed:
```
GET /agency/api/sidebar/activity
```

Response format:
```json
{
    "success": true,
    "activities": [
        {
            "type": "campaign",
            "title": "New campaign: Summer Collection",
            "description": "Brand: Fashion Co",
            "timestamp": "2025-09-30 10:30:00",
            "url": "/agency/campaigns/123"
        }
    ]
}
```

## Quick Search

### Activation
- Press `Ctrl+K` (or `Cmd+K` on Mac)
- Click the "Quick Search" button in sidebar

### Features
- Searches navigation items
- Searches brands, campaigns, creators, proposals via API
- Real-time results as you type
- Keyboard navigable

### Search API

```
GET /agency/api/sidebar/search?query={searchTerm}
```

Response format:
```json
{
    "success": true,
    "results": [
        {
            "name": "Brand Name",
            "category": "Brand",
            "url": "/agency/brands/123",
            "meta": "Fashion Industry"
        },
        {
            "name": "Campaign Name",
            "category": "Campaign",
            "url": "/agency/campaigns/456",
            "meta": "Status: active"
        }
    ]
}
```

## Customization

### Changing Sidebar Width

Edit the component:
```javascript
// In agency-sidebar.blade.php
:style="{'width': sidebarCollapsed ? '80px' : '320px'}" // Change 320px
```

### Adding New Navigation Items

1. Add the HTML link in the navigation section:
```blade
<a href="{{ route('agency.new-feature') }}"
   @click="setActive('new-feature')"
   :class="isActive('new-feature') ? 'bg-purple-600 text-white' : 'text-purple-200 hover:bg-purple-800'"
   class="nav-item flex items-center space-x-3 px-3 py-2.5 rounded-lg transition-all duration-200 group"
   role="menuitem">
    <svg class="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <!-- Your icon SVG path -->
    </svg>
    <span x-show="!sidebarCollapsed" class="text-sm font-medium">New Feature</span>
</a>
```

2. Add to `allNavItems` array for search:
```javascript
allNavItems: [
    // ... existing items
    { name: 'New Feature', url: '{{ route("agency.new-feature") }}', category: 'Navigation' }
]
```

3. Add to `setActiveFromUrl()` method:
```javascript
else if (path.includes('/new-feature')) this.activeItem = 'new-feature';
```

### Adding Badges to New Items

```blade
<span x-show="!sidebarCollapsed && badges.newFeatureCount > 0"
      class="ml-auto bg-blue-500 text-white text-xs px-2 py-0.5 rounded-full"
      x-text="badges.newFeatureCount"></span>
```

Update the badge API to include the new count.

## Mobile Responsiveness

### Breakpoints
- **Desktop** (≥1024px): Full sidebar visible
- **Mobile** (<1024px): Hamburger menu with overlay

### Mobile Behavior
- Sidebar hidden by default
- Hamburger button in top-left
- Click overlay to close
- Full sidebar slides in from left

## Keyboard Navigation

### Shortcuts
- `Ctrl+K` / `Cmd+K` - Open quick search
- `Escape` - Close modals/search
- `Tab` - Navigate through items
- `Enter` - Activate focused item

### Focus Management
- Visible focus indicators
- Logical tab order
- Trapped focus in modals

## Accessibility

### ARIA Attributes
- `role="navigation"` on nav element
- `role="menuitem"` on nav links
- `aria-label` for icon-only buttons
- `aria-expanded` for expandable menus
- `aria-modal` for modals

### Screen Reader Support
- Descriptive labels
- Hidden text for icons
- Semantic HTML structure

### Keyboard Support
- All interactive elements keyboard accessible
- Logical focus order
- Visual focus indicators

## State Persistence

### LocalStorage Keys
- `agencySidebarCollapsed` - Sidebar collapsed state
- `activeAgencyNavItem` - Currently active menu item

### Behavior
- State persists across page reloads
- Per-browser storage
- Automatic sync on state change

## Styling

### Color Scheme
- Background: Gradient from purple-900 to indigo-900
- Active item: Purple-600
- Hover: Purple-800
- Text: White/Purple-200

### Customizing Colors

Edit the Tailwind classes in the component:
```blade
<!-- Change background gradient -->
class="bg-gradient-to-b from-purple-900 to-indigo-900"

<!-- Change active state -->
:class="isActive('item') ? 'bg-purple-600 text-white' : 'text-purple-200'"
```

## Performance

### Optimizations
- Badge API calls cached for 30 seconds
- Debounced search input
- Lazy-loaded search results
- Minimal re-renders with Alpine.js

### Best Practices
- Keep badge counts lightweight
- Limit search results to 20 items
- Use CDN for icons if needed

## Security Considerations

### Role-Based Access
- Sidebar only renders for `agency_admin` role
- All routes protected by middleware
- API endpoints require authentication

### XSS Prevention
- All user input escaped
- Blade templating auto-escapes
- CSP headers recommended

### CSRF Protection
- All POST requests include CSRF token
- API calls include X-CSRF-TOKEN header

### Audit Logging
- Sensitive actions logged (remove brand, reject proposal)
- Team member actions tracked
- Accessible via Account Menu → Audit Logs

## Agency-Specific Features

### Multi-Brand Oversight
- View all managed brands in one place
- Quick filters by status, industry, performance
- Status indicators (active, paused, pending)
- Quick actions: View details, Send message, Remove

### Campaign Management
- Create campaigns for any managed brand
- Assign creators from marketplace
- Manage milestones and deliverables
- Budget allocation across brands
- Track campaign performance

### Proposal Workflows
- Oversee all proposals between brands and creators
- Approve/reject proposals on behalf of brands
- Add comments and feedback
- Track proposal lifecycle
- Confirmation dialogs for sensitive actions

### Creator Directory
- Access to full marketplace directory
- Shortlist potential influencers
- Send invites to creators
- View creator profiles and metrics
- Filter by niche, engagement, reach

### Messaging Hub
- Multi-thread conversations
- Chat with brands and creators
- Attach files and media
- Message history and search
- Unread message indicators

### Analytics & Reports
- Campaign performance across all brands
- Creator engagement metrics
- ROI reports and insights
- Export to CSV/PDF
- Custom date ranges
- Comparative analysis

### Billing Management
- View all invoices
- Revenue sharing with brands
- Track payments and transactions
- Payment reminders
- Financial reports

## Troubleshooting

### Sidebar Not Showing
1. Check user has `agency_admin` role
2. Verify layout is using `@hasrole('agency_admin')`
3. Check Alpine.js is loaded

### Badges Not Updating
1. Verify API route is accessible
2. Check CSRF token in headers
3. Inspect browser console for errors
4. Verify database queries in controller

### Search Not Working
1. Check search API endpoint
2. Verify query parameter encoding
3. Check database indexes for performance
4. Review error logs

### Mobile Menu Issues
1. Verify viewport meta tag
2. Check z-index conflicts
3. Test touch events
4. Validate responsive breakpoints

## Testing

### Manual Testing Checklist
- [ ] Sidebar visible for agency_admin
- [ ] Sidebar hidden for other roles
- [ ] All navigation links work
- [ ] Badges display correct counts
- [ ] Quick search returns results
- [ ] Collapse/expand persists
- [ ] Mobile menu functions
- [ ] Keyboard navigation works
- [ ] Screen reader accessible
- [ ] No console errors
- [ ] Confirmation dialogs work
- [ ] Audit logs record actions

### Automated Testing

Example test:
```php
// tests/Feature/AgencySidebarTest.php
public function test_sidebar_visible_for_agency_admin()
{
    $user = User::factory()->create();
    $user->assignRole('agency_admin');
    
    $response = $this->actingAs($user)
        ->get(route('agency.dashboard'));
    
    $response->assertSee('Agency Admin');
    $response->assertSee('Dashboard');
    $response->assertSee('Managed Brands');
}

public function test_sidebar_badges_api()
{
    $user = User::factory()->create();
    $user->assignRole('agency_admin');
    
    $response = $this->actingAs($user)
        ->getJson(route('agency.sidebar.badges'));
    
    $response->assertOk()
        ->assertJsonStructure([
            'success',
            'badges' => [
                'totalBrands',
                'pendingProposals',
                'activeCampaigns',
                'unreadMessages',
                'notifications'
            ]
        ]);
}
```

## Future Enhancements

### Planned Features
- [ ] Drag-and-drop menu reordering
- [ ] Custom menu item creation
- [ ] Theme customization UI
- [ ] Notification center panel
- [ ] Recent items history
- [ ] Favorites/bookmarks
- [ ] Multi-language support
- [ ] Dark/light mode toggle
- [ ] Advanced filtering in search
- [ ] Bulk actions on brands/campaigns

## Support

For issues or questions:
1. Check this documentation
2. Review error logs
3. Inspect browser console
4. Contact development team

## Changelog

### Version 1.0.0 (2025-09-30)
- Initial release
- 12 navigation items as specified
- Badge system with 5 indicators
- Quick search functionality
- Mobile responsive design
- Accessibility compliant
- Keyboard navigation support
- Multi-brand oversight features
- Campaign management tools
- Proposal approval workflows
- Creator directory access
- Messaging hub
- Analytics & reporting
- Billing management
- Audit logging

## Related Documentation

- [Brand Admin Sidebar](./BRAND_ADMIN_SIDEBAR.md)
- [Creator Admin Sidebar](./CREATOR_ADMIN_SIDEBAR.md)
- [Super Admin Sidebar](./SUPERADMIN_SIDEBAR_SETUP.md)

## API Reference

### Sidebar Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/agency/api/sidebar/badges` | GET | Get badge counts |
| `/agency/api/sidebar/search` | GET | Quick search |
| `/agency/api/sidebar/kpis` | GET | Dashboard KPIs |
| `/agency/api/sidebar/activity` | GET | Recent activity |

### Response Codes

| Code | Description |
|------|-------------|
| 200 | Success |
| 401 | Unauthorized |
| 403 | Forbidden (wrong role) |
| 500 | Server error |

## Best Practices

1. **Always confirm sensitive actions** - Use confirmation dialogs for removing brands, rejecting proposals
2. **Log all actions** - Ensure audit trail for team member actions
3. **Keep badges accurate** - Refresh badge counts regularly
4. **Optimize queries** - Use database indexes for search and badge queries
5. **Handle errors gracefully** - Show user-friendly error messages
6. **Test across devices** - Ensure mobile responsiveness
7. **Follow accessibility guidelines** - Maintain WCAG 2.1 AA compliance
8. **Document custom changes** - Keep documentation updated

## Conclusion

The Agency Admin sidebar provides a comprehensive navigation system tailored for agency administrators managing multiple brands and coordinating between brands and creators. With its intuitive design, real-time updates, and powerful features, it enables efficient multi-brand oversight and campaign management.