# Unified CloudStorageController - Documentation

## Description

The `CloudStorageController` has been refactored to unify all file and document management operations into a single controller, eliminating code duplication and providing a cleaner and more maintainable architecture.

## Unified Architecture

### 🎯 **Main Objective**

- **Eliminate duplication**: A single controller for all cloud storage operations
- **DRY Code**: Avoid logic repetition between controllers
- **Maintainability**: Easy maintenance and updates
- **Consistency**: Uniform behavior across all operations

### 📁 **Controller Structure**

```
CloudStorageController
├── Configuration Management
│   ├── index() - List configurations
│   ├── create() - Show configuration form
│   ├── show() - Show specific configuration
│   ├── store() - Save configuration
│   └── update() - Update configuration
├── File Management
│   ├── fileIndex() - List files
│   ├── fileCreate() - Show upload form
│   ├── fileUpload() - Upload file
│   ├── fileShow() - Show file
│   ├── fileEdit() - Edit file
│   ├── fileUpdate() - Update file
│   ├── fileDestroy() - Delete file
│   └── fileDownload() - Download file
├── Document Management
│   ├── documentIndex() - List documents
│   ├── documentCreate() - Show creation form
│   ├── documentStore() - Create document
│   ├── documentShow() - Show document
│   ├── documentEdit() - Edit document
│   ├── documentUpdate() - Update document
│   └── documentDestroy() - Delete document
└── Cloud Storage Operations
    ├── uploadFile() - Upload file to cloud storage
    ├── createDocument() - Create document in cloud storage
    ├── createSpreadsheet() - Create spreadsheet
    ├── listFiles() - List files
    ├── createFolder() - Create folder
    └── shareFile() - Share file
```

## Implemented Functionalities

### 🔧 **Configuration Management**

#### Configure Providers
```php
// Configure Google Workspace
POST /setup/cloud-storage
{
    "service_provider": "google",
    "service_account_key": "[JSON file]",
    "organization_domain": "company.com"
}

// Configure Microsoft 365
POST /setup/cloud-storage
{
    "service_provider": "microsoft",
    "client_id": "your_client_id",
    "client_secret": "your_client_secret",
    "tenant_id": "your_tenant_id"
}
```

#### Update Configuration
```php
PUT /setup/cloud-storage/{id}
{
    "is_update": "1",
    "configuration_id": "{id}",
    // ... other provider-specific fields
}
```

### 📁 **File Management**

#### List Files
```php
GET /files/
```

#### Upload File
```php
POST /files/store
Content-Type: multipart/form-data

{
    "file": [file],
    "name": "File name",
    "description": "Optional description",
    "path": "documents/report.pdf",
    "folder_id": "optional_folder_id",
    "provider": "google" // or "microsoft"
}
```

#### Download File
```php
GET /files/download/{media}
```

#### Delete File
```php
GET /files/destroy/{media}
```

### 📄 **Document Management**

#### List Documents
```php
GET /document/
```

#### Create Document
```php
GET /document/create?docname=My Document&documentType=document&actualUrl=/dashboard
```

#### Create Spreadsheet
```php
GET /document/create?docname=My Sheet&documentType=spreadsheet&actualUrl=/dashboard
```

#### Edit Document
```php
GET /document/edit/{document}
PUT /document/update/{document}
{
    "name": "New Name",
    "description": "Updated description"
}
```

#### Delete Document
```php
GET /document/destroy/{document}
```

### ☁️ **Cloud Storage Operations**

#### Upload File to Cloud Storage
```php
POST /setup/cloud-storage/upload
Content-Type: multipart/form-data

{
    "file": [file],
    "path": "documents/report.pdf",
    "folder_id": "optional_folder_id",
    "provider": "google"
}
```

#### Create Document in Cloud Storage
```php
POST /setup/cloud-storage/document
Content-Type: application/json

{
    "name": "My Document",
    "folder_id": "optional_folder_id",
    "provider": "google"
}
```

#### Create Spreadsheet in Cloud Storage
```php
POST /setup/cloud-storage/spreadsheet
Content-Type: application/json

{
    "name": "My Spreadsheet",
    "folder_id": "optional_folder_id",
    "provider": "google"
}
```

#### List Cloud Storage Files
```php
GET /setup/cloud-storage/files?path=/&provider=google
```

#### Create Folder in Cloud Storage
```php
POST /setup/cloud-storage/folder
Content-Type: application/json

{
    "name": "New Folder",
    "parent_folder_id": "optional_parent_id",
    "provider": "google"
}
```

#### Share File
```php
POST /setup/cloud-storage/share
Content-Type: application/json

{
    "document_id": "1ABC123...",
    "permissions": [
        {
            "type": "user",
            "role": "writer",
            "email": "user@company.com"
        }
    ],
    "provider": "google"
}
```

## Unification Advantages

### ✅ **Technical Benefits**

1. **DRY Code**: Elimination of code duplication
2. **Maintainability**: Single place for updates
3. **Consistency**: Uniform behavior
4. **Testing**: Easier to test
5. **Debugging**: Single entry point for debugging

### 🚀 **Functional Benefits**

1. **Multi-Provider Support**: Unified support for multiple providers
2. **Centralized Logging**: Centralized auditing of all operations
3. **Error Handling**: Consistent error handling strategy
4. **Validation**: Unified validations
5. **Responses**: Consistent response format

### 🔄 **Compatibility**

- **Existing Routes**: Maintains compatibility with existing routes
- **Existing Views**: No changes required in views
- **Legacy System**: Maintains fallback to existing system
- **Gradual Migration**: Allows migration without disrupting functionality

## Controller Migration

### 📋 **Replaced Controllers**

1. **MediaController** → `CloudStorageController` (`file*` methods)
2. **DocumentController** → `CloudStorageController` (`document*` methods)

### 🔄 **Updated Routes**

```php
// Before
Route::get('/', [MediaController::class, 'index'])->name('file.index');
Route::post('store', [MediaController::class, 'store'])->name('file.store');

// After
Route::get('/', [CloudStorageController::class, 'fileIndex'])->name('file.index');
Route::post('store', [CloudStorageController::class, 'fileUpload'])->name('file.store');
```

### 📝 **Migrated Methods**

#### MediaController → CloudStorageController
- `index()` → `fileIndex()`
- `create()` → `fileCreate()`
- `store()` → `fileUpload()`
- `show()` → `fileShow()`
- `edit()` → `fileEdit()`
- `update()` → `fileUpdate()`
- `destroy()` → `fileDestroy()`
- `download()` → `fileDownload()`

#### DocumentController → CloudStorageController
- `index()` → `documentIndex()`
- `create()` → `documentCreate()`
- `store()` → `documentStore()`
- `show()` → `documentShow()`
- `edit()` → `documentEdit()`
- `update()` → `documentUpdate()`
- `destroy()` → `documentDestroy()`
- `uploadFile()` → `uploadFile()`
- `listFiles()` → `listFiles()`
- `createFolder()` → `createFolder()`
- `shareDocument()` → `shareFile()`

## Configuration and Usage

### 🛠 **Required Configuration**

1. **Providers**: Configure at least one provider in `/setup/cloud-storage`
2. **Middleware**: Authentication and tenant verification
3. **Environment Variables**: For OAuth2 fallback

### 📊 **Logging and Auditing**

All operations are logged with provider information:

```php
Log::info('File uploaded via cloud service', [
    'document_id' => $document->id,
    'file_id' => $fileId,
    'path' => $path,
    'size' => $file->getSize(),
    'user_id' => auth()->id(),
    'provider' => $config->provider->value
]);
```

### 🎯 **Error Handling**

Consistent JSON responses:

```json
{
    "success": true/false,
    "message": "Result description",
    "data": { /* additional data */ }
}
```

## Next Steps

### 🚀 **Future Improvements**

1. **Configuration Cache**: Cache configurations for better performance
2. **Operation Queue**: Asynchronous operations for large files
3. **Webhooks**: Real-time notifications
4. **Synchronization**: Synchronization between providers
5. **Metrics**: Usage and performance dashboard

### 📈 **Monitoring**

- **Centralized Logs**: All operations in one place
- **Provider Metrics**: Usage and performance per provider
- **Alerts**: Error and issue notifications
- **Reports**: Activity and usage reports

## Usage Examples

### 🔄 **Complete Workflow**

```php
// 1. Configure providers
$config = CloudServiceConfiguration::where('provider', 'google')->first();

// 2. Create folder
$response = Http::post('/setup/cloud-storage/folder', [
    'name' => 'Project ABC',
    'provider' => 'google'
]);
$folderId = $response->json()['folder_id'];

// 3. Upload file
$response = Http::attach('file', $fileContents, 'document.pdf')
    ->post('/setup/cloud-storage/upload', [
        'path' => 'Project ABC/document.pdf',
        'folder_id' => $folderId,
        'provider' => 'google'
    ]);

// 4. Create document
$response = Http::post('/setup/cloud-storage/document', [
    'name' => 'Specifications',
    'folder_id' => $folderId,
    'provider' => 'google'
]);

// 5. Share
$response = Http::post('/setup/cloud-storage/share', [
    'document_id' => $response->json()['document_id'],
    'permissions' => [
        ['type' => 'user', 'role' => 'writer', 'email' => 'team@company.com']
    ],
    'provider' => 'google'
]);
```

This unified architecture provides a solid foundation for complete cloud storage management, eliminating code duplication and providing a consistent experience for all users.
