# OnlyOffice File Manager Integration - COMPLETE

## Implementation Summary (Option 1 with Enhancements)

### ✅ What Was Implemented:

#### 1. **"New" Dropdown Button in Toolbar**
**Location:** File Manager toolbar (next to "Upload" and "New Folder")

```
[📤 Upload] [📁 New Folder] [📄 New ▾]
                               ├─ 📝 Word Document (.docx)
                               ├─ 📊 Spreadsheet (.xlsx)
                               └─ 📽️ Presentation (.pptx)
```

**Features:**
- Creates blank Office documents
- Auto-opens in OnlyOffice editor
- Respects current folder location
- Respects current context filter

#### 2. **"Edit in OnlyOffice" Button**
**Location:** Toolbar (appears when editable file is selected)

**Behavior:**
- Hidden by default
- Appears when you select **one** Office file
- Supports: Word, Excel, PowerPoint, Text files
- Opens file in OnlyOffice editor

**Supported File Types:**
- **Word:** doc, docx, docm, dot, dotx, dotm, odt, rtf, txt
- **Excel:** xls, xlsx, xlsm, xlt, xltx, xltm, ods, csv
- **PowerPoint:** ppt, pptx, pptm, pot, potx, potm, odp

#### 3. **Smart UI Integration**
- Edit button shows/hides automatically based on selection
- Icons match Office document types (blue=Word, green=Excel, red=PowerPoint)
- Clean dropdown design matches existing UI
- No modal popups - creates and opens directly

---

## Architecture

### File Storage: **ERP Server** (Recommended & Implemented)

```
┌─────────────────────────────┐         ┌───────────────────────────┐
│  Your ERP Server            │         │  files.merph.mavrixone    │
│  (localhost/production)     │◄────────┤  (OnlyOffice Server)      │
│                             │  HTTPS  │                           │
│  ├─ uploads/files/          │         │  ├─ OnlyOffice Editor     │
│  │  ├─ document1.docx       │         │  └─ Document Server API   │
│  │  └─ spreadsheet1.xlsx    │         │                           │
│  ├─ Database (metadata)     │         └───────────────────────────┘
│  └─ File Manager UI         │
└─────────────────────────────┘
```

**How it works:**
1. User clicks "New" → Word Document
2. ERP creates blank .docx in `uploads/files/`
3. ERP redirects browser to OnlyOffice editor
4. OnlyOffice fetches file from ERP via `https://your-erp/onlyoffice/download/{id}`
5. User edits in browser
6. OnlyOffice saves changes back to ERP via `https://your-erp/onlyoffice/callback/{id}`
7. File is updated in `uploads/files/`

---

## Configuration

### OnlyOffice Server URL

**Current:** `https://files.merph.mavrixone`

**Change in:** `controllers/OnlyOfficeController.php` line 21

```php
$this->onlyofficeUrl = 'https://files.merph.mavrixone';
```

Or set environment variable:
```bash
export ONLYOFFICE_URL=https://files.merph.mavrixone
```

---

## Security (JWT)

✅ **JWT authentication configured** (via `core/OnlyOfficeJWT.php`)

**How it works:**
1. ERP signs editor config with JWT secret
2. OnlyOffice verifies JWT before downloading files
3. OnlyOffice signs callback requests with JWT
4. ERP verifies JWT before saving files

**Requirements:**
- Both ERP and OnlyOffice must use **same JWT secret**
- Configure in `core/OnlyOfficeJWT.php`

---

## Network Requirements

### ✅ Required (You Have These):

1. **OnlyOffice can reach your ERP via HTTPS**
   - Your ERP must be accessible at a public/network URL
   - Self-signed certificates are OK (OnlyOffice configured to accept)

2. **Your ERP can reach OnlyOffice**
   - `https://files.merph.mavrixone` must be accessible from ERP server
   - Port: 443 (HTTPS) or custom if configured

3. **Users' browsers can reach both**
   - Browser loads editor from `files.merph.mavrixone`
   - Browser loads ERP from your ERP URL

### URLs OnlyOffice Needs to Access:

```
https://your-erp-domain/onlyoffice/download/{fileId}  ← Fetch file
https://your-erp-domain/onlyoffice/callback/{fileId}  ← Save changes
```

**Important:** Replace `localhost` with actual domain/IP if OnlyOffice is on a different server.

---

## Files Modified

### 1. **views/file_manager/index.php**
- Added "New" dropdown button (lines 65-81)
- Added "Edit in OnlyOffice" button (lines 97-99)

### 2. **public/js/file-manager.js**
- Added `createNewDocument(type)` function (lines 1659-1700)
- Added `updateToolbarButtons()` enhancement (lines 1708-1743)
- Added selection change listener (lines 1746-1750)

### 3. **controllers/OnlyOfficeController.php**
- Updated OnlyOffice URL to `files.merph.mavrixone` (line 21)
- Existing functions already support JWT and remote server

### 4. **No changes needed to:**
- Database schema (uses existing `files` table)
- Routes (already configured)
- Models (FileManager already handles storage)

---

## Testing Checklist

### ✅ Test New Document Creation:

1. Go to File Manager: `http://localhost/files`
2. Click **"New"** dropdown
3. Select **"Word Document"**
4. Enter name (e.g., "Test Document")
5. ✅ Should redirect to OnlyOffice editor
6. ✅ Should show blank Word document
7. Type some text
8. ✅ Should auto-save
9. Close editor tab
10. ✅ File should appear in File Manager

### ✅ Test Edit Existing File:

1. Upload a .docx file to File Manager
2. Click checkbox to select it
3. ✅ "Edit in OnlyOffice" button should appear
4. Click **"Edit in OnlyOffice"**
5. ✅ Should open in editor
6. Make changes
7. ✅ Should save automatically
8. Download file to verify changes

### ✅ Test Smart Button Visibility:

- Select Word/Excel/PowerPoint file → Edit button shows
- Select PDF/image file → Edit button hidden
- Select multiple files → Edit button hidden
- Deselect all → Edit button hidden

---

## Troubleshooting

### "Download failed" in OnlyOffice Editor

**Cause:** OnlyOffice cannot reach your ERP

**Fix:**
1. Ensure your ERP has public/network URL (not `localhost`)
2. Update `base_url()` in your ERP config
3. Check firewall allows OnlyOffice server to reach ERP

### "Document could not be saved"

**Cause:** OnlyOffice cannot send saved file back to ERP

**Fix:**
1. Check callback URL is accessible from OnlyOffice server
2. Verify JWT secret matches on both servers
3. Check file permissions on `uploads/files/` directory (775 or 777)

### JWT Verification Failed

**Cause:** JWT secret mismatch

**Fix:**
1. Check `core/OnlyOfficeJWT.php` has correct secret
2. Ensure OnlyOffice server has same JWT secret
3. Restart OnlyOffice after changing JWT secret

### Self-Signed Certificate Errors

**Fix:** Configure PHP to accept self-signed certs:

```php
// In OnlyOfficeController callback method, add:
stream_context_set_default([
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
]);
```

---

## File Storage Alternative (Not Implemented)

If you want to store files on `files.merph.mavrixone` instead of your ERP:

**Pros:**
- Faster editing (no network download/upload)
- Reduced ERP server load

**Cons:**
- Requires building WebDAV or file storage API
- Files separated from ERP database
- More complex backup strategy

**Implementation needed:**
1. Install WebDAV server on `files.merph.mavrixone`
2. Mount WebDAV share in ERP
3. Update file paths to use WebDAV mount
4. Update FileManager model to use remote storage

---

## Next Steps (Optional Enhancements)

### 1. **Add File Icons in File List**
Show Word/Excel/PowerPoint icons for editable files

### 2. **Context Menu Integration**
Right-click file → "Edit in OnlyOffice"

### 3. **Collaborative Editing**
Multiple users can edit same document simultaneously (already supported by OnlyOffice)

### 4. **Document Templates**
Pre-populate new documents with company templates

### 5. **Version History UI**
Show file versions in File Manager (backend already tracks versions)

---

## Support & Documentation

- **OnlyOffice API Docs:** https://api.onlyoffice.com/editors/basic
- **JWT Configuration:** https://api.onlyoffice.com/editors/signature
- **Your Implementation:** `docs/ONLYOFFICE_INTEGRATION.md`

---

## Summary

✅ **Clean & Simple Integration Complete!**

**What Users See:**
- "New" button with dropdown (Word, Excel, PowerPoint)
- "Edit" button appears when selecting Office files
- Seamless editing experience
- Files stored in your ERP
- OnlyOffice provides the editor interface

**What You Manage:**
- Files: Your ERP server (`uploads/files/`)
- Metadata: Your ERP database (`files` table)
- OnlyOffice: Just the editor service (no file storage)

**Ready to Use!**
Navigate to File Manager and click "New" → Word Document to test.
