# Video Management System - Deployment Guide

## Table of Contents
1. [System Requirements](#system-requirements)
2. [Installation Steps](#installation-steps)
3. [Database Setup](#database-setup)
4. [Configuration](#configuration)
5. [CRON Setup](#cron-setup)
6. [API Documentation](#api-documentation)
7. [Security Considerations](#security-considerations)
8. [Troubleshooting](#troubleshooting)

---

## System Requirements

- **Server**: Linux VPS (Hostinger or similar)
- **Web Server**: Apache 2.4+ with mod_rewrite enabled
- **PHP**: 8.0 or higher
- **MySQL**: 5.7+ or MariaDB 10.3+
- **Required PHP Extensions**:
  - PDO
  - PDO_MySQL
  - fileinfo
  - json

---

## Installation Steps

### 1. Upload Files

Upload the entire `video-management-system` directory to your server's web root:

```bash
# Example using SCP
scp -r video-management-system user@your-server:/var/www/html/

# Or using SFTP/FTP through Hostinger's file manager
```

### 2. Set Directory Permissions

```bash
# Navigate to project directory
cd /var/www/html/video-management-system

# Set proper ownership (adjust user/group as needed)
sudo chown -R www-data:www-data .

# Set directory permissions
sudo chmod -R 755 .

# Set writable permissions for storage
sudo chmod -R 775 storage/

# Ensure logs directory is writable
mkdir -p storage/logs
sudo chmod -R 775 storage/logs
```

### 3. Enable Apache Modules

```bash
# Enable required modules
sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod expires
sudo a2enmod deflate

# Restart Apache
sudo systemctl restart apache2
```

### 4. Configure Virtual Host (Optional)

Create a virtual host configuration:

```apache
<VirtualHost *:80>
    ServerName videos.yourdomain.com
    DocumentRoot /var/www/html/video-management-system/public

    <Directory /var/www/html/video-management-system/public>
        AllowOverride All
        Require all granted
    </Directory>

    # Alias for video storage
    Alias /storage /var/www/html/video-management-system/storage
    <Directory /var/www/html/video-management-system/storage>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/video-system-error.log
    CustomLog ${APACHE_LOG_DIR}/video-system-access.log combined
</VirtualHost>
```

---

## Database Setup

### 1. Create Database

Using phpMyAdmin or MySQL CLI:

```sql
CREATE DATABASE video_management
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;

CREATE USER 'video_user'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON video_management.* TO 'video_user'@'localhost';
FLUSH PRIVILEGES;
```

### 2. Import Schema

Using phpMyAdmin:
1. Select the `video_management` database
2. Go to "Import" tab
3. Upload `sql/001_create_database.sql`
4. Click "Go"

Using CLI:
```bash
mysql -u video_user -p video_management < sql/001_create_database.sql
```

### 3. Import Sample Data (Optional)

```bash
mysql -u video_user -p video_management < sql/002_seed_data.sql
```

---

## Configuration

### 1. Database Configuration

Edit `config/database.php`:

```php
<?php
return [
    'host'     => 'localhost',
    'port'     => 3306,
    'dbname'   => 'video_management',
    'username' => 'video_user',          // Change this
    'password' => 'your_secure_password', // Change this
    'charset'  => 'utf8mb4',
    'options'  => [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]
];
```

### 2. Application Configuration

Edit `config/app.php` as needed:

```php
<?php
return [
    'name' => 'Video Management System',
    'base_url' => 'https://videos.yourdomain.com',  // Update this

    'video' => [
        'max_file_size' => 524288000,    // 500MB
        'retention_days' => 30,           // 30 days
        'min_free_space' => 1073741824,  // 1GB minimum
    ],
    // ...
];
```

### 3. PHP Configuration

Update `php.ini` (or create `.user.ini` in public folder):

```ini
; Increase upload limits for large video files
upload_max_filesize = 500M
post_max_size = 512M
max_execution_time = 300
max_input_time = 300
memory_limit = 256M
```

---

## CRON Setup

### Add Cleanup Cron Job

The cleanup script runs daily to delete videos older than 30 days.

```bash
# Open crontab editor
crontab -e

# Add the following line (runs at 3 AM daily)
0 3 * * * /usr/bin/php /var/www/html/video-management-system/scripts/clean_old_videos.php >> /var/log/video-cleanup.log 2>&1
```

### Hostinger VPS Cron Setup

1. Log into Hostinger hPanel
2. Go to "Advanced" > "Cron Jobs"
3. Add new cron job:
   - Command: `/usr/bin/php /home/user/public_html/video-management-system/scripts/clean_old_videos.php`
   - When: Once a day (or custom: `0 3 * * *`)

### Verify Cron is Working

```bash
# Check cron logs
tail -f /var/log/video-cleanup.log

# Run manually to test
php /var/www/html/video-management-system/scripts/clean_old_videos.php
```

---

## API Documentation

### Upload Video

**Endpoint**: `POST /api/upload_video.php`

**Content-Type**: `multipart/form-data`

**Parameters**:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| video | file | Yes | MP4 video file |
| arena_id | int | Yes | Arena identifier |
| court_id | int | Yes | Court identifier |
| type | string | Yes | Video type/category |

**Example (cURL)**:
```bash
curl -X POST \
  -F "video=@/path/to/video.mp4" \
  -F "arena_id=1" \
  -F "court_id=1" \
  -F "type=match" \
  https://videos.yourdomain.com/api/upload_video.php
```

**Success Response** (201):
```json
{
    "status": "success",
    "message": "Video uploaded successfully",
    "data": {
        "id": 1,
        "filename": "20240115_143022_abc123def456.mp4",
        "arena_id": 1,
        "court_id": 1,
        "type": "match"
    }
}
```

**Error Response** (400/500):
```json
{
    "status": "error",
    "message": "Invalid file type. Only MP4 videos are allowed"
}
```

---

### List Videos

**Endpoint**: `GET /api/list_videos.php`

**Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| arena_id | int | No | Filter by arena |
| court_id | int | No | Filter by court |
| type | string | No | Filter by type |
| search | string | No | Search text |
| page | int | No | Page number (default: 1) |
| per_page | int | No | Items per page (default: 20, max: 100) |

**Example**:
```bash
curl "https://videos.yourdomain.com/api/list_videos.php?arena_id=1&type=match&page=1"
```

**Response** (200):
```json
{
    "status": "success",
    "message": "Success",
    "data": {
        "items": [
            {
                "id": 1,
                "arena_id": 1,
                "court_id": 1,
                "type": "match",
                "filename": "20240115_143022_abc123.mp4",
                "file_size": 52428800,
                "created_at": "2024-01-15 14:30:22",
                "arena_name": "Arena Central",
                "court_name": "Quadra 1",
                "url": "../storage/videos/arena_1/court_1/20240115_143022_abc123.mp4"
            }
        ],
        "pagination": {
            "total": 45,
            "per_page": 20,
            "current_page": 1,
            "total_pages": 3,
            "has_more": true
        }
    }
}
```

---

### Get Filters

**Endpoint**: `GET /api/get_filters.php`

Returns available filter options with video counts.

**Response**:
```json
{
    "status": "success",
    "data": {
        "arenas": [
            {"id": 1, "name": "Arena Central", "video_count": 15}
        ],
        "courts": [
            {"id": 1, "arena_id": 1, "name": "Quadra 1", "arena_name": "Arena Central", "video_count": 5}
        ],
        "types": ["match", "training", "highlight"]
    }
}
```

---

### Get Courts by Arena

**Endpoint**: `GET /api/get_courts.php?arena_id={id}`

**Response**:
```json
{
    "status": "success",
    "data": [
        {"id": 1, "arena_id": 1, "name": "Quadra 1"},
        {"id": 2, "arena_id": 1, "name": "Quadra 2"}
    ]
}
```

---

## Security Considerations

### 1. Database Credentials

- Never commit real credentials to version control
- Use environment variables in production
- Create a separate database user with minimal permissions

### 2. File Upload Security

- Only MP4 files are accepted
- MIME type is validated server-side
- Files are renamed with unique identifiers
- PHP execution is disabled in storage directory

### 3. Directory Protection

Protected directories (via .htaccess):
- `/app` - Application code
- `/config` - Configuration files
- `/scripts` - CLI scripts
- `/storage/logs` - Log files

### 4. SQL Injection Prevention

- All queries use PDO prepared statements
- No raw SQL with user input

### 5. XSS Prevention

- All output is escaped with `htmlspecialchars()`
- JavaScript uses `textContent` instead of `innerHTML`

### 6. HTTPS

Configure SSL/TLS:
```bash
# Using Let's Encrypt
sudo certbot --apache -d videos.yourdomain.com
```

---

## Troubleshooting

### Videos Not Uploading

1. Check PHP upload limits:
   ```bash
   php -i | grep -E "upload_max_filesize|post_max_size"
   ```

2. Check storage directory permissions:
   ```bash
   ls -la storage/videos/
   ```

3. Check available disk space:
   ```bash
   df -h
   ```

### Database Connection Errors

1. Verify credentials in `config/database.php`
2. Check MySQL is running:
   ```bash
   sudo systemctl status mysql
   ```

3. Test connection:
   ```bash
   mysql -u video_user -p -e "SELECT 1"
   ```

### 500 Internal Server Error

1. Check Apache error log:
   ```bash
   tail -f /var/log/apache2/error.log
   ```

2. Enable PHP error display temporarily:
   ```php
   ini_set('display_errors', 1);
   error_reporting(E_ALL);
   ```

### CRON Not Running

1. Check cron service:
   ```bash
   sudo systemctl status cron
   ```

2. Check cron logs:
   ```bash
   grep CRON /var/log/syslog
   ```

3. Verify PHP path:
   ```bash
   which php
   ```

### Videos Not Playing

1. Check file permissions on video files
2. Verify Apache can serve MP4 files
3. Check browser console for errors
4. Ensure video URL is accessible

---

## Support

For issues and feature requests, please contact your system administrator or development team.
