# Video Management System - API Examples

## Quick Reference

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/upload_video.php` | POST | Upload a video |
| `/api/list_videos.php` | GET | List videos with filters |
| `/api/get_filters.php` | GET | Get filter options |
| `/api/get_courts.php` | GET | Get courts by arena |

---

## Upload Video

### cURL

```bash
curl -X POST \
  -F "video=@/path/to/video.mp4" \
  -F "arena_id=1" \
  -F "court_id=1" \
  -F "type=match" \
  http://localhost/video-management-system/public/api/upload_video.php
```

### PHP

```php
<?php
$url = 'http://localhost/video-management-system/public/api/upload_video.php';

$postData = [
    'arena_id' => 1,
    'court_id' => 1,
    'type' => 'match',
    'video' => new CURLFile('/path/to/video.mp4', 'video/mp4', 'video.mp4')
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$result = json_decode($response, true);
print_r($result);
```

### JavaScript (Browser)

```javascript
async function uploadVideo(file, arenaId, courtId, type) {
    const formData = new FormData();
    formData.append('video', file);
    formData.append('arena_id', arenaId);
    formData.append('court_id', courtId);
    formData.append('type', type);

    const response = await fetch('/api/upload_video.php', {
        method: 'POST',
        body: formData
    });

    return await response.json();
}

// Usage with file input
document.getElementById('videoInput').addEventListener('change', async (e) => {
    const file = e.target.files[0];
    const result = await uploadVideo(file, 1, 1, 'match');
    console.log(result);
});
```

### Python

```python
import requests

url = 'http://localhost/video-management-system/public/api/upload_video.php'

files = {
    'video': ('video.mp4', open('/path/to/video.mp4', 'rb'), 'video/mp4')
}

data = {
    'arena_id': 1,
    'court_id': 1,
    'type': 'match'
}

response = requests.post(url, files=files, data=data)
print(response.json())
```

---

## List Videos

### cURL

```bash
# List all videos
curl "http://localhost/video-management-system/public/api/list_videos.php"

# With filters
curl "http://localhost/video-management-system/public/api/list_videos.php?arena_id=1&court_id=1&type=match&page=1&per_page=10"

# With search
curl "http://localhost/video-management-system/public/api/list_videos.php?search=championship"
```

### PHP

```php
<?php
$baseUrl = 'http://localhost/video-management-system/public/api/list_videos.php';

$params = [
    'arena_id' => 1,
    'type' => 'match',
    'page' => 1,
    'per_page' => 20
];

$url = $baseUrl . '?' . http_build_query($params);

$response = file_get_contents($url);
$result = json_decode($response, true);

foreach ($result['data']['items'] as $video) {
    echo $video['filename'] . ' - ' . $video['arena_name'] . "\n";
}
```

### JavaScript

```javascript
async function listVideos(filters = {}) {
    const params = new URLSearchParams(filters);
    const response = await fetch(`/api/list_videos.php?${params}`);
    return await response.json();
}

// Usage
const videos = await listVideos({
    arena_id: 1,
    type: 'match',
    page: 1
});

console.log(videos.data.items);
console.log(videos.data.pagination);
```

### Python

```python
import requests

url = 'http://localhost/video-management-system/public/api/list_videos.php'

params = {
    'arena_id': 1,
    'type': 'match',
    'page': 1,
    'per_page': 20
}

response = requests.get(url, params=params)
data = response.json()

for video in data['data']['items']:
    print(f"{video['filename']} - {video['arena_name']}")
```

---

## Get Filters

### cURL

```bash
curl "http://localhost/video-management-system/public/api/get_filters.php"
```

### JavaScript

```javascript
async function getFilters() {
    const response = await fetch('/api/get_filters.php');
    return await response.json();
}

const filters = await getFilters();
console.log('Arenas:', filters.data.arenas);
console.log('Courts:', filters.data.courts);
console.log('Types:', filters.data.types);
```

---

## Get Courts by Arena

### cURL

```bash
curl "http://localhost/video-management-system/public/api/get_courts.php?arena_id=1"
```

### JavaScript

```javascript
async function getCourtsByArena(arenaId) {
    const response = await fetch(`/api/get_courts.php?arena_id=${arenaId}`);
    return await response.json();
}

const courts = await getCourtsByArena(1);
console.log(courts.data);
```

---

## Response Handling

### Success Response Structure

```json
{
    "status": "success",
    "message": "Success",
    "data": { ... }
}
```

### Error Response Structure

```json
{
    "status": "error",
    "message": "Error description",
    "errors": {
        "field_name": "Validation error message"
    }
}
```

### JavaScript Error Handling

```javascript
async function apiRequest(url, options = {}) {
    try {
        const response = await fetch(url, options);
        const data = await response.json();

        if (data.status === 'error') {
            throw new Error(data.message);
        }

        return data;
    } catch (error) {
        console.error('API Error:', error.message);
        throw error;
    }
}
```

---

## Batch Upload Example

### JavaScript

```javascript
async function batchUpload(files, arenaId, courtId, type) {
    const results = [];

    for (const file of files) {
        try {
            const result = await uploadVideo(file, arenaId, courtId, type);
            results.push({ file: file.name, success: true, data: result });
        } catch (error) {
            results.push({ file: file.name, success: false, error: error.message });
        }
    }

    return results;
}
```

### PHP

```php
<?php
function batchUpload(array $videoPaths, int $arenaId, int $courtId, string $type): array
{
    $results = [];
    $url = 'http://localhost/video-management-system/public/api/upload_video.php';

    foreach ($videoPaths as $path) {
        $postData = [
            'arena_id' => $arenaId,
            'court_id' => $courtId,
            'type' => $type,
            'video' => new CURLFile($path, 'video/mp4')
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $results[] = [
            'file' => basename($path),
            'success' => $httpCode === 201,
            'response' => json_decode($response, true)
        ];
    }

    return $results;
}
```

---

## Integration with External Systems

### Webhook Notification (Example)

After uploading, notify an external system:

```php
<?php
// After successful upload
function notifyExternalSystem(array $videoData): void
{
    $webhookUrl = 'https://external-system.com/webhook/video-uploaded';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $webhookUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($videoData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer YOUR_API_KEY'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_exec($ch);
    curl_close($ch);
}
```
