# 📊 LMS Performance API Documentation

## Overview

The LMS Performance API provides comprehensive analytics and metrics for student performance tracking. This includes individual progress monitoring, category-wise analysis, comparative statistics, and leaderboard functionality.

## Base URL
```
{{base_url}}/api/quizzes
```

## Authentication
All endpoints require Bearer token authentication:
```
Authorization: Bearer {token}
```

---

## 📈 Performance Endpoints

### 1. Get Overall Performance Metrics

**GET** `/my-performance`

Get comprehensive performance statistics for the authenticated user.

#### Response Data
| Field | Type | Description |
|-------|------|-------------|
| `practice_attempts` | integer | Total completed practice attempts |
| `tryout_attempts` | integer | Total completed tryout attempts |
| `average_practice_score` | float | Average score across all practice quizzes |
| `average_tryout_score` | float | Average score across all tryouts |
| `average_practice_time` | float | Average time per practice quiz (seconds) |
| `average_tryout_time` | float | Average time per tryout (seconds) |
| `accuracy` | float | Overall accuracy percentage |
| `total_questions_answered` | integer | Total questions answered |
| `all_customers_average` | object | Platform-wide averages for comparison |
| `recent_activity` | array | Last 5 quiz attempts |

#### Example Response
```json
{
    "success": true,
    "data": {
        "practice_attempts": 45,
        "tryout_attempts": 12,
        "average_practice_score": 78.5,
        "average_tryout_score": 72.3,
        "average_practice_time": 1245.7,
        "average_tryout_time": 3456.2,
        "accuracy": 74.2,
        "total_questions_answered": 1280,
        "all_customers_average": {
            "practice_score": 65.8,
            "tryout_score": 68.1,
            "practice_time": 1456.3,
            "tryout_time": 3789.1
        },
        "recent_activity": [
            {
                "id": 145,
                "quiz_id": 23,
                "quiz_title": "Matematika Dasar - Aljabar",
                "quiz_type": "practice",
                "score": 85.5,
                "completed_at": "2024-01-15T10:30:00.000000Z"
            }
        ]
    }
}
```

---

### 2. Get Practice Quiz Performance

**GET** `/my-performance/practice`

Get detailed performance metrics for all practice quizzes attempted by the user.

#### Response Data
Each quiz performance includes:
| Field | Type | Description |
|-------|------|-------------|
| `quiz_id` | integer | Quiz identifier |
| `quiz_title` | string | Quiz name |
| `best_score` | float | Highest score achieved |
| `attempts_count` | integer | Number of attempts |
| `last_attempt_date` | string | Date of last attempt |
| `improvement` | float | Score improvement (last - first) |
| `average_score` | float | Average across all attempts |
| `average_time` | float | Average time taken (seconds) |

#### Example Response
```json
{
    "success": true,
    "data": [
        {
            "quiz_id": 23,
            "quiz_title": "Matematika Dasar - Aljabar",
            "best_score": 85.5,
            "attempts_count": 3,
            "last_attempt_date": "2024-01-15T10:30:00.000000Z",
            "improvement": 12.5,
            "average_score": 78.3,
            "average_time": 1245.7
        }
    ]
}
```

---

### 3. Get Tryout Performance

**GET** `/my-performance/tryouts`

Get detailed performance metrics for all tryout attempts by the user.

#### Response Data
Each tryout performance includes:
| Field | Type | Description |
|-------|------|-------------|
| `tryout_id` | integer | Tryout identifier |
| `tryout_title` | string | Tryout name |
| `best_score` | float | Highest score achieved |
| `attempts_count` | integer | Number of attempts |
| `last_attempt_date` | string | Date of last attempt |
| `improvement` | float | Score improvement (last - first) |
| `average_score` | float | Average across all attempts |
| `average_time` | float | Average time taken (seconds) |

#### Example Response
```json
{
    "success": true,
    "data": [
        {
            "tryout_id": 45,
            "tryout_title": "Tryout CPNS 2024 - Batch 1",
            "best_score": 78.2,
            "attempts_count": 2,
            "last_attempt_date": "2024-01-14T14:20:00.000000Z",
            "improvement": 5.3,
            "average_score": 75.55,
            "average_time": 3456.2
        }
    ]
}
```

---

### 4. Get Category Performance

**GET** `/my-performance/categories`

Get performance metrics broken down by question categories (subcategories).

#### Response Data
Each category performance includes:
| Field | Type | Description |
|-------|------|-------------|
| `sub_category_id` | integer | Subcategory identifier |
| `name` | string | Category name |
| `attempts_count` | integer | Number of attempts in this category |
| `average_score` | float | Average score in this category |
| `accuracy` | float | Accuracy percentage |
| `average_time` | float | Average time per question (seconds) |

#### Example Response
```json
{
    "success": true,
    "data": [
        {
            "sub_category_id": 1,
            "name": "Matematika Dasar",
            "attempts_count": 15,
            "average_score": 78.5,
            "accuracy": 74.2,
            "average_time": 1245.7
        },
        {
            "sub_category_id": 2,
            "name": "Bahasa Indonesia",
            "attempts_count": 12,
            "average_score": 85.3,
            "accuracy": 82.1,
            "average_time": 1156.5
        }
    ]
}
```

---

### 5. Get Pentagon Chart Performance

**GET** `/my-performance/pentagon`

Get performance data formatted for pentagon chart visualization showing performance across 5 main categories.

#### Response Data
| Field | Type | Description |
|-------|------|-------------|
| `pentagon_data` | array | Performance scores for 5 main categories |
| `category_performance` | array | Detailed metrics for each category |
| `overall_metrics` | object | Overall performance summary |
| `comparison` | object | Comparison with platform averages |
| `chart_config` | object | Chart configuration settings |

#### Pentagon Data Structure
```json
{
    "category_id": 1,
    "category_name": "Matematika",
    "category_code": "MAT",
    "performance_score": 78.5
}
```

#### Category Performance Structure
```json
{
    "category_id": 1,
    "category_name": "Matematika",
    "category_code": "MAT",
    "performance_score": 78.5,
    "metrics": {
        "average_score": 78.5,
        "best_score": 92.0,
        "recent_score": 85.5,
        "total_attempts": 15,
        "improvement_trend": 8.7,
        "consistency_score": 82.3
    }
}
```

#### Overall Metrics Structure
```json
{
    "overall_average": 76.24,
    "total_attempts": 65,
    "categories_attempted": 5,
    "overall_improvement": 8.46,
    "performance_level": "Advanced"
}
```

#### Comparison Structure
```json
{
    "customer_average": 76.24,
    "platform_average": 68.7,
    "performance_vs_average": 7.54,
    "percentile_rank": 78.5,
    "ranking_message": "You're performing better than 78% of students!"
}
```

---

## 🏆 Leaderboard Endpoints

### 1. Get Global Leaderboard

**GET** `/leaderboard`

Get global leaderboard showing top performers across all quizzes.

#### Response Data
| Field | Type | Description |
|-------|------|-------------|
| `practice` | array | Top 20 practice quiz performers |
| `tryout` | array | Top 20 tryout performers |

#### Leaderboard Entry Structure
```json
{
    "customer_id": 45,
    "customer_name": "Ahmad Rizki",
    "quiz_id": 23,
    "quiz_title": "Matematika Dasar - Aljabar",
    "quiz_type": "practice",
    "score": 98.5,
    "time_taken_seconds": 1023.5,
    "completed_at": "2024-01-15T08:30:00.000000Z"
}
```

---

### 2. Get Practice Quiz Leaderboard

**GET** `/leaderboard/practice/{quiz_id}`

Get leaderboard for a specific practice quiz.

#### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `quiz_id` | integer | ✅ | ID of the practice quiz |

#### Response Data
```json
{
    "success": true,
    "data": {
        "quiz": {
            "id": 23,
            "title": "Matematika Dasar - Aljabar"
        },
        "leaderboard": [
            {
                "customer_id": 45,
                "customer_name": "Ahmad Rizki",
                "score": 98.5,
                "time_taken_seconds": 1023.5,
                "completed_at": "2024-01-15T08:30:00.000000Z"
            }
        ]
    }
}
```

---

### 3. Get Tryout Leaderboard

**GET** `/leaderboard/tryout/{quiz_id}`

Get leaderboard for a specific tryout.

#### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `quiz_id` | integer | ✅ | ID of the tryout quiz |

#### Response Data
```json
{
    "success": true,
    "data": {
        "tryout": {
            "id": 45,
            "title": "Tryout CPNS 2024 - Batch 1"
        },
        "leaderboard": [
            {
                "customer_id": 89,
                "customer_name": "Dewi Kartika",
                "score": 94.5,
                "time_taken_seconds": 3245.7,
                "completed_at": "2024-01-14T09:30:00.000000Z"
            }
        ]
    }
}
```

---

## 📊 Key Performance Indicators

### Performance Levels
- **Beginner**: 0-54%
- **Intermediate**: 55-69%
- **Advanced**: 70-84%
- **Expert**: 85-100%

### Score Metrics
- **Average Score**: Mean score across all attempts
- **Best Score**: Highest score achieved
- **Recent Score**: Score from most recent attempt
- **Improvement**: Difference between last and first attempt
- **Consistency**: Standard deviation-based consistency metric

### Time Metrics
- **Average Time**: Mean time per quiz/question
- **Time Efficiency**: Comparison with platform averages
- **Speed Index**: Performance relative to time taken

### Accuracy Metrics
- **Overall Accuracy**: (Correct answers / Total questions) × 100
- **Category Accuracy**: Accuracy within specific subject areas
- **Trend Analysis**: Improvement over time

---

## 🔍 Usage Examples

### Frontend Integration

#### React Component Example
```jsx
import { useEffect, useState } from 'react';
import axios from 'axios';

function PerformanceDashboard() {
    const [performance, setPerformance] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchPerformance = async () => {
            try {
                const response = await axios.get('/api/quizzes/my-performance', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                setPerformance(response.data.data);
            } catch (error) {
                console.error('Error fetching performance:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchPerformance();
    }, []);

    if (loading) return <div>Loading...</div>;

    return (
        <div className="performance-dashboard">
            <h2>My Performance</h2>
            <div className="stats-grid">
                <div className="stat-card">
                    <h3>Practice Attempts</h3>
                    <p>{performance?.practice_attempts}</p>
                </div>
                <div className="stat-card">
                    <h3>Average Score</h3>
                    <p>{performance?.average_practice_score?.toFixed(1)}%</p>
                </div>
                <div className="stat-card">
                    <h3>Accuracy</h3>
                    <p>{performance?.accuracy?.toFixed(1)}%</p>
                </div>
            </div>
            
            <div className="recent-activity">
                <h3>Recent Activity</h3>
                {performance?.recent_activity?.map(activity => (
                    <div key={activity.id} className="activity-item">
                        <span>{activity.quiz_title}</span>
                        <span>{activity.score}%</span>
                        <span>{new Date(activity.completed_at).toLocaleDateString()}</span>
                    </div>
                ))}
            </div>
        </div>
    );
}
```

#### Pentagon Chart Integration
```jsx
import { Radar } from 'react-chartjs-2';

function PentagonChart() {
    const [pentagonData, setPentagonData] = useState(null);

    useEffect(() => {
        const fetchPentagonData = async () => {
            const response = await axios.get('/api/quizzes/my-performance/pentagon');
            setPentagonData(response.data.data);
        };
        fetchPentagonData();
    }, []);

    if (!pentagonData) return <div>Loading chart...</div>;

    const chartData = {
        labels: pentagonData.chart_config.categories,
        datasets: [{
            label: 'My Performance',
            data: pentagonData.pentagon_data.map(item => item.performance_score),
            borderColor: 'rgb(54, 162, 235)',
            backgroundColor: 'rgba(54, 162, 235, 0.2)',
        }]
    };

    const options = {
        scales: {
            r: {
                beginAtZero: true,
                max: 100,
                min: 0
            }
        }
    };

    return (
        <div className="pentagon-chart">
            <h3>Category Performance</h3>
            <Radar data={chartData} options={options} />
            <div className="performance-summary">
                <p>Overall Level: {pentagonData.overall_metrics.performance_level}</p>
                <p>Percentile Rank: {pentagonData.comparison.percentile_rank}%</p>
                <p>{pentagonData.comparison.ranking_message}</p>
            </div>
        </div>
    );
}
```

---

## 🎯 Best Practices

### 1. **Caching Strategy**
- Cache performance data for 5-10 minutes
- Invalidate cache after new quiz completions
- Use Redis or local storage for frontend caching

### 2. **Error Handling**
```javascript
try {
    const response = await axios.get('/api/quizzes/my-performance');
    // Handle success
} catch (error) {
    if (error.response?.status === 401) {
        // Redirect to login
    } else if (error.response?.status === 403) {
        // Show access denied message
    } else {
        // Show generic error
    }
}
```

### 3. **Loading States**
- Show skeleton loaders during data fetching
- Implement progressive loading for large datasets
- Use optimistic updates for better UX

### 4. **Data Visualization**
- Use charts for trend analysis
- Color-code performance levels
- Show progress indicators
- Include comparison benchmarks

---

## 📋 Common Use Cases

### 1. **Student Dashboard**
- Overall performance metrics
- Recent activity feed
- Progress tracking
- Goal setting and achievements

### 2. **Performance Analysis**
- Category-wise strengths/weaknesses
- Improvement trends over time
- Comparative analysis with peers
- Time management insights

### 3. **Leaderboard Features**
- Global rankings
- Quiz-specific competitions
- Achievement badges
- Social comparison features

### 4. **Progress Tracking**
- Learning path completion
- Skill development monitoring
- Performance goal tracking
- Adaptive learning recommendations

---

## 🔄 API Rate Limits

- **Standard Rate**: 100 requests per minute
- **Burst Rate**: 200 requests per minute
- **Daily Limit**: 10,000 requests per day

### Rate Limit Headers
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 99
X-RateLimit-Reset: 1640995200
```

---

## 🛠️ Testing

### Postman Collection
Import the provided `LMS-Performance-API.postman_collection.json` for comprehensive testing.

### Sample Test Cases
1. **Authentication**: Test with valid/invalid tokens
2. **Data Integrity**: Verify score calculations
3. **Performance**: Test response times
4. **Error Handling**: Test edge cases
5. **Pagination**: Test large datasets

---

## 📞 Support

For technical support or API questions:
- **Email**: api-support@lms.com
- **Documentation**: https://docs.lms.com/api/performance
- **Status Page**: https://status.lms.com

---

## 🔄 Changelog

### v1.0.0 (Current)
- Initial release with core performance metrics
- Pentagon chart visualization
- Global and quiz-specific leaderboards
- Category-wise performance analysis
- Comparative statistics with platform averages 