<?php
<td><?=esc($d['ime'].' '.$d['prezime'])?></td>


<!-- Dogovorena plaća (po djelatniku) -->
<td class="text-end">
<input type="number" step="0.01" class="form-control form-control-sm"
name="dogovorena_placa[<?=$id?>]" value="<?=number_format((float)$d['dogovorena_placa'],2,'.','')?>">
</td>


<!-- Mjesečna stavka -->
<td class="text-end">
<input type="number" step="0.01" class="form-control form-control-sm money"
name="gotovina[<?=$id?>]" value="<?=$fmt($row['gotovina'])?>">
</td>
<td class="text-end">
<input type="number" step="0.01" class="form-control form-control-sm money"
name="nagrada[<?=$id?>]" value="<?=$fmt($row['nagrada'])?>">
</td>
<td class="text-end">
<input type="number" step="0.01" class="form-control form-control-sm money"
name="bonus[<?=$id?>]" value="<?=$fmt($row['bonus'])?>">
</td>
<td class="text-end">
<input type="number" step="0.01" class="form-control form-control-sm money"
name="osnovica[<?=$id?>]" value="<?=$fmt($row['osnovica'])?>">
</td>
<td class="text-end">
<input type="number" step="0.01" class="form-control form-control-sm money"
name="dodaci[<?=$id?>]" value="<?=$fmt($row['dodaci'])?>">
</td>


<td class="text-end mono">
<input type="text" class="form-control form-control-sm" name="ukupno_view[<?=$id?>]"
value="<?=number_format($uk,2,'.','')?>" disabled>
</td>


<td class="text-end mono">
<?= $prev_total!==null ? number_format($prev_total,2,',','.') : '—' ?>
</td>
<td class="text-end mono">
<?php if ($delta!==null): ?>
<span class="<?= $delta>=0 ? 'delta-pos':'delta-neg' ?>">
<?= number_format($delta,2,',','.') ?>
</span>
<?php else: ?> — <?php endif; ?>
</td>
<td>
<input type="text" class="form-control form-control-sm" name="napomena[<?=$id?>]"
value="<?=esc($row['napomena'])?>">
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>


<div class="d-flex gap-2">
<button class="btn btn-primary">Spremi sve</button>
<button type="button" class="btn btn-outline-secondary" id="btnRecalc">Ponovno izračunaj ukupno</button>
</div>
</form>
</div>
</div>
</div>


<script>
// Re-kalkulacija "Ukupno" po retku — bez nagrade i bonusa
function recalcRow(tr){
const pick = name => {
const el = tr.querySelector(`input[name^="${name}[""]`);
return el ? (parseFloat((el.value||'').replace(',', '.'))||0) : 0;
};
const sum = pick('gotovina') + pick('osnovica') + pick('dodaci');
const out = tr.querySelector('input[name^="ukupno_view[" ]');
if(out){ out.value = sum.toFixed(2); }
}


document.querySelectorAll('tr[data-id]').forEach(tr=>{
tr.querySelectorAll('input.money').forEach(inp=>inp.addEventListener('input', ()=>recalcRow(tr)));
});


document.getElementById('btnRecalc').addEventListener('click', ()=>{
document.querySelectorAll('tr[data-id]').forEach(tr=>recalcRow(tr));
});
</script>
</body>
</html>