# Plant Works Documents Integration Guide

## Files Created
1. `2026-06-15_add_plant_works_documents.sql` - Database migration
2. `works_document_upload.php` - Upload/delete/download handler
3. `works_documents_helper.php` - Helper functions
4. `works_documents_modal.php` - Modal component for viewing documents

## Integration Steps

### Step 1: Run Database Migration
Execute the migration file to create the `plant_list_works_documents` table:
```bash
php /CRUD/plant_list/plant_list_works/2026-06-15_add_plant_works_documents.sql
```
Or manually run in phpMyAdmin.

### Step 2: Update plantlist_update.php (Major Works Tab)

Add this include at the top after other requires:
```php
require_once $_SERVER['DOCUMENT_ROOT'] . '/CRUD/plant_list/plant_list_works/works_documents_modal.php';
```

Find the Major Works table (around line 1219) and add a "Documents" column header:
```html
<th>Documents</th>
```

In the loop that renders each row, add this column before the closing `</tr>`:
```html
<td width="80">
    <button class="btn btn-sm btn-info" onclick="openWorksDocumentsModal(<?= (int)$rowMW['plw_id'] ?>)" title="View Documents">
        <i class="fas fa-file"></i> 
        <span class="badge badge-primary" id="doc-count-<?= (int)$rowMW['plw_id'] ?>">0</span>
    </button>
</td>
```

Add this before the closing `</body>` tag:
```php
<?= render_works_documents_modal($pdo) ?>
```

Add this JavaScript at the end before `</body>`:
```html
<script>
// Load document counts for all works
function loadDocumentCounts() {
    const plwIds = Array.from(document.querySelectorAll('[id^="doc-count-"]'))
        .map(el => el.id.replace('doc-count-', ''));
    
    plwIds.forEach(plwId => {
        fetch('/CRUD/plant_list/plant_list_works/works_document_upload.php?action=list&plw_id=' + plwId)
            .then(response => response.json())
            .then(data => {
                const count = (data.documents || []).length;
                const badge = document.getElementById('doc-count-' + plwId);
                if (badge) {
                    badge.textContent = count;
                    badge.style.display = count > 0 ? 'inline-block' : 'none';
                }
            })
            .catch(err => console.error('Error loading doc count:', err));
    });
}

document.addEventListener('DOMContentLoaded', loadDocumentCounts);
</script>
```

### Step 3: Update plantlistworks_create.php

Add this include near the top:
```php
require_once $_SERVER['DOCUMENT_ROOT'] . '/CRUD/plant_list/plant_list_works/works_documents_helper.php';
```

After the form creation is saved (when you have the `plw_id`), before the success redirect, output the documents section:
```html
<h4>Attach Evidence Documents</h4>
<?= render_document_upload_ui($plw_id) ?>
```

Or integrate it into the form itself by adding before the submit button:
```php
<?php if (!empty($plw_id)): ?>
    <?= render_document_upload_ui($plw_id) ?>
<?php endif; ?>
```

### Step 4: Update plantlistworks_update.php

Add the same include and document UI:
```php
require_once $_SERVER['DOCUMENT_ROOT'] . '/CRUD/plant_list/plant_list_works/works_documents_helper.php';

// Then in the form, after displaying existing data:
<?= render_document_upload_ui($id) ?>
```

## Functionality

### Upload
- User selects file (any type, max 5MB)
- Enters document name/description
- File stored with timestamp + random name
- Metadata saved to database

### View (Major Works Tab)
- "Documents" button with count badge
- Click opens modal popup
- Shows all documents with size, upload date, uploader
- Download and delete buttons

### Download
- Click download button
- File downloads with original filename

### Delete
- Click delete button
- Confirms deletion
- File removed from disk and database

## File Structure
```
CRUD/plant_list/plant_list_works/
├── documents/                          (auto-created, stores files)
├── works_document_upload.php           (handler)
├── works_documents_helper.php          (UI rendering)
├── works_documents_modal.php           (modal component)
└── INTEGRATION_GUIDE.md                (this file)
```
