# Getting Started - Unified File Upload System

## Step 1: Run the Migration (Required First!)

```bash
cd /Users/rpmbbu/LocalPHPStorm/m1_erp_web
mysql -u rpmbbu -p brickwal_m1_ds < database/migrations/030_unified_file_uploads.sql
```

Enter your database password when prompted.

## Step 2: Verify Installation

```bash
mysql -u rpmbbu -p brickwal_m1_ds -e "SHOW TABLES LIKE 'file_uploads';"
mysql -u rpmbbu -p brickwal_m1_ds -e "SHOW TABLES LIKE 'storage_quotas';"
```

You should see both tables listed.

## Step 3: Access Test Pages

Once logged into your ERP system, visit these URLs:

### Main Test Page
**URL:** `http://your-domain/file-upload-test`

This page has 3 test forms:
1. **Test 1: Single File Upload** - Blue card on left
   - Tests the `upload_file()` helper function
   - Try uploading any document, image, or archive
   - Select file type and add description

2. **Test 2: Multiple Files** - Green card in middle
   - Tests the `upload_multiple()` helper function
   - Select multiple files (hold Ctrl/Cmd)
   - All files uploaded at once with individual results

3. **Test 3: Image + Thumbnail** - Yellow card on right
   - Tests `FileUploadHandler` class directly
   - Upload an image (JPG, PNG, GIF, WEBP)
   - Automatically generates 200x200 thumbnail

### Statistics Page
**URL:** `http://your-domain/file-upload-test/stats`

View detailed statistics:
- Files per context
- Storage usage
- Recent uploads across all contexts
- Storage quotas

## What to Test

### Test 1: Basic Upload
1. Go to test page
2. In the blue card (Test 1), select any file
3. Choose file type (document/image/archive)
4. Add description
5. Click "Upload Single File"
6. You'll see success message with file ID, path, size, MIME type

### Test 2: Multiple Upload
1. In the green card (Test 2), click "Choose Files"
2. Hold Ctrl (Windows) or Cmd (Mac) and select 3-5 files
3. Click "Upload Multiple Files"
4. See results for each file (success/fail)

### Test 3: Image with Thumbnail
1. In the yellow card (Test 3), select an image
2. Click "Upload Image"
3. Check the "Recent Uploads" table below
4. Look for "Yes" in the Thumbnail column
5. Download the file to verify it works

### Test 4: View All Files
Scroll down to "Recent Test Uploads" table to see:
- All uploaded test files
- File details (name, type, size, entity, date)
- Thumbnail status
- Download and delete buttons

### Test 5: Storage Stats
1. Click "View Statistics" button (top right)
2. See storage usage by context
3. View quotas for each context
4. Browse recent uploads across all modules

## Database Verification

Check the database to see tracked files:

```sql
-- View all test uploads
SELECT * FROM file_uploads WHERE context = 'test' ORDER BY created_at DESC;

-- Check storage quotas
SELECT * FROM storage_quotas;

-- View upload statistics
SELECT * FROM v_file_upload_stats;

-- Check for thumbnails
SELECT id, original_filename, thumbnail_path 
FROM file_uploads 
WHERE thumbnail_path IS NOT NULL;
```

## Example URLs (Replace with Your Domain)

- **Local Development:**
  - http://localhost/m1_erp_web/public/file-upload-test
  - http://localhost/m1_erp_web/public/file-upload-test/stats

- **Production/Server:**
  - http://your-domain.com/file-upload-test
  - http://your-domain.com/file-upload-test/stats

## Features to Test

✅ **Single file upload** - Helper function `upload_file()`  
✅ **Multiple file upload** - Helper function `upload_multiple()`  
✅ **Image thumbnail generation** - Automatic 200x200 thumbnail  
✅ **File validation** - MIME type, size, extension checking  
✅ **Database tracking** - All uploads logged to `file_uploads` table  
✅ **Storage quotas** - Automatic tracking per context  
✅ **Download files** - Click download button in table  
✅ **Delete files** - Physical file + database record  
✅ **File metadata** - Description, tags, checksum, etc.  

## Expected Behavior

### Successful Upload
- Green success message appears at top
- File details displayed (ID, path, size, MIME)
- File appears in "Recent Uploads" table
- File saved to `uploads/test/` directory
- Database record created in `file_uploads` table

### Failed Upload
- Red error message appears with reason
- Common errors:
  - "Invalid file type" - Wrong file extension/MIME
  - "File size exceeds maximum" - File too large
  - "File extension does not match file content" - Security check failed

### Thumbnail Generation
- Only for images (JPG, PNG, GIF, WEBP)
- Creates thumb_filename.ext in same directory
- Maintains aspect ratio (max 200x200)
- "Yes" badge shows in Recent Uploads table

## Troubleshooting

### "No file uploaded" Error
- Make sure form has `enctype="multipart/form-data"`
- Check that file input name matches controller expectation
- Verify file was actually selected

### "Failed to move uploaded file"
- Check `/uploads/test/` directory permissions (should be 0755)
- Create directory manually: `mkdir -p uploads/test && chmod 755 uploads/test`
- Check disk space

### "Invalid CSRF token"
- Refresh the page and try again
- Check that `<?= csrf_field() ?>` is in the form
- Verify cookies are enabled in browser

### Page Not Found (404)
- Run migration first (Step 1 above)
- Clear any cache if applicable
- Check that routes were added to `public/index.php`

### Database Errors
- Verify migration ran successfully
- Check `file_uploads` and `storage_quotas` tables exist
- Verify database user has INSERT permissions

## Next Steps After Testing

Once you've confirmed uploads work:

1. **Review the code** in `controllers/FileUploadTestController.php`
2. **Check implementation** in `core/FileUploadHandler.php`
3. **Read the documentation:**
   - `docs/UNIFIED_FILE_UPLOAD_GUIDE.md` - Complete guide
   - `docs/FILE_UPLOAD_QUICK_REFERENCE.md` - Quick reference
   - `docs/FILE_UPLOAD_ANALYSIS_SUMMARY.md` - Benefits & analysis

4. **Start using in production:**
   - Use `upload_file()` helper in your controllers
   - Migrate existing upload code gradually
   - Add to new features immediately

## Quick Code Example

After testing, use this pattern in your controllers:

```php
// In any controller
$result = upload_file($_FILES['document'], 'crm', 'customer', $customerId, [
    'type' => 'document',
    'description' => $_POST['description'] ?? null
]);

if ($result['success']) {
    // Save file_path to your entity
    $this->model->update($entityId, [
        'document_path' => $result['file_path']
    ]);
    Session::setFlash('success', 'File uploaded!');
} else {
    Session::setFlash('error', $result['error']);
}
```

That's it - 8 lines instead of 40+!

## Support

Questions? Check:
- `docs/UNIFIED_FILE_UPLOAD_GUIDE.md` - Complete documentation
- `docs/FILE_UPLOAD_QUICK_REFERENCE.md` - Quick lookup
- Database schema in `database/migrations/030_unified_file_uploads.sql`
- Source code in `core/FileUploadHandler.php`

---

**You're all set! Visit the test page and start uploading files to see the system in action.**
