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

// projekti (samo otvoreni za odabir naloga)
$projectsRes = $mysqli->query("SELECT id, name, project_status FROM projects 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;
}
?>
<div class="row g-3 mb-3 align-items-center">
    <div class="col">
        <div class="section-title">Novi nalog utroška</div>
        <div class="text-muted small">Unos utroška materijala po projektu</div>
    </div>
</div>

<div class="card card-soft">
    <div class="card-body card-soft-body">
        <form method="post" action="order_save.php" id="orderForm">
            <div class="mb-3">
                <label class="form-label">Projekt (pretraži)</label>
                <input type="hidden" name="project_id" id="project_id">
                <input type="text" name="project_label"
                       class="form-control"
                       list="projectsList"
                       placeholder="počni pisati naziv projekta..."
                       oninput="projectInputChanged(this)"
                       required>
            </div>
            <div class="mb-3">
                <label class="form-label">Datum utroška</label>
                <input type="text" name="usage_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">Napomena (opcionalno)</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 utroška</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>
                    <!-- inline novi artikl -->
                    <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 nalog</button>
                <a href="orders.php" class="btn btn-outline-secondary btn-soft">Odustani</a>
            </div>
        </form>
    </div>
</div>

<datalist id="projectsList">
    <?php while ($p = $projectsRes->fetch_assoc()):
        $label = $p['name'];
        if ($p['project_status'] === 'closed') {
            $label .= ' [DOVRŠEN]';
        }
    ?>
        <option value="<?php echo htmlspecialchars($label); ?>"></option>
    <?php endwhile; ?>
</datalist>

<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 -->
<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">
              <?php
              $groups = $mysqli->query('SELECT id, name FROM item_groups ORDER BY name');
              ?>
              <div class="mb-2">
                  <label class="form-label">Grupa</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 (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;

    const projectsData = <?php
        $pRes = $mysqli->query("SELECT id, name, project_status FROM projects ORDER BY name");
        $pList = [];
        while ($pr = $pRes->fetch_assoc()) $pList[] = $pr;
        echo json_encode($pList, JSON_UNESCAPED_UNICODE);
    ?>;

    function projectInputChanged(input) {
        const val = input.value;
        const hidden = document.getElementById('project_id');
        const match = projectsData.find(p => {
            let label = p.name;
            if (p.project_status === 'closed') label += ' [DOVRŠEN]';
            return label === val || p.name === val;
        });
        if (match) {
            if (match.project_status === 'closed') {
                alert('Projekt je dovršen – nije moguće dodavati novi utrošak.');
                input.value = '';
                hidden.value = '';
            } else {
                hidden.value = match.id;
            }
        } else {
            hidden.value = '';
        }
    }

    function addRow() {
        const container = document.getElementById('itemsContainer');
        const rowId = 'row_' + (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('orderForm').addEventListener('submit', function(e) {
        const projectId = document.getElementById('project_id').value;
        if (!projectId) {
            e.preventDefault();
            alert('Morate odabrati projekt iz liste.');
            return;
        }
        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
    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) {
                // dodaj u itemsData
                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.');
        });
    }

    // default jedna stavka
    addRow();
</script>

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