# DocumentController - Improved Usage Guide

## Description

The `DocumentController` has been refactored to integrate the new cloud services system, providing improved functionality for document creation, file upload, and management of multiple cloud storage providers.

## Main Features

### ✅ **Implemented Functionalities**

1. **Document Creation** - Google Docs and Sheets
2. **File Upload** - Up to 100MB
3. **File Listing** - Folder navigation
4. **Folder Creation** - File organization
5. **Document Sharing** - Granular permissions
6. **Document Management** - Complete CRUD
7. **Audit Logging** - Operation tracking
8. **OAuth2 Fallback** - Compatibility with existing system
9. **Multi-Provider Support** - Google Workspace and Microsoft 365

### 🔄 **Compatibility**

- **New System**: Uses service account (recommended)
- **Legacy System**: Falls back to OAuth2 if no configuration exists
- **Multiple Providers**: Selection between Google and Microsoft

## Controller Usage

### 1. **Document Creation**

#### Create Google Doc
```php
// Via URL with parameters
GET /document/create?docname=My Document&documentType=document&actualUrl=/dashboard

// Via direct POST
POST /document/store
{
    "folder_id": "optional_folder_id"
}
```

#### Create Google Sheets
```php
// Via URL with parameters
GET /document/create?docname=My Spreadsheet&documentType=spreadsheet&actualUrl=/dashboard

// Via direct POST
POST /document/store
{
    "folder_id": "optional_folder_id"
}
```

### 2. **File Upload with Provider Selection**

```php
POST /document/upload
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"
}
```

**Response:**
```json
{
    "success": true,
    "message": "File uploaded successfully",
    "document": {
        "id": 1,
        "name": "report.pdf",
        "google_id": "1ABC123...",
        "url": "https://drive.google.com/file/d/1ABC123.../view",
        "path": "documents/report.pdf",
        "size": 1024000,
        "mime_type": "application/pdf"
    },
    "file_id": "1ABC123...",
    "url": "https://drive.google.com/file/d/1ABC123.../view"
}
```

### 3. **File Listing by Provider**

```php
GET /document/files?path=/&provider=google
GET /document/files?path=/&provider=microsoft
```

**Response:**
```json
{
    "success": true,
    "files": [
        {
            "id": "1ABC123...",
            "name": "My Document",
            "type": "application/vnd.google-apps.document",
            "size": null,
            "modified": "2024-01-15T10:30:00Z",
            "is_folder": false
        },
        {
            "id": "2DEF456...",
            "name": "Projects Folder",
            "type": "application/vnd.google-apps.folder",
            "size": null,
            "modified": "2024-01-14T15:20:00Z",
            "is_folder": true
        }
    ]
}
```

### 4. **Folder Creation**

```php
POST /document/folder
Content-Type: application/json

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

**Response:**
```json
{
    "success": true,
    "message": "Folder created successfully",
    "folder_id": "3GHI789..."
}
```

### 5. **Document Sharing**

```php
POST /document/share
Content-Type: application/json

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

**Response:**
```json
{
    "success": true,
    "message": "Document shared successfully"
}
```

### 6. **Document Management**

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

#### View Document
```php
GET /document/show/{id}
```

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

#### Delete Document
```php
DELETE /document/destroy/{id}
```

## Integration in Views

### Upload Form Example with Provider Selection

```blade
<form action="{{ route('document.upload') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="mb-4">
        <label for="file" class="block text-sm font-medium text-gray-700">File</label>
        <input type="file" name="file" id="file" class="mt-1 block w-full" required>
    </div>
    
    <div class="mb-4">
        <label for="name" class="block text-sm font-medium text-gray-700">Name</label>
        <input type="text" name="name" id="name" class="mt-1 block w-full">
    </div>
    
    <div class="mb-4">
        <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
        <textarea name="description" id="description" class="mt-1 block w-full"></textarea>
    </div>
    
    <div class="mb-4">
        <label for="path" class="block text-sm font-medium text-gray-700">Path</label>
        <input type="text" name="path" id="path" value="documents/" class="mt-1 block w-full" required>
    </div>
    
    <!-- Provider Selector -->
    @if($cloudConfigs->count() > 0)
    <div class="mb-4">
        <label for="provider" class="block text-sm font-medium text-gray-700">Storage Provider</label>
        <select name="provider" id="provider" class="mt-1 block w-full" required>
            @foreach($cloudConfigs as $config)
                <option value="{{ $config->provider->value }}" 
                        {{ $defaultConfig && $defaultConfig->id === $config->id ? 'selected' : '' }}>
                    {{ $config->provider->getName() }}
                    @if($config->organization_domain)
                        ({{ $config->organization_domain }})
                    @endif
                </option>
            @endforeach
        </select>
    </div>
    @endif
    
    <div class="mb-4">
        <label for="folder_id" class="block text-sm font-medium text-gray-700">Folder (Optional)</label>
        <select name="folder_id" id="folder_id" class="mt-1 block w-full">
            <option value="">Root folder</option>
        </select>
    </div>
    
    <button type="submit" class="btn btn-primary">Upload File</button>
</form>
```

### JavaScript/AJAX Example

```javascript
// Upload file with provider selection
async function uploadFile(file, path, provider) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('path', path);
    formData.append('provider', provider);
    formData.append('_token', document.querySelector('meta[name=csrf-token]').content);

    try {
        const response = await fetch('/document/upload', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            console.log('File uploaded:', result.document);
            // Show success message
        } else {
            console.error('Error:', result.message);
            // Show error message
        }
    } catch (error) {
        console.error('Network error:', error);
    }
}

// List files by provider
async function listFiles(path = '/', provider = 'google') {
    try {
        const response = await fetch(`/document/files?path=${encodeURIComponent(path)}&provider=${provider}`);
        const result = await response.json();
        
        if (result.success) {
            displayFiles(result.files);
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

// Load folders from selected provider
async function loadFolders(provider) {
    try {
        const response = await fetch(`/document/files?path=/&provider=${provider}`);
        const result = await response.json();
        
        if (result.success) {
            const folderSelect = document.getElementById('folder_id');
            const folders = result.files.filter(file => file.is_folder);
            
            folderSelect.innerHTML = '<option value="">Root folder</option>';
            folders.forEach(folder => {
                const option = document.createElement('option');
                option.value = folder.id;
                option.textContent = folder.name;
                folderSelect.appendChild(option);
            });
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

// Handle provider change
document.getElementById('provider').addEventListener('change', function(e) {
    const selectedProvider = e.target.value;
    loadFolders(selectedProvider);
});
```

## Required Configuration

### 1. **Provider Configuration**

Make sure you have at least one provider configured at:
```
/setup/cloud-storage
```

**Supported Providers:**
- **Google Workspace**: Service account with Drive permissions
- **Microsoft 365**: App registration with Graph API permissions

### 2. **Environment Variables (OAuth2 Fallback)**

```env
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_REDIRECT_URI=your_redirect_uri
```

### 3. **Middleware**

The controller uses:
- `auth` - Authentication required
- `CheckSubdomain` - Tenant verification

## Logging and Auditing

All operations are automatically logged:

```php
Log::info('Document created via cloud service', [
    'document_id' => $document->id,
    'google_id' => $documentId,
    'type' => $documentType,
    'user_id' => auth()->id(),
    'provider' => $config->provider->value
]);
```

## Error Handling

### Common Errors

1. **"Cloud service not configured"**
   - Configure at least one provider at `/setup/cloud-storage`

2. **"Cloud service not configured for provider: microsoft"**
   - The selected provider is not configured
   - Verify the specific provider configuration

3. **"File too large"**
   - Current limit: 100MB
   - Consider implementing chunked uploads for larger files

4. **"Invalid permissions"**
   - Verify that the service account has permissions in the selected provider

### Error Responses

```json
{
    "success": false,
    "message": "Error description"
}
```

## New System Advantages

### ✅ **Implemented Improvements**

1. **Multi-Provider Support**: Support for Google and Microsoft
2. **Service Account**: More secure and reliable than OAuth2
3. **Complete Logging**: Auditing of all operations
4. **Error Handling**: Consistent and informative responses
5. **Validation**: Robust input validation
6. **Compatibility**: Maintains existing functionality
7. **Scalability**: Prepared for multiple providers

### 🔄 **Gradual Migration**

- The system automatically detects if there is a service account configuration
- If not, uses the existing OAuth2 system
- Allows migration without disrupting functionality
- Support for multiple simultaneous providers

## Next Steps

### 🚀 **Future Improvements**

1. **Support for more providers** (Dropbox, Box, etc.)
2. **Large file uploads** (>100MB)
3. **Operation progress**
4. **File search**
5. **Document versions**
6. **Real-time collaboration**
7. **Synchronization between providers**

### 📊 **Monitoring**

- Implement usage dashboard per provider
- Performance metrics
- Error alerts
- Activity reports

## Complete Usage Examples

### Complete Workflow with Multiple Providers

```php
// 1. Create project folder in Google
$folderResponse = Http::post('/document/folder', [
    'name' => 'Project ABC',
    'provider' => 'google'
]);
$googleFolderId = $folderResponse->json()['folder_id'];

// 2. Create project folder in Microsoft
$folderResponse = Http::post('/document/folder', [
    'name' => 'Project ABC',
    'provider' => 'microsoft'
]);
$microsoftFolderId = $folderResponse->json()['folder_id'];

// 3. Create document in Google
$docResponse = Http::post('/document/store', [
    'folder_id' => $googleFolderId,
    'provider' => 'google'
]);

// 4. Upload files to both providers
$uploadResponse = Http::attach('file', $fileContents, 'specifications.pdf')
    ->post('/document/upload', [
        'path' => 'Project ABC/specifications.pdf',
        'folder_id' => $googleFolderId,
        'provider' => 'google'
    ]);

$uploadResponse = Http::attach('file', $fileContents, 'specifications.pdf')
    ->post('/document/upload', [
        'path' => 'Project ABC/specifications.pdf',
        'folder_id' => $microsoftFolderId,
        'provider' => 'microsoft'
    ]);

// 5. Share with team in both providers
$shareResponse = Http::post('/document/share', [
    'document_id' => $docResponse->json()['document']['google_id'],
    'permissions' => [
        ['type' => 'user', 'role' => 'writer', 'email' => 'team@company.com']
    ],
    'provider' => 'google'
]);
```

This controller provides a solid foundation for complete document management with support for multiple cloud storage providers, with advanced functionality and compatibility with the existing system.
