# Creator Admin Sidebar Navigation

Complete documentation for the Creator/Influencer left sidebar navigation system.

## Overview

The Creator Admin sidebar is a comprehensive navigation system designed specifically for content creators and influencers. It provides quick access to all creator-level features including content management, campaign participation, social integrations, earnings tracking, and analytics.

## Features

### ✅ Core Features
- **14 Navigation Items** in logical order (as per requirements)
- **Role-Based Access** - Only visible to `creator` 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 (pink accent color)
- Hover effects and visual feedback
- Purple gradient background design
- Icon-based navigation
- Submenu support (Settings)
- Quick stats display in top bar

## Installation

### 1. Files Created

```
resources/views/components/creator-sidebar.blade.php
resources/views/layouts/creator-admin.blade.php
app/Http/Controllers/Creator/SidebarController.php
docs/CREATOR_ADMIN_SIDEBAR.md
```

### 2. Routes Added

```php
// In routes/web.php - Creator sidebar API routes
Route::get('/api/sidebar/badges', [SidebarController::class, 'getBadges'])
    ->name('creator.sidebar.badges');
Route::get('/api/sidebar/search', [SidebarController::class, 'quickSearch'])
    ->name('creator.sidebar.search');
Route::get('/api/sidebar/stats', [SidebarController::class, 'getDashboardStats'])
    ->name('creator.sidebar.stats');
Route::post('/api/notifications/{notification}/read', [SidebarController::class, 'markNotificationRead'])
    ->name('creator.notifications.read');
Route::post('/api/notifications/read-all', [SidebarController::class, 'markAllNotificationsRead'])
    ->name('creator.notifications.read-all');
```

## Usage

### Basic Usage

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

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

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

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

### Direct Component Usage

If you need more control, use the component directly:

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

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

## Navigation Structure

### Main Navigation Items (in order as per requirements)

1. **Dashboard** - Overview cards: followers, engagement, campaign invites, earnings
2. **Social Accounts** - Connect/disconnect/test (Instagram, YouTube, TikTok, X, LinkedIn)
3. **Content Ideas** - AI suggestions for posts/reels, save as draft, schedule
4. **Reels** - Create/edit AI-powered reels, track status
5. **Scheduled Posts** - Calendar view of planned content
6. **Campaigns** - List of campaigns creator is invited/participating, milestones, deliverables (with badge)
7. **Proposals** - View brand proposals, accept/reject, track negotiations (with badge)
8. **Messaging** - Thread-based chat with brands/agencies (with badge)
9. **Analytics** - Personal growth charts (followers, engagement, reach by platform)
10. **Notifications** - Alerts for new campaigns, expiring tokens, unread chats (with badge)
11. **Earnings** - Show accepted contracts, payments received, pending payouts (with badge)
12. **Support Bot** - FAQs, raise support ticket, chatbot with fallback
13. **Settings** (expandable submenu):
    - Profile & Bio
    - Niche & Audience
    - API Keys
    - Privacy Settings
14. **Account Menu** (bottom):
    - Profile
    - Audit Logs
    - Logout

## Badge System

### Real-Time Badges

The sidebar displays real-time notification badges for:

- **Pending Proposals** (yellow badge) - Proposals received from brands awaiting response
- **Active Campaigns** (green badge) - Campaigns creator is currently participating in
- **Unread Messages** (red badge) - Unread messages from brands/agencies
- **Notifications** (red badge) - System notifications
- **Pending Payments** (orange badge) - Payments pending or in processing

### Badge API

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

Response format:
```json
{
    "success": true,
    "badges": {
        "pendingProposals": 3,
        "activeCampaigns": 5,
        "unreadMessages": 12,
        "notifications": 8,
        "pendingPayments": 2
    }
}
```

Badges auto-refresh every 30 seconds.

## Quick Search

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

### Features
- Searches navigation items
- Searches campaigns, content ideas, proposals, scheduled posts via API
- Real-time results as you type
- Keyboard navigable

### Search API

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

Response format:
```json
{
    "success": true,
    "results": [
        {
            "name": "Campaign Name",
            "category": "Campaign",
            "url": "/creator/campaigns/123",
            "meta": "Status: active"
        },
        {
            "name": "Content Idea Title",
            "category": "Content Idea",
            "url": "/creator/content-ideas/456",
            "meta": "Status: draft"
        }
    ]
}
```

## Dashboard Stats API

Get creator dashboard statistics:

```
GET /creator/api/sidebar/stats
```

Response format:
```json
{
    "success": true,
    "stats": {
        "totalFollowers": 125000,
        "avgEngagement": 4.5,
        "totalEarnings": 15000.00,
        "pendingEarnings": 2500.00,
        "activeCampaigns": 3,
        "campaignInvites": 5
    }
}
```

## Feature Details

### 1. Dashboard
- Overview cards showing key metrics
- Follower count across all platforms
- Engagement rate
- Campaign invites count
- Total and pending earnings
- Quick action buttons

### 2. Social Accounts
- Connect multiple social platforms (Instagram, YouTube, TikTok, X, LinkedIn)
- OAuth integration for secure connection
- Test connection functionality
- Disconnect/reconnect options
- View account metrics
- Share access with brands (controlled)

### 3. Content Ideas
- AI-powered content suggestions
- Save ideas as drafts
- Schedule posts directly
- Filter by platform
- Search and organize ideas
- Export to proposals

### 4. Reels
- Create AI-powered reels
- Upload custom content
- Track processing status
- Download completed reels
- Retry failed generations
- View performance metrics

### 5. Scheduled Posts
- Calendar view of all scheduled content
- Create new scheduled posts
- Edit/reschedule posts
- Publish immediately option
- Cancel scheduled posts
- Track posting status
- Retry failed posts

### 6. Campaigns (Participation)
- View campaigns creator is invited to
- Active campaign tracking
- Milestone management
- Deliverable tracking
- Campaign performance metrics
- Export campaign data

### 7. Proposals (Received & Sent)
- View proposals from brands
- Accept/reject proposals
- Negotiate terms
- Track proposal status
- Comment on proposals
- View proposal history

### 8. Messaging
- Thread-based conversations with brands
- Real-time messaging
- Unread message indicators
- Search conversations
- Attachment support
- Message history

### 9. Analytics (Personal Performance)
- Follower growth charts
- Engagement rate trends
- Reach by platform
- Content performance
- Audience demographics
- Export analytics data

### 10. Notifications
- Campaign invitations
- Proposal updates
- Payment alerts
- Token expiration warnings
- Message notifications
- System announcements

### 11. Earnings
- Accepted contracts list
- Payment history
- Pending payouts
- Payment status tracking
- Invoice generation
- Earnings analytics

### 12. Support Bot
- FAQ access
- Raise support tickets
- AI chatbot assistance
- Escalate to human support
- Track ticket status
- Knowledge base search

### 13. Settings
**Profile & Bio:**
- Edit creator profile
- Update bio and description
- Profile picture management
- Social links

**Niche & Audience:**
- Define content niche
- Target audience demographics
- Content categories
- Influencer type

**API Keys:**
- Manage API credentials
- Generate new keys
- Revoke access
- View usage statistics

**Privacy Settings:**
- Account visibility
- Data sharing preferences
- Notification settings
- Security options

### 14. Account Menu
**Profile:**
- View public profile
- Edit profile details
- Profile analytics

**Audit Logs:**
- View activity history
- Track important actions
- Security events
- Login history

**Logout:**
- Secure logout
- Session termination

## Customization

### Changing Sidebar Width

Edit the component:
```javascript
// In creator-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('creator.new-feature') }}" 
   @click="setActive('new-feature')"
   :class="isActive('new-feature') ? 'bg-pink-600 text-white' : 'text-purple-100 hover:bg-purple-700'"
   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("creator.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
- `creatorSidebarCollapsed` - Sidebar collapsed state
- `activeCreatorNavItem` - 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-800
- Active item: Pink-600
- Hover: Purple-700
- Text: White/Purple-100

### Customizing Colors

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

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

## 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

## Troubleshooting

### Sidebar Not Showing
1. Check user has `creator` role
2. Verify layout is using `@hasrole('creator')`
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

## Security Considerations

### Role-Based Access
- Sidebar only renders for `creator` 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

## Important Actions with Confirmation

The following actions require user confirmation and are logged in audit logs:

1. **Accept/Reject Proposal** - Confirmation modal before action
2. **Disconnect Social Account** - Warning about data loss
3. **Revoke Brand Access** - Confirmation of access removal
4. **Delete Scheduled Post** - Confirmation before deletion
5. **Cancel Campaign Participation** - Warning about contract implications

## Testing

### Manual Testing Checklist
- [ ] Sidebar visible for creator role
- [ ] 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 modals work
- [ ] Audit logs created for important actions

### Automated Testing

Example test:
```php
// tests/Feature/CreatorSidebarTest.php
public function test_sidebar_visible_for_creator()
{
    $user = User::factory()->create();
    $user->assignRole('creator');
    
    $response = $this->actingAs($user)
        ->get(route('creator.dashboard'));
    
    $response->assertSee('Creator Hub');
    $response->assertSee('Dashboard');
}

public function test_badges_api_returns_correct_counts()
{
    $creator = User::factory()->create();
    $creator->assignRole('creator');
    
    // Create test data
    Proposal::factory()->count(3)->create([
        'creator_id' => $creator->id,
        'status' => 'sent'
    ]);
    
    $response = $this->actingAs($creator)
        ->getJson(route('creator.sidebar.badges'));
    
    $response->assertJson([
        'success' => true,
        'badges' => [
            'pendingProposals' => 3
        ]
    ]);
}
```

## Acceptance Criteria Verification

✅ **Sidebar केवल creator role के लिए visible हो**
- Implemented with `@hasrole('creator')` directive

✅ **Navigation items ऊपर defined order में हों**
- All 14 items in exact order as specified

✅ **Badges सही count दिखाएं**
- Real-time badge counts for proposals, messages, campaigns, payments

✅ **Collapsed/expanded state persist हो**
- LocalStorage implementation for state persistence

✅ **Important actions → confirmation + audit log**
- Confirmation modals for critical actions
- Audit log integration ready

✅ **Mobile drawer usable और responsive हो**
- Hamburger menu with slide drawer
- Touch-friendly interface

✅ **Accessibility standards pass करें**
- ARIA roles implemented
- Focus states defined
- Contrast ratios meet WCAG standards

## 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
- [ ] Voice navigation support
- [ ] Offline mode support

## 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
- 14 navigation items as per requirements
- Badge system with 5 badge types
- Quick search functionality
- Mobile responsive design
- Accessibility compliant
- Keyboard navigation support
- Role-based access control
- Audit log integration ready
- Confirmation modals for important actions

## Related Documentation

- [Brand Admin Sidebar](./BRAND_ADMIN_SIDEBAR.md)
- [Social Account Integration](./SOCIAL_ACCOUNTS.md)
- [Campaign Management](./CAMPAIGNS.md)
- [Earnings & Payments](./EARNINGS.md)
- [Analytics System](./ANALYTICS.md)

## API Reference

### GET /creator/api/sidebar/badges
Returns badge counts for sidebar notifications.

**Response:**
```json
{
    "success": true,
    "badges": {
        "pendingProposals": 3,
        "activeCampaigns": 5,
        "unreadMessages": 12,
        "notifications": 8,
        "pendingPayments": 2
    }
}
```

### GET /creator/api/sidebar/search?query={term}
Searches across creator content.

**Parameters:**
- `query` (string, required): Search term (minimum 2 characters)

**Response:**
```json
{
    "success": true,
    "results": [
        {
            "name": "Item name",
            "category": "Category",
            "url": "/creator/path/123",
            "meta": "Additional info"
        }
    ]
}
```

### GET /creator/api/sidebar/stats
Returns dashboard statistics.

**Response:**
```json
{
    "success": true,
    "stats": {
        "totalFollowers": 125000,
        "avgEngagement": 4.5,
        "totalEarnings": 15000.00,
        "pendingEarnings": 2500.00,
        "activeCampaigns": 3,
        "campaignInvites": 5
    }
}
```

### POST /creator/api/notifications/{notification}/read
Marks a specific notification as read.

**Response:**
```json
{
    "success": true,
    "message": "Notification marked as read"
}
```

### POST /creator/api/notifications/read-all
Marks all notifications as read.

**Response:**
```json
{
    "success": true,
    "message": "All notifications marked as read"
}
```

## License

This component is part of the AI Business Market platform and is proprietary software.

---

**Last Updated:** 2025-09-30  
**Version:** 1.0.0  
**Maintained By:** Development Team