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

$suppliersRes = $mysqli->query('SELECT id, name FROM suppliers ORDER BY name');
$itemsRes = $mysqli->query('SELECT id, code, name, unit FROM items ORDER BY name');
$items = [];
while ($row = $itemsRes->fetch_assoc()) {
    $items[] = $row;
}
?>
<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>
                <button type="button" class="btn btn-secondary btn-soft btn-sm" onclick="addRow()">+ Dodaj stavku</button>
            </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>

<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-5 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-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" required>
                </div>
                <div class="col-md-2 col-6">
  <label class="form-label small">Cijena (€)</label>
  <input type="number" step="0.0001" min="0"
         name="unit_price[]"
         class="form-control form-control-sm"
         placeholder="0,00">
</div>

                <div class="col-md-2 col-6">
                    <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).');
        }
    });

    addRow();
</script>

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