<?php $id = (int) $item['id']; ?>
<div class="field-row" data-item-id="<?= $id ?>">
    <div class="field-row-head">
        <span class="num"><?= esc($item['numero'] ?? '') ?></span>
        <span class="q"><?= esc($item['pregunta']) ?></span>
        <?php if (! empty($item['equipo'])): ?><span class="equipment"><?= esc($item['equipo']) ?></span><?php endif; ?>
    </div>
    <input type="file" class="attachment-input" data-item-id="<?= $id ?>" accept="image/*,.pdf,.doc,.docx">
    <small class="muted" data-att-status="<?= $id ?>"><?= esc($saved['value_text'] ?? '') ?></small>
    <input type="hidden" data-bind="items.<?= $id ?>.value_text" value="<?= esc($saved['value_text'] ?? '') ?>">
</div>
<script>
(function () {
    const id = <?= $id ?>;
    const input = document.querySelector('.attachment-input[data-item-id="' + id + '"]');
    const hidden = document.querySelector('input[data-bind="items.' + id + '.value_text"]');
    const status = document.querySelector('[data-att-status="' + id + '"]');
    if (!input) return;
    input.addEventListener('change', async () => {
        const f = input.files?.[0]; if (!f) return;
        status.textContent = 'Subiendo…';
        const fd = new FormData();
        fd.append('file', f);
        fd.append('item_id', id);
        const csrfName = document.querySelector('meta[name="csrf-token-name"]')?.content;
        const csrfHash = document.querySelector('meta[name="csrf-token"]')?.content;
        if (csrfName) fd.append(csrfName, csrfHash);
        try {
            const r = await fetch(<?= json_encode(site_url('inspections/' . $inspection['id'] . '/attachments')) ?>, {
                method: 'POST', body: fd,
                headers: { 'X-CSRF-TOKEN': csrfHash || '' },
                credentials: 'same-origin',
            });
            const j = await r.json();
            if (j && j.csrf_token) {
                document.querySelector('meta[name="csrf-token"]')?.setAttribute('content', j.csrf_token);
            }
            if (j.ok) {
                hidden.value = j.path;
                hidden.dispatchEvent(new Event('change', {bubbles: true}));
                status.textContent = '✓ ' + f.name;
            } else {
                status.textContent = '✗ ' + (j.msg || 'Error al subir');
            }
        } catch (e) {
            status.textContent = '✗ Sin conexión, se reintentará';
        }
    });
})();
</script>
