# File Manager Laravel Integration

This document describes the transformation of a standalone PHP file manager into a Laravel-integrated file management system.

## Architecture Overview

The file manager has been restructured into three main components following Laravel best practices:

### 1. Configuration (`config/file_manager.php`)
Centralized configuration for all file manager settings including:
- Root directory paths
- Security restrictions (file size limits, allowed extensions)
- MIME type mappings
- File categories
- API behavior settings
- Pagination options
- Thumbnail generation settings

### 2. Core Library (`app/Library/FileManager.php`)
The main business logic class that handles:
- Secure file operations with path validation
- Directory traversal protection
- File metadata extraction
- Upload processing with validation
- File listing with pagination and sorting
- Text file preview with encoding detection
- Comprehensive error handling and logging

### 3. API Controller (`app/Http/Controllers/Api/FileManagerController.php`)
RESTful API endpoints that provide:
- Input validation using Laravel's validator
- JSON responses with consistent format
- Proper HTTP status codes
- Activity logging for audit trails
- CORS support for cross-origin requests

## API Endpoints

All endpoints are prefixed with `/api/v1/file-manager/` and require API authentication.

### File Listing
```
GET /api/v1/file-manager/list
Parameters:
- dir: Directory path (optional, default: root)
- sort: Sort field (name|size|modified|type, default: name)
- order: Sort order (asc|desc, default: asc)
- page: Page number (default: 1)
- limit: Items per page (optional, uses config default)
- filter: Filter pattern for filenames (optional)

Response:
{
  "success": true,
  "data": {
    "items": [...], 
    "current_path": "uploads",
    "breadcrumbs": [...],
    "pagination": {...}
  }
}
```

### File Upload
```
POST /api/v1/file-manager/upload
Form Data:
- files: File(s) to upload (required)
- dir: Target directory (optional, default: root)

Response:
{
  "success": true,
  "uploaded": [...],
  "errors": [...],
  "total_uploaded": 2,
  "total_errors": 0
}
```

### File/Directory Deletion
```
DELETE /api/v1/file-manager/delete
JSON Body:
- path: Path to delete (required)

Response:
{
  "success": true,
  "message": "Item deleted successfully"
}
```

### File/Directory Rename
```
PUT /api/v1/file-manager/rename
JSON Body:
- path: Current path (required)
- name: New name (required)

Response:
{
  "success": true,
  "data": {...}, // Updated file info
  "message": "Item renamed successfully"
}
```

### Directory Creation
```
POST /api/v1/file-manager/mkdir
Form Data:
- path: Parent directory (optional, default: root)
- name: Directory name (required)

Response:
{
  "success": true,
  "data": {...}, // New directory info
  "message": "Directory created successfully"
}
```

### File/Directory Information
```
GET /api/v1/file-manager/info
Parameters:
- path: Path to file/directory (required)

Response:
{
  "success": true,
  "data": {
    "name": "example.txt",
    "path": "uploads/example.txt",
    "type": "file",
    "size": 1024,
    "modified": 1635789600,
    "extension": "txt",
    "mime_type": "text/plain",
    "category": "document",
    "is_image": false,
    "is_text": true,
    ...
  }
}
```

### Raw File Access
```
GET /api/v1/file-manager/raw
Parameters:
- path: File path (required)
- download: Force download (0|1, default: 0 for inline)

Response: Raw file content with appropriate headers
```

### Text File Preview
```
GET /api/v1/file-manager/preview
Parameters:
- path: Text file path (required)

Response:
{
  "success": true,
  "data": {
    "content": "file content...",
    "file_size": 1024,
    "preview_size": 1024,
    "is_truncated": false,
    "encoding": "UTF-8"
  }
}
```

### Statistics
```
GET /api/v1/file-manager/stats

Response:
{
  "success": true,
  "data": {
    "total_files": 150,
    "total_size": 52428800,
    "root_path": "/path/to/storage",
    "allowed_extensions": [...],
    "max_file_size": 10485760,
    "max_files_per_upload": 10
  }
}
```

## Security Features

### Path Validation
- All paths are normalized and validated against directory traversal attacks
- Files must exist within the configured root directory
- Real path resolution prevents symlink-based escapes

### File Upload Security
- Extension whitelist validation
- File size limits (configurable)
- MIME type detection and validation
- Automatic filename sanitization
- Collision detection with auto-renaming

### Access Control
- API authentication required for all endpoints
- Activity logging for audit trails
- Configurable CORS support
- Input validation on all parameters

### Error Handling
- Comprehensive exception handling
- Detailed logging without exposing sensitive information
- Consistent JSON error responses
- HTTP status code compliance

## Configuration Options

### Security Settings
```php
'security' => [
    'max_file_size' => 10 * 1024 * 1024, // 10MB
    'max_files_per_upload' => 10,
    'max_text_preview_bytes' => 1024 * 1024, // 1MB
],
```

### Allowed File Types
```php
'allowed_extensions' => [
    'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg',
    'pdf', 'doc', 'docx', 'txt', 'rtf',
    'zip', 'rar', '7z',
    'js', 'css', 'html', 'php', 'json',
    'mp4', 'avi', 'mov', 'mp3', 'wav'
],
```

### File Categories
```php
'categories' => [
    'image' => ['jpg', 'jpeg', 'png', 'gif', ...],
    'document' => ['pdf', 'doc', 'docx', 'txt', ...],
    'code' => ['js', 'css', 'php', 'py', ...],
    'archive' => ['zip', 'rar', '7z', ...],
    'media' => ['mp4', 'avi', 'mov', 'mp3', ...],
],
```

## Usage Examples

### Frontend Integration
```javascript
// List files
const response = await fetch('/api/v1/file-manager/list?dir=uploads&sort=name&order=asc');
const data = await response.json();

// Upload files
const formData = new FormData();
formData.append('files', file);
formData.append('dir', 'uploads');

const response = await fetch('/api/v1/file-manager/upload', {
    method: 'POST',
    body: formData
});

// Get file info
const response = await fetch('/api/v1/file-manager/info?path=uploads/example.txt');
const info = await response.json();
```

### Laravel Integration
```php
// Use in other controllers
$fileManager = new \Acelle\Library\FileManager();
$result = $fileManager->listFiles('uploads');

// Access via route
$url = route('api.file_manager.raw', ['path' => 'uploads/file.pdf']);
```

## Migration from Standalone Version

The transformation maintains API compatibility while adding Laravel-specific features:

1. **Path handling**: Uses Laravel's storage path functions
2. **Configuration**: Integrated with Laravel's config system
3. **Logging**: Uses Laravel's Log facade
4. **Validation**: Uses Laravel's Validator facade
5. **Responses**: Returns proper Laravel Response objects
6. **Authentication**: Integrated with Laravel's API authentication
7. **Routes**: Proper Laravel route registration with named routes

## Best Practices

### Error Handling
- Always check `success` field in responses
- Handle both client and server errors appropriately
- Log important operations for debugging

### File Operations
- Validate file types on client side for better UX
- Implement progress indicators for large uploads
- Use pagination for directories with many files
- Cache file listings when appropriate

### Security
- Never trust user input for paths
- Validate file types and sizes before upload
- Implement rate limiting for upload endpoints
- Monitor file system usage and implement quotas

### Performance
- Use streaming for large file downloads
- Implement thumbnail generation for images
- Consider CDN integration for public files
- Cache directory statistics for large directories