# 🎯 Super Admin Dashboard - Complete Guide

## Overview

The Super Admin Dashboard provides comprehensive analytics and management capabilities for the entire food delivery platform.

## Features

### 📊 Real-Time Statistics
- **Total Revenue**: Track all-time and daily revenue with growth indicators
- **Total Orders**: Monitor order volume with pending order counts
- **Restaurants**: View total, active, and pending restaurant approvals
- **Users**: Track user registrations and verification status
- **Delivery Boys**: Monitor total, active, and online delivery personnel
- **Live Stats**: Real-time active orders and pending approvals

### 📈 Analytics & Charts
- **Revenue Trend Chart**: Line chart showing revenue over selected period
- **Order Status Distribution**: Doughnut chart displaying order status breakdown
- **Payment Methods**: Analysis of payment method usage
- **Daily Trends**: Day-by-day order and revenue tracking

### 🏆 Top Performers
- **Top Restaurants**: Ranked by revenue and order count
- **Top Products**: Most ordered items across the platform
- **Top Delivery Boys**: Highest performing delivery personnel

### 📋 Recent Activities
- Real-time feed of:
  - New orders placed
  - Restaurant registrations
  - User sign-ups
  - System events

## API Endpoints

### Get Dashboard Data
```http
GET /api/admin/dashboard?period=30
```

**Parameters:**
- `period` (optional): Number of days to analyze (default: 30)
  - Options: 7, 30, 90

**Response:**
```json
{
  "success": true,
  "data": {
    "stats": {
      "total_revenue": {
        "value": 125000,
        "today": 3500,
        "growth": 15.5
      },
      "total_orders": {
        "value": 1250,
        "today": 45,
        "pending": 12,
        "growth": 8.2
      },
      "total_restaurants": {
        "value": 85,
        "active": 78,
        "pending": 5
      },
      "total_users": {
        "value": 5420,
        "today": 23,
        "verified": 4890
      },
      "delivery_boys": {
        "total": 120,
        "active": 110,
        "online": 45
      },
      "live_stats": {
        "active_orders": 28,
        "pending_approvals": 7
      }
    },
    "charts": {
      "revenue": [...],
      "orders": [...],
      "order_status": [...],
      "payment_methods": [...]
    },
    "recent_activities": [...],
    "top_performers": {
      "restaurants": [...],
      "products": [...],
      "delivery_boys": [...]
    }
  }
}
```

## Frontend Components

### Main Dashboard Component
**Location:** `admin-dashboard/src/views/SuperAdminDashboard.vue`

**Features:**
- Period selector (7, 30, 90 days)
- Responsive grid layout
- Interactive charts using Chart.js
- Real-time data updates
- Loading states

### Reusable Components

#### StatsCard Component
**Location:** `admin-dashboard/src/components/dashboard/StatsCard.vue`

**Usage:**
```vue
<StatsCard
  title="Total Revenue"
  :value="125000"
  icon="💰"
  :growth="15.5"
  subtitle="Today: $3,500"
  variant="revenue"
  format="currency"
/>
```

**Props:**
- `title`: Card title
- `value`: Numeric value to display
- `icon`: Emoji or icon
- `growth`: Growth percentage (optional)
- `subtitle`: Additional info (optional)
- `variant`: Color theme (revenue, orders, restaurants, users, delivery, live)
- `format`: Value format (number, currency)

## State Management

### Pinia Store
**Location:** `admin-dashboard/src/store/modules/superAdmin.js`

**Actions:**
```javascript
import { useSuperAdminStore } from '@/store/modules/superAdmin'

const store = useSuperAdminStore()

// Fetch dashboard data
await store.fetchDashboardData(30)

// Refresh stats only
await store.refreshStats()
```

**Getters:**
- `totalRevenue`
- `totalOrders`
- `totalRestaurants`
- `totalUsers`
- `activeOrders`
- `pendingApprovals`

## Routing

### Access Dashboard
```
/super-admin
```

**Route Configuration:**
```javascript
{
  path: '/super-admin',
  name: 'SuperAdminDashboard',
  component: () => import('@/views/SuperAdminDashboard.vue'),
  meta: { 
    title: 'Super Admin Dashboard', 
    role: 'super-admin' 
  }
}
```

## Permissions

Required role: `super-admin`

The dashboard automatically checks user role and redirects unauthorized users.

## Installation & Setup

### 1. Backend Setup

Run migrations (already done):
```bash
php artisan migrate
```

Seed roles and permissions:
```bash
php artisan db:seed --class=RolePermissionSeeder
```

### 2. Frontend Setup

Install Chart.js:
```bash
cd admin-dashboard
npm install chart.js
```

### 3. Test Login

Use the super admin credentials:
- **Email:** admin@fooddelivery.com
- **Password:** admin123

## Usage Guide

### 1. Login as Super Admin
Navigate to `/login` and use super admin credentials.

### 2. Access Dashboard
Click "Super Admin Dashboard" in the navigation or go to `/super-admin`.

### 3. Select Time Period
Use the dropdown to view data for:
- Last 7 days
- Last 30 days (default)
- Last 90 days

### 4. Monitor Key Metrics
- Check revenue growth
- Monitor pending orders
- Review restaurant approvals
- Track delivery boy availability

### 5. Analyze Performance
- Review top performing restaurants
- Identify best-selling products
- Recognize top delivery personnel

### 6. Recent Activities
- Monitor real-time platform activity
- Quick access to recent orders
- Track new registrations

## Customization

### Add New Stat Card
```vue
<div class="stat-card custom">
  <div class="stat-icon">🎯</div>
  <div class="stat-details">
    <h3>Custom Metric</h3>
    <p class="stat-value">{{ customValue }}</p>
  </div>
</div>
```

### Add New Chart
```javascript
const customChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: [...],
    datasets: [{
      label: 'Custom Data',
      data: [...]
    }]
  }
})
```

## Performance Optimization

### Caching
Dashboard data is cached for 5 minutes on the backend.

### Lazy Loading
Charts are rendered only after data is loaded.

### Auto Refresh
Set up auto-refresh for live stats:
```javascript
setInterval(() => {
  store.refreshStats()
}, 60000) // Every minute
```

## Troubleshooting

### Dashboard Not Loading
1. Check authentication token
2. Verify super-admin role
3. Check API endpoint: `/api/admin/dashboard`
4. Review browser console for errors

### Charts Not Rendering
1. Ensure Chart.js is installed
2. Check canvas refs are properly bound
3. Verify chart data format

### Permission Denied
1. Confirm user has `super-admin` role
2. Check role assignment in database
3. Clear cache: `php artisan cache:clear`

## Security

- Dashboard requires authentication
- Role-based access control (RBAC)
- API rate limiting applied
- Sensitive data filtered by role

## Future Enhancements

- [ ] Export dashboard data to PDF/CSV
- [ ] Custom date range selector
- [ ] Real-time WebSocket updates
- [ ] Customizable dashboard widgets
- [ ] Email reports scheduling
- [ ] Mobile responsive improvements
- [ ] Dark mode support

## Support

For issues or questions:
- Check Laravel logs: `storage/logs/laravel.log`
- Review browser console
- Test API endpoints with Postman
- Contact development team

---

**Built for efficient platform management** 🚀
