<?php
require_once 'header.php';
require_permission('receipts');

$rid = (int)($_GET['id'] ?? 0);
if ($rid <= 0) { header('Location: receipts.php'); exit; }

// header primke
$stmt = $mysqli->prepare("SELECT id, supplier_id, receipt_date, doc_no, note FROM receipts WHERE id=?");
$stmt->bind_param('i', $rid);
$stmt->execute();
$res = $stmt->get_result();
$rec = $res->fetch_assoc();
$stmt->close();

if(!$rec){
  echo '<div class="alert alert-danger m-3">Primka nije pronađena.</div>';
  require_once 'footer.php'; exit;
}

// dobavljači
$suppliers = $mysqli->query("SELECT id, name FROM suppliers ORDER BY name");

// artikli
$itemsRes = $mysqli->query('SELECT id, code, name, unit FROM items ORDER BY name');
$items = [];
while($r=$itemsRes->fetch_assoc()) $items[]=$r;

// stavke primke
$lineRes = $mysqli->query("
  SELECT ri.item_id, i.code, i.name, ri.quantity, ri.unit
  FROM receipt_items ri
  JOIN items i ON i.id=ri.item_id
  WHERE ri.receipt_id=".(int)$rid."
  ORDER BY i.name
");
$lines=[];
while($r=$lineRes->fetch_assoc()) $lines[]=$r;

$date_display = '';
$dt = DateTime::createFromFormat('Y-m-d', $rec['receipt_date']);
$date_display = $dt ? $dt->format('d.m.Y') : $rec['receipt_date'];
?>
<div class="row g-3 mb-3 align-items-center">
  <div class="col">
    <div class="section-title">Uredi primku</div>
    <div class="text-muted small">Primka #<?php echo $rid; ?></div>
  </div>
  <div class="col-auto">
    <a href="receipts.php" class="btn btn-outline-secondary btn-soft btn-sm">← Primke</a>
  </div>
</div>

<div class="card card-soft">
  <div class="card-body card-soft-body">
    <form method="post" action="receipt_update.php" id="receiptForm">
      <input type="hidden" name="receipt_id" value="<?php echo $rid; ?>">

      <div class="mb-3">
        <label class="form-label">Dobavljač</label>
        <select name="supplier_id" class="form-select" required>
          <option value="">-- odaberite dobavljača --</option>
          <?php while($s=$suppliers->fetch_assoc()): ?>
            <option value="<?php echo $s['id']; ?>"
              <?php echo ((int)$s['id']==(int)$rec['supplier_id'])?'selected':''; ?>>
              <?php echo htmlspecialchars($s['name']); ?>
            </option>
          <?php endwhile; ?>
        </select>
      </div>

      <div class="mb-3">
        <label class="form-label">Datum primke</label>
        <input type="text" name="receipt_date" class="form-control"
               value="<?php echo htmlspecialchars($date_display); ?>"
               placeholder="dd.mm.yyyy" required>
      </div>

      <div class="mb-3">
        <label class="form-label">Broj dokumenta</label>
        <input type="text" name="doc_no" class="form-control"
               value="<?php echo htmlspecialchars($rec['doc_no'] ?? ''); ?>">
      </div>

      <div class="mb-3">
        <label class="form-label">Napomena</label>
        <input type="text" name="note" class="form-control"
               value="<?php echo htmlspecialchars($rec['note'] ?? ''); ?>">
      </div>

      <hr class="my-3">

      <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-2">
        <h5 class="mb-0">Stavke primke</h5>
        <div class="d-flex gap-2 flex-wrap">
          <button type="button" class="btn btn-secondary btn-soft btn-sm" onclick="addRow()">+ Dodaj stavku</button>
          <button type="button" class="btn btn-outline-primary btn-soft btn-sm"
                  data-bs-toggle="modal" data-bs-target="#newItemModal">
            + Novi artikl
          </button>
        </div>
      </div>

      <div id="itemsContainer"></div>

      <div class="mt-4">
        <button class="btn btn-primary btn-soft" type="submit">Spremi izmjene</button>
        <a href="receipts.php" class="btn btn-outline-secondary btn-soft">Natrag</a>
      </div>
    </form>
  </div>
</div>

<datalist id="itemsList">
  <?php foreach($items as $i): ?>
    <option value="<?php echo htmlspecialchars($i['name'].' ('.$i['code'].')'); ?>"></option>
  <?php endforeach; ?>
</datalist>

<!-- Modal novi artikl -->
<div class="modal fade" id="newItemModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Novi artikl</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-2">
          <label class="form-label">Naziv</label>
          <input type="text" class="form-control" id="inline_item_name">
        </div>
        <div class="mb-2">
          <label class="form-label">JM</label>
          <input type="text" class="form-control" id="inline_item_unit" placeholder="kom, m, kg...">
        </div>
        <p class="small text-muted mb-0">Šifra se dodjeljuje automatski.</p>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary btn-soft" data-bs-dismiss="modal" type="button">Odustani</button>
        <button class="btn btn-primary btn-soft" type="button" onclick="saveInlineItem()">Spremi</button>
      </div>
    </div>
  </div>
</div>

<script>
const itemsData = <?php echo json_encode($items, JSON_UNESCAPED_UNICODE); ?>;
const existingLines = <?php echo json_encode($lines, JSON_UNESCAPED_UNICODE); ?>;
let rowIndex = 0;

function addRow(prefill=null){
  const container = document.getElementById('itemsContainer');
  const rowId = 'r_'+(rowIndex++);
  const row = document.createElement('div');
  row.className='list-card';
  row.id=rowId;

  const label=prefill?(prefill.name+' ('+prefill.code+')'):'';
  const qty=prefill?prefill.quantity:'';
  const unit=prefill?prefill.unit:'';

  row.innerHTML = `
    <div class="row g-2 align-items-end">
      <div class="col-md-5 col-12">
        <label class="form-label small">Artikl</label>
        <input type="hidden" name="item_id[]" class="item-id" value="${prefill?prefill.item_id:''}">
        <input type="text" name="item_label[]" class="form-control form-control-sm"
               list="itemsList" placeholder="počni pisati naziv artikla..."
               value="${label}" oninput="itemInputChanged(this)" required>
      </div>
      <div class="col-md-2 col-6">
        <label class="form-label small">Količina</label>
        <input type="number" step="0.001" min="0" name="quantity[]" class="form-control form-control-sm"
               value="${qty}" required>
      </div>
      <div class="col-md-2 col-3">
        <label class="form-label small">JM</label>
        <input type="text" name="unit[]" class="form-control form-control-sm item-unit"
               value="${unit}" readonly required>
      </div>
      <div class="col-md-1 col-1 text-end">
        <button type="button" class="btn btn-outline-danger btn-sm btn-soft"
                onclick="removeRow('${rowId}')">×</button>
      </div>
    </div>`;
  container.appendChild(row);
}

function removeRow(id){ const row=document.getElementById(id); if(row) row.remove(); }

function itemInputChanged(input){
  const value=input.value;
  const row=input.closest('.list-card');
  const hiddenId=row.querySelector('.item-id');
  const unitInput=row.querySelector('.item-unit');

  const match=itemsData.find(i => (i.name+' ('+i.code+')')===value || i.name===value);
  if(match){
    hiddenId.value=match.id;
    unitInput.value=match.unit;
  } else {
    hiddenId.value='';
    unitInput.value='';
  }
}

document.getElementById('receiptForm').addEventListener('submit', function(e){
  const rows=document.querySelectorAll('#itemsContainer .list-card');
  if(!rows.length){ e.preventDefault(); alert('Dodaj barem jednu stavku.'); return; }
  let ok=true; rows.forEach(r=>{ if(!r.querySelector('.item-id').value) ok=false; });
  if(!ok){ e.preventDefault(); alert('Za svaku stavku moraš odabrati artikl iz liste.'); }
});

function saveInlineItem(){
  const name=document.getElementById('inline_item_name').value.trim();
  const unit=document.getElementById('inline_item_unit').value.trim();
  if(!name || !unit){ alert('Naziv i JM su obavezni.'); return; }

  const fd=new FormData();
  fd.append('name', name);
  fd.append('unit', unit);

  fetch('item_add_inline.php',{ method:'POST', body:fd })
    .then(r=>r.json())
    .then(data=>{
      if(!data.success){ alert('Greška: '+(data.error||'')); return; }
      itemsData.push(data.item);
      alert('Artikl dodan: '+data.item.name+' ('+data.item.code+')');
      bootstrap.Modal.getInstance(document.getElementById('newItemModal')).hide();
      document.getElementById('inline_item_name').value='';
      document.getElementById('inline_item_unit').value='';
    })
    .catch(()=>alert('Greška pri spremanju artikla.'));
}

// init
if(existingLines.length) existingLines.forEach(l=>addRow(l));
else addRow();
</script>

<?php require_once 'footer.php'; ?>
