<?php
/** @var array $attachments  list from Attachment::forOwner() */
/** @var string $ownerType   'asset' | 'incident' | 'work_order' | 'expense' */
/** @var int    $ownerId */
/** @var string $csrf */
$attachments = $attachments ?? [];
?>
<div class="rs-card p-3 mt-3">
    <h6 class="fw-bold mb-2"><i class="fas fa-paperclip me-1 text-primary"></i>Attachments</h6>

    <?php if (!empty($attachments)): ?>
        <div class="table-responsive">
            <table class="table table-sm table-hover mb-3">
                <thead><tr><th>File</th><th>Caption</th><th>Size</th><th>Uploaded</th><th></th></tr></thead>
                <tbody>
                    <?php foreach ($attachments as $a): ?>
                        <tr>
                            <td>
                                <a href="<?= url('/Attachments/download/' . (int) $a['attachment_id']) ?>" target="_blank" class="text-decoration-none">
                                    <i class="fas <?= in_array($a['file_ext'] ?? '', ['jpg','jpeg','png','gif','webp'], true) ? 'fa-image' : 'fa-file' ?> me-1"></i>
                                    <?= e($a['original_name']) ?>
                                </a>
                            </td>
                            <td class="small text-muted"><?= e($a['caption'] ?? '') ?></td>
                            <td class="small text-muted"><?= isset($a['size_bytes']) ? number_format((int) $a['size_bytes'] / 1024, 1) . ' KB' : '—' ?></td>
                            <td class="small text-muted"><?= e($a['created_at']) ?></td>
                            <td class="text-end">
                                <a href="<?= url('/Attachments/delete/' . (int) $a['attachment_id']) ?>" onclick="return confirm('Delete this file?')" class="text-danger"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <p class="text-muted small">No attachments yet.</p>
    <?php endif; ?>

    <form method="post" action="<?= url('/Attachments/upload') ?>" enctype="multipart/form-data" class="row g-2 align-items-end">
        <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">
        <input type="hidden" name="owner_type" value="<?= e($ownerType) ?>">
        <input type="hidden" name="owner_id"   value="<?= (int) $ownerId ?>">
        <div class="col-md-5"><label class="form-label">File</label><input type="file" class="form-control form-control-sm" name="file" required></div>
        <div class="col-md-5"><label class="form-label">Caption</label><input type="text" class="form-control form-control-sm" name="caption" placeholder="(optional)"></div>
        <div class="col-md-2"><button type="submit" class="btn btn-sm btn-primary w-100"><i class="fas fa-upload me-1"></i>Upload</button></div>
    </form>
</div>
