let flockData = []; async function loadFlock() { const msg = document.getElementById('msg'); try { const [current, history] = await Promise.all([ API.get('/api/flock/current'), API.get('/api/flock'), ]); document.getElementById('current-count').textContent = current?.chicken_count ?? '—'; document.getElementById('current-date').textContent = current ? fmtDate(current.date) : 'No data'; flockData = history; renderTable(); } catch (err) { showMessage(msg, `Failed to load flock data: ${err.message}`, 'error'); } } function renderTable() { const tbody = document.getElementById('flock-body'); if (flockData.length === 0) { tbody.innerHTML = 'No flock history yet.'; return; } tbody.innerHTML = flockData.map(e => ` ${fmtDate(e.date)} ${e.chicken_count} ${e.notes || ''} `).join(''); } function startEdit(id) { const entry = flockData.find(e => e.id === id); const row = document.querySelector(`tr[data-id="${id}"]`); row.innerHTML = ` `; } async function saveEdit(id) { const msg = document.getElementById('msg'); const row = document.querySelector(`tr[data-id="${id}"]`); const [dateInput, countInput, notesInput] = row.querySelectorAll('input'); try { const updated = await API.put(`/api/flock/${id}`, { date: dateInput.value, chicken_count: parseInt(countInput.value, 10), notes: notesInput.value.trim() || null, }); const idx = flockData.findIndex(e => e.id === id); flockData[idx] = updated; renderTable(); loadFlock(); // refresh current-flock callout showMessage(msg, 'Entry updated.'); } catch (err) { showMessage(msg, `Error: ${err.message}`, 'error'); } } async function deleteEntry(id) { if (!confirm('Delete this flock entry?')) return; const msg = document.getElementById('msg'); try { await API.del(`/api/flock/${id}`); flockData = flockData.filter(e => e.id !== id); renderTable(); loadFlock(); showMessage(msg, 'Entry deleted.'); } catch (err) { showMessage(msg, `Error: ${err.message}`, 'error'); } } document.addEventListener('DOMContentLoaded', () => { const form = document.getElementById('flock-form'); const msg = document.getElementById('msg'); setToday(document.getElementById('date')); form.addEventListener('submit', async (e) => { e.preventDefault(); const data = { date: document.getElementById('date').value, chicken_count: parseInt(document.getElementById('count').value, 10), notes: document.getElementById('notes').value.trim() || null, }; try { await API.post('/api/flock', data); showMessage(msg, 'Flock change saved!'); form.reset(); setToday(document.getElementById('date')); loadFlock(); } catch (err) { showMessage(msg, `Error: ${err.message}`, 'error'); } }); loadFlock(); });