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

// dobavljači
$suppliersRes = $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 ($row = $itemsRes->fetch_assoc()) {
    $items[] = $row;
}

// grupe artikala (za modal)
$groups = $mysqli->query('SELECT id, name FROM item_groups ORDER BY name');
?>
<div class="row g-3 mb-3 align-items-center">
    <div class="col">
        <div class="section-title">Nova primka</div>
        <div class="text-muted small">Unos ulaznog dokumenta i stavki</div>
    </div>
</div>

<div class="card card-soft">
    <div class="card-body card-soft-body">
        <form method="post" action="receipt_save.php" id="receiptForm">
            <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 = $suppliersRes->fetch_assoc()): ?>
                        <option value="<?php echo $s['id']; ?>">
                            <?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 date('d.m.Y'); ?>" 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">
            </div>
            <div class="mb-3">
                <label class="form-label">Napomena</label>
                <input type="text" name="note" class="form-control">
            </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 flex-wrap gap-2">
                    <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" class="mt-2"></div>

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

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

<!-- Modal: novi artikl (inline, kao kod naloga) -->
<div class="modal fade" id="newItemModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <form method="post" id="inlineItemForm">
          <div class="modal-header">
            <h5 class="modal-title">Novi artikl</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Zatvori"></button>
          </div>
          <div class="modal-body">
              <div class="mb-2">
                  <label class="form-label">Grupa artikla</label>
                  <select name="item_group_id" class="form-select form-select-sm" id="inline_item_group_id">
                      <option value="0">-- bez grupe --</option>
                      <?php
                      $groups->data_seek(0);
                      while ($g = $groups->fetch_assoc()): ?>
                          <option value="<?php echo $g['id']; ?>">
                              <?php echo htmlspecialchars($g['name']); ?>
                          </option>
                      <?php endwhile; ?>
                  </select>
              </div>
              <div class="mb-2">
                  <label class="form-label">Naziv artikla</label>
                  <input type="text" class="form-control" id="inline_item_name" required>
              </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..." required>
              </div>
              <p class="small text-muted mb-0">
                  Šifra se dodjeljuje automatski kao sljedeći broj u nizu.
              </p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary btn-soft" data-bs-dismiss="modal">Odustani</button>
            <button type="button" class="btn btn-primary btn-soft" onclick="saveInlineItem()">Spremi artikl</button>
          </div>
      </form>
    </div>
  </div>
</div>

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

    function addRow() {
        const container = document.getElementById('itemsContainer');
        const rowId = 'r_' + (rowIndex++);
        const row = document.createElement('div');
        row.className = 'list-card';
        row.id = rowId;
        row.innerHTML = `
            <div class="row g-2 align-items-end">
                <div class="col-md-6 col-12">
                    <label class="form-label small">Artikl</label>
                    <input type="hidden" name="item_id[]" class="item-id">
                    <input type="text"
                           name="item_label[]"
                           class="form-control form-control-sm item-search"
                           list="itemsList"
                           placeholder="počni pisati naziv artikla..."
                           oninput="itemInputChanged(this)"
                           required>
                </div>
                <div class="col-md-3 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" required>
                </div>
                <div class="col-md-2 col-5">
                    <label class="form-label small">JM</label>
                    <input type="text" name="unit[]" class="form-control form-control-sm item-unit" required readonly>
                </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('Dodajte barem jednu stavku.');
            return;
        }
        let ok = true;
        rows.forEach(row => {
            const id = row.querySelector('.item-id').value;
            if (!id) ok = false;
        });
        if (!ok) {
            e.preventDefault();
            alert('Za svaku stavku morate odabrati artikl iz liste (JM se automatski popunjava).');
        }
    });

    // inline spremanje artikla (isti endpoint kao kod naloga)
    function saveInlineItem() {
        const name = document.getElementById('inline_item_name').value.trim();
        const unit = document.getElementById('inline_item_unit').value.trim();
        const groupId = document.getElementById('inline_item_group_id').value;

        if (!name || !unit) {
            alert('Naziv i JM su obavezni.');
            return;
        }

        const formData = new FormData();
        formData.append('name', name);
        formData.append('unit', unit);
        formData.append('item_group_id', groupId);

        fetch('item_add_inline.php', {
            method: 'POST',
            body: formData
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                itemsData.push({
                    id: data.item.id,
                    code: data.item.code,
                    name: data.item.name,
                    unit: data.item.unit
                });
                alert('Artikl dodan: ' + data.item.name + ' (' + data.item.code + ')');

                const modalEl = document.getElementById('newItemModal');
                const modal = bootstrap.Modal.getInstance(modalEl);
                modal.hide();

                document.getElementById('inline_item_name').value = '';
                document.getElementById('inline_item_unit').value = '';
            } else {
                alert('Greška: ' + (data.error || 'Nepoznata greška'));
            }
        })
        .catch(err => {
            console.error(err);
            alert('Greška pri spremanju artikla.');
        });
    }

    // jedna stavka po defaultu
    addRow();
</script>

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