<?php $title='Create Restock'; ob_start(); ?>
<h1 class="h5 mb-3">Create Restock</h1>
<form method="post" action="/samanta_crm/restocks">
  <div class="row mb-3 g-2">
    <div class="col-md-2"><label class="form-label">Date</label><input type="date" name="restock_date" value="<?=date('Y-m-d');?>" class="form-control form-control-sm"></div>
    <div class="col-md-3"><label class="form-label">Supplier</label><input type="text" name="supplier" class="form-control form-control-sm" placeholder="Supplier name"></div>
    <div class="col-md-7"><label class="form-label">Notes</label><input type="text" name="notes" class="form-control form-control-sm" placeholder="Optional notes"></div>
  </div>
  <table class="table table-sm" id="restock-items">
    <thead><tr><th>Ingredient</th><th style="width:100px">Unit</th><th style="width:140px">Qty</th><th style="width:140px">Location</th><th style="width:40px"></th></tr></thead>
    <tbody></tbody>
  </table>
  <button type="button" class="btn btn-sm btn-outline-secondary" onclick="addRow()">Add Item</button>
  <button class="btn btn-sm btn-primary"><?= __("common.save", "Save") ?></button>
  <a href="/samanta_crm/restocks" class="btn btn-sm btn-outline-secondary"><?= __("common.cancel", "Cancel") ?></a>
</form>
<?php $content=ob_get_clean(); require __DIR__.'/../layout.php'; ?>
<script>
const ingredients = <?=json_encode(array_map(function($i){return ['id'=>$i['id'],'name'=>$i['name'],'unit'=>$i['unit']];}, $ingredients));?>;
function addRow(){
  const tbody=document.querySelector('#restock-items tbody');
  const tr=document.createElement('tr');
  tr.innerHTML=`<td><select name="item_ingredient_id[]" class="form-select form-select-sm" onchange="updateUnit(this)">${ingredients.map(i=>`<option value="${i.id}">${i.name}${i.unit?(' ('+i.unit+')'):''}</option>`).join('')}</select></td>
    <td class="unit-cell"></td>
    <td><input type="text" name="item_qty[]" class="form-control form-control-sm" value="0"></td>
    <td><select name="item_location[]" class="form-select form-select-sm"><option value="MAIN">MAIN</option><option value="SEC">SEC</option></select></td>
    <td><button type="button" class="btn btn-sm btn-danger" onclick="this.closest('tr').remove()">&times;</button></td>`;
  tbody.appendChild(tr);
  updateUnit(tr.querySelector('select[name="item_ingredient_id[]"]'));
}
function updateUnit(sel){
  const tr=sel.closest('tr');
  const ing=ingredients.find(i=>i.id==sel.value);
  tr.querySelector('.unit-cell').textContent=ing && ing.unit?ing.unit:'';
}
addRow();
</script>
