# 🚨 LMS Question Reporting API Documentation

## Overview

The Question Reporting API allows users to report questions that contain errors, typos, incorrect answers, or other issues. This helps maintain the quality of the quiz content and improves the learning experience for all users.

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

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

---

## 🔥 Question Reporting Endpoints

### 1. Report a Question

**POST** `/report`

Report a question for errors or issues.

#### Request Body
```json
{
    "question_id": 1234,
    "report_reason": "Incorrect answer marked as correct",
    "additional_details": "The correct answer should be option B, but the system shows option A as correct. This is based on the textbook reference mentioned in the question."
}
```

#### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `question_id` | integer | ✅ | ID of the question to report |
| `report_reason` | string | ✅ | Reason for reporting (max 1000 characters) |
| `additional_details` | string | ❌ | Additional details about the issue (max 2000 characters) |

#### Common Report Reasons
- **Incorrect answer marked as correct**
- **Typo in question text**
- **Missing or broken image**
- **Unclear question wording**
- **Wrong explanation provided**
- **Missing answer options**
- **Duplicate question**
- **Outdated information**
- **Grammar or spelling errors**

#### Response Examples

**✅ Success Response (201)**
```json
{
    "success": true,
    "message": "Question reported successfully. Thank you for helping us improve!",
    "data": {
        "report_id": 78,
        "question_id": 1234,
        "report_reason": "Incorrect answer marked as correct",
        "status": "pending",
        "reported_at": "2024-01-15T10:30:00.000000Z"
    }
}
```

**⚠️ Already Reported (409)**
```json
{
    "success": false,
    "message": "You have already reported this question. Your previous report is being reviewed.",
    "data": {
        "report_id": 78,
        "status": "pending",
        "reported_at": "2024-01-15T10:30:00.000000Z"
    }
}
```

**❌ Validation Error (422)**
```json
{
    "success": false,
    "message": "The given data was invalid.",
    "errors": {
        "question_id": [
            "The selected question id is invalid."
        ],
        "report_reason": [
            "The report reason field is required."
        ]
    }
}
```

---

### 2. Get My Question Reports

**GET** `/my-reports`

Get user's question reports history with pagination.

#### Query Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `per_page` | integer | 10 | Number of reports per page |

#### Response Data
| Field | Type | Description |
|-------|------|-------------|
| `reports` | array | List of question reports |
| `pagination` | object | Pagination metadata |

#### Response Example

**✅ Success Response (200)**
```json
{
    "success": true,
    "message": "Question reports retrieved successfully",
    "data": {
        "reports": [
            {
                "id": 78,
                "customer_id": 123,
                "question_id": 1234,
                "report_reason": "Incorrect answer marked as correct",
                "status": "pending",
                "admin_notes": "The correct answer should be option B, but the system shows option A as correct.",
                "created_at": "2024-01-15T10:30:00.000000Z",
                "updated_at": "2024-01-15T10:30:00.000000Z",
                "question": {
                    "id": 1234,
                    "question_text": "What is the capital of Indonesia?",
                    "quiz_id": 45,
                    "subtest_id": null,
                    "quiz": {
                        "id": 45,
                        "title": "Geography Practice Quiz"
                    },
                    "subtest": null
                }
            },
            {
                "id": 77,
                "customer_id": 123,
                "question_id": 1235,
                "report_reason": "Typo in question text",
                "status": "resolved",
                "admin_notes": "Fixed: Changed 'whitch' to 'which' in question text",
                "created_at": "2024-01-14T15:20:00.000000Z",
                "updated_at": "2024-01-15T09:45:00.000000Z",
                "question": {
                    "id": 1235,
                    "question_text": "Which of the following is correct?",
                    "quiz_id": null,
                    "subtest_id": 67,
                    "quiz": null,
                    "subtest": {
                        "id": 67,
                        "name": "Mathematics Subtest"
                    }
                }
            }
        ],
        "pagination": {
            "current_page": 1,
            "per_page": 10,
            "total": 2,
            "last_page": 1,
            "has_more": false
        }
    }
}
```

---

### 3. Get Specific Question Report

**GET** `/reports/{id}`

Get detailed information about a specific question report.

#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | integer | Report ID |

#### Response Example

**✅ Success Response (200)**
```json
{
    "success": true,
    "message": "Question report retrieved successfully",
    "data": {
        "id": 78,
        "customer_id": 123,
        "question_id": 1234,
        "report_reason": "Incorrect answer marked as correct",
        "status": "pending",
        "admin_notes": "The correct answer should be option B, but the system shows option A as correct.",
        "created_at": "2024-01-15T10:30:00.000000Z",
        "updated_at": "2024-01-15T10:30:00.000000Z",
        "question": {
            "id": 1234,
            "question_text": "What is the capital of Indonesia?",
            "question_body": "<p>Indonesia is a country in Southeast Asia. What is its capital city?</p>",
            "quiz_id": 45,
            "subtest_id": null,
            "quiz": {
                "id": 45,
                "title": "Geography Practice Quiz"
            },
            "subtest": null
        }
    }
}
```

**❌ Not Found (404)**
```json
{
    "success": false,
    "message": "Report not found or you do not have permission to view it."
}
```

---

## 📊 Report Status Values

| Status | Description |
|--------|-------------|
| `pending` | Report submitted, awaiting admin review |
| `reviewed` | Admin has reviewed but not yet resolved |
| `resolved` | Issue has been fixed/resolved |

---

## 🔧 Frontend Integration Examples

### React Component for Reporting

```jsx
import React, { useState } from 'react';
import { reportQuestion } from '../api/questionAPI';

const QuestionReportButton = ({ questionId }) => {
    const [isReporting, setIsReporting] = useState(false);
    const [reportReason, setReportReason] = useState('');
    const [additionalDetails, setAdditionalDetails] = useState('');

    const handleReport = async () => {
        setIsReporting(true);
        try {
            await reportQuestion({
                question_id: questionId,
                report_reason: reportReason,
                additional_details: additionalDetails
            });
            alert('Question reported successfully!');
        } catch (error) {
            alert('Error reporting question: ' + error.message);
        } finally {
            setIsReporting(false);
        }
    };

    return (
        <div className="question-report">
            <button onClick={() => setIsReporting(true)}>
                🚨 Report Issue
            </button>
            
            {isReporting && (
                <div className="report-modal">
                    <select 
                        value={reportReason} 
                        onChange={(e) => setReportReason(e.target.value)}
                    >
                        <option value="">Select reason...</option>
                        <option value="Incorrect answer marked as correct">Incorrect answer</option>
                        <option value="Typo in question text">Typo in question</option>
                        <option value="Missing or broken image">Broken image</option>
                        <option value="Unclear question wording">Unclear wording</option>
                        <option value="Wrong explanation provided">Wrong explanation</option>
                    </select>
                    
                    <textarea
                        placeholder="Additional details (optional)"
                        value={additionalDetails}
                        onChange={(e) => setAdditionalDetails(e.target.value)}
                        maxLength={2000}
                    />
                    
                    <button onClick={handleReport} disabled={!reportReason}>
                        Submit Report
                    </button>
                </div>
            )}
        </div>
    );
};
```

### API Service Functions

```javascript
// questionAPI.js
const API_BASE = process.env.REACT_APP_API_URL;

export const reportQuestion = async (reportData) => {
    const response = await fetch(`${API_BASE}/api/quizzes/questions/report`, {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${getAuthToken()}`,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(reportData)
    });
    
    if (!response.ok) {
        throw new Error('Failed to report question');
    }
    
    return response.json();
};

export const getMyReports = async (page = 1, perPage = 10) => {
    const response = await fetch(
        `${API_BASE}/api/quizzes/questions/my-reports?per_page=${perPage}&page=${page}`,
        {
            headers: {
                'Authorization': `Bearer ${getAuthToken()}`,
            },
        }
    );
    
    return response.json();
};

export const getReportDetails = async (reportId) => {
    const response = await fetch(
        `${API_BASE}/api/quizzes/questions/reports/${reportId}`,
        {
            headers: {
                'Authorization': `Bearer ${getAuthToken()}`,
            },
        }
    );
    
    return response.json();
};
```

---

## 📱 Mobile Implementation

### Flutter/Dart Example

```dart
class QuestionReportService {
    final String baseUrl = 'https://api.example.com';
    
    Future<Map<String, dynamic>> reportQuestion({
        required int questionId,
        required String reportReason,
        String? additionalDetails,
    }) async {
        final response = await http.post(
            Uri.parse('$baseUrl/api/quizzes/questions/report'),
            headers: {
                'Authorization': 'Bearer ${await getAuthToken()}',
                'Content-Type': 'application/json',
            },
            body: jsonEncode({
                'question_id': questionId,
                'report_reason': reportReason,
                'additional_details': additionalDetails,
            }),
        );
        
        if (response.statusCode == 201) {
            return jsonDecode(response.body);
        } else {
            throw Exception('Failed to report question');
        }
    }
}
```

---

## 🎯 Best Practices

### 1. **User Experience**
- Show clear report categories/reasons
- Provide immediate feedback after reporting
- Allow users to track their report status
- Display helpful tips for effective reporting

### 2. **Error Handling**
- Handle duplicate report attempts gracefully
- Provide clear validation error messages
- Implement retry mechanisms for network failures

### 3. **Data Validation**
- Validate question_id exists before reporting
- Sanitize user input for security
- Limit report reason length to prevent abuse

### 4. **Performance**
- Implement pagination for report history
- Cache frequently accessed report data
- Use debouncing for real-time search

---

## 📈 Analytics Integration

Track question reporting metrics:

```javascript
// Track report submission
analytics.track('Question Reported', {
    question_id: questionId,
    report_reason: reportReason,
    quiz_type: 'practice', // or 'tryout'
    category: 'Geography'
});

// Track report resolution
analytics.track('Question Report Resolved', {
    report_id: reportId,
    resolution_time_hours: timeDiff,
    was_valid: true
});
```

---

## 🔐 Security Considerations

- **Rate Limiting**: Prevent spam reporting
- **Authentication**: Ensure only authenticated users can report
- **Input Validation**: Sanitize all user inputs
- **Authorization**: Users can only view their own reports
- **Audit Trail**: Log all report actions for tracking

---

## 🚀 Future Enhancements

1. **Admin Dashboard**: Interface for admins to manage reports
2. **Batch Operations**: Allow admins to resolve multiple reports
3. **Report Categories**: More granular categorization
4. **Community Voting**: Allow users to vote on report validity
5. **Auto-Resolution**: Automatically resolve certain types of reports
6. **Report Analytics**: Dashboard showing report trends and patterns

---

## 📞 Support

For questions or issues with the Question Reporting API:
- 📧 Email: dev@lms.com
- 📱 WhatsApp: +62-xxx-xxx-xxxx
- 📋 GitHub Issues: Create an issue in the repository

---

*Last updated: January 2024* 