<?php
$cols = $template['items'] ?? [];
// Convención: en modo equipment_table guardamos toda la tabla en savedItems[0].value_json
$rows = $savedItems[0]['value_json'] ?? [];
if (! is_array($rows)) { $rows = []; }
?>
<fieldset class="stack-sm">
    <legend>Tabla de equipos</legend>
    <p class="muted">Agrega una fila por cada equipo inspeccionado.</p>
    <div class="table-wrap">
        <table id="equipment-table">
            <thead><tr>
                <?php foreach ($cols as $col): ?>
                    <th>
                        <?= esc($col['pregunta']) ?>
                        <?php if (! empty($col['equipo'])): ?><small><?= esc($col['equipo']) ?></small><?php endif; ?>
                    </th>
                <?php endforeach; ?>
                <th></th>
            </tr></thead>
            <tbody id="equipment-rows"></tbody>
        </table>
    </div>
    <button type="button" class="btn btn-secondary" id="add-equipment-row">+ Agregar fila</button>
    <input type="hidden" data-bind="items.0.value_json" id="equipment-json">
</fieldset>

<script>
(function () {
    const cols = <?= json_encode(array_map(static fn ($c) => ['key' => 'c' . $c['id'], 'label' => $c['pregunta']], $cols), JSON_UNESCAPED_UNICODE) ?>;
    const initial = <?= json_encode($rows, JSON_UNESCAPED_UNICODE) ?>;
    const tbody = document.getElementById('equipment-rows');
    const hidden = document.getElementById('equipment-json');

    function sync() {
        const data = Array.from(tbody.querySelectorAll('tr')).map(tr => {
            const obj = {};
            cols.forEach(c => { obj[c.key] = tr.querySelector('input[data-col="' + c.key + '"]').value; });
            return obj;
        });
        hidden.value = JSON.stringify(data);
        hidden.dispatchEvent(new Event('change', {bubbles: true}));
    }

    function addRow(data = {}) {
        const tr = document.createElement('tr');
        cols.forEach(c => {
            const td = document.createElement('td');
            const inp = document.createElement('input');
            inp.type = 'text';
            inp.dataset.col = c.key;
            inp.value = data[c.key] ?? '';
            inp.addEventListener('input', sync);
            td.appendChild(inp);
            tr.appendChild(td);
        });
        const del = document.createElement('td');
        const btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'link-button';
        btn.textContent = 'Eliminar';
        btn.addEventListener('click', () => { tr.remove(); sync(); });
        del.appendChild(btn);
        tr.appendChild(del);
        tbody.appendChild(tr);
        sync();
    }

    (initial.length ? initial : [{}]).forEach(addRow);
    document.getElementById('add-equipment-row').addEventListener('click', () => addRow());
})();
</script>
