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

function table_exists(mysqli $mysqli, string $table): bool {
    $safe = $mysqli->real_escape_string($table);
    $res = $mysqli->query("SHOW TABLES LIKE '{$safe}'");
    return $res && $res->num_rows > 0;
}

function column_exists(mysqli $mysqli, string $table, string $column): bool {
    $safeTable = $mysqli->real_escape_string($table);
    $safeColumn = $mysqli->real_escape_string($column);
    $res = $mysqli->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeColumn}'");
    return $res && $res->num_rows > 0;
}

$hasSubgroups = table_exists($mysqli, 'item_subgroups');
$hasItemWarranty = column_exists($mysqli, 'items', 'has_warranty') && column_exists($mysqli, 'items', 'warranty_months');
$hasConsumptionItemWarranty = column_exists($mysqli, 'consumption_items', 'has_warranty') && column_exists($mysqli, 'consumption_items', 'warranty_months');

$projectsRes = $mysqli->query("SELECT id, name, project_status FROM projects ORDER BY name");

$groups = [];
$groupsRes = $mysqli->query("SELECT id, name FROM item_groups ORDER BY name");
if ($groupsRes) { while ($row = $groupsRes->fetch_assoc()) $groups[] = $row; }

$subgroups = [];
if ($hasSubgroups) {
    $subRes = $mysqli->query("SELECT id, item_group_id, name FROM item_subgroups ORDER BY name");
    if ($subRes) { while ($row = $subRes->fetch_assoc()) $subgroups[] = $row; }
}

$selectItemWarranty = $hasItemWarranty ? ", i.has_warranty, i.warranty_months" : ", 0 AS has_warranty, NULL AS warranty_months";
if ($hasSubgroups) {
    $itemsSql = "SELECT i.id, i.code, i.name, i.unit, i.item_group_id, i.item_subgroup_id,
                        g.name AS group_name, sg.name AS subgroup_name
                        {$selectItemWarranty}
                 FROM items i
                 LEFT JOIN item_groups g ON g.id = i.item_group_id
                 LEFT JOIN item_subgroups sg ON sg.id = i.item_subgroup_id
                 ORDER BY g.name, sg.name, i.name";
} else {
    $itemsSql = "SELECT i.id, i.code, i.name, i.unit, i.item_group_id, NULL AS item_subgroup_id,
                        g.name AS group_name, NULL AS subgroup_name
                        {$selectItemWarranty}
                 FROM items i
                 LEFT JOIN item_groups g ON g.id = i.item_group_id
                 ORDER BY g.name, i.name";
}
$itemsRes = $mysqli->query($itemsSql);
$items = [];
if ($itemsRes) { while ($row = $itemsRes->fetch_assoc()) $items[] = $row; }

$empRes = $mysqli->query("SELECT id, first_name, last_name, hourly_rate FROM employees WHERE active=1 ORDER BY last_name, first_name");
$employees = [];
while ($empRes && ($r = $empRes->fetch_assoc())) { $employees[] = $r; }
?>
<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" enctype="multipart/form-data">
            <div class="mb-3">
                <label class="form-label">Projekt</label>
                <input type="hidden" name="project_id" id="project_id">
                <input type="text" name="project_label" id="project_label" class="form-control"
                       placeholder="Odaberi ili pretraži projekt..." autocomplete="off" required>
                <div class="lookup-results project-results d-none"></div>
            </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>
                    <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>

            <hr class="my-3">

            <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-2">
                <h5 class="mb-0">Rad (sati)</h5>
                <button type="button" class="btn btn-secondary btn-soft btn-sm" onclick="addLaborRow()">+ Dodaj radnika</button>
            </div>

            <div class="list-card bulk-labor-card mb-3">
                <div class="item-card-summary">Grupni unos radnika prema datumu naloga</div>
                <div class="row g-2 align-items-end">
                    <div class="col-md-2 col-6">
                        <label class="form-label small">Od</label>
                        <input type="time" id="bulk_time_from" class="form-control form-control-sm" value="07:00">
                    </div>
                    <div class="col-md-2 col-6">
                        <label class="form-label small">Do</label>
                        <input type="time" id="bulk_time_to" class="form-control form-control-sm" value="15:00">
                    </div>
                    <div class="col-md-2 col-6">
                        <label class="form-label small">Pauza (min)</label>
                        <input type="number" id="bulk_break_min" class="form-control form-control-sm" min="0" step="5" inputmode="numeric" value="0">
                    </div>
                    <div class="col-md-2 col-6">
                        <label class="form-label small">Sati</label>
                        <input type="text" id="bulk_hours" class="form-control form-control-sm" readonly>
                    </div>
                    <div class="col-md-4 col-12">
                        <label class="form-label small">Napomena</label>
                        <input type="text" id="bulk_labor_note" class="form-control form-control-sm" placeholder="npr. montaža, servis...">
                    </div>
                </div>
                <div class="mt-3">
                    <label class="form-label small">Pretraži radnike</label>
                    <input type="text" id="bulk_employee_search" class="form-control form-control-sm" placeholder="Upiši ime radnika..." autocomplete="off">
                </div>
                <div class="d-flex flex-wrap gap-2 mt-2">
                    <button type="button" class="btn btn-outline-secondary btn-soft btn-sm" onclick="toggleBulkEmployees(true)">Označi prikazane</button>
                    <button type="button" class="btn btn-outline-secondary btn-soft btn-sm" onclick="toggleBulkEmployees(false)">Makni oznake</button>
                    <button type="button" class="btn btn-primary btn-soft btn-sm" onclick="addSelectedEmployees()">Dodaj označene radnike</button>
                </div>
                <div id="bulkEmployeeList" class="bulk-employee-list mt-3"></div>
            </div>

            <div id="laborContainer" class="mt-2"></div>

            <hr class="my-3">

            <div class="mt-3">
                <div class="section-subtitle">Prilozi (slike / video)</div>
                <div class="text-muted small mb-2">Možeš dodati više slika i/ili video. Slike se po mogućnosti spremaju kao WebP.</div>
                <input class="form-control" type="file" name="media_files[]" id="media_files" multiple accept="image/*,video/*">
                <div class="form-text">Preporuka: slike do 12MB, video do 250MB po datoteci.</div>
            </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>


<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" onsubmit="return false;">
          <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</label>
                  <select name="item_group_id" class="form-select form-select-sm" id="inline_item_group_id" onchange="inlineGroupChanged()">
                      <option value="0">-- bez grupe --</option>
                      <?php foreach ($groups as $g): ?>
                          <option value="<?php echo (int)$g['id']; ?>"><?php echo htmlspecialchars($g['name']); ?></option>
                      <?php endforeach; ?>
                  </select>
              </div>
              <?php if ($hasSubgroups): ?>
              <div class="mb-2 d-none" id="inline_subgroup_wrap">
                  <label class="form-label">Podgrupa</label>
                  <select name="item_subgroup_id" class="form-select form-select-sm" id="inline_item_subgroup_id">
                      <option value="0">-- bez podgrupe --</option>
                  </select>
              </div>
              <?php endif; ?>
              <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.</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>

<style>
.item-card-summary{
  font-size:12px; color:rgba(255,255,255,.72); margin-bottom:10px;
}
.lookup-results{
  margin-top:8px; max-height:220px; overflow:auto;
  border:1px solid rgba(255,255,255,.12);
  border-radius:14px; background:rgba(12,18,35,.98);
}
.lookup-result-item{
  width:100%; border:0; display:block; text-align:left; background:transparent;
  color:#fff; padding:12px 14px; border-bottom:1px solid rgba(255,255,255,.06);
}
.lookup-result-item:last-child{ border-bottom:none; }
.lookup-result-item:hover,.lookup-result-item:focus,.lookup-result-item.active{ background:rgba(255,255,255,.08); }
.search-empty{ padding:12px 14px; color:rgba(255,255,255,.7); font-size:13px; }
.item-selected{ font-size:13px; color:rgba(255,255,255,.78); margin-top:8px; }
.item-warranty-badge{display:inline-flex;align-items:center;gap:6px;margin-top:8px;padding:6px 10px;border-radius:999px;background:rgba(255,193,7,.12);border:1px solid rgba(255,193,7,.28);color:#ffe08a;font-size:12px;font-weight:600;}
.unit-chip{
  min-height:46px; display:flex; align-items:center; justify-content:center;
  border:1px solid rgba(255,255,255,.14); border-radius:14px; font-weight:700;
  color:#fff; background:rgba(255,255,255,.03);
}
.mobile-hidden{ display:none; }
@media (max-width: 768px){
  .list-card{ padding:14px; border-radius:18px; }
  .form-control,.form-select{ min-height:50px; font-size:16px; border-radius:14px; }
  .btn-soft.btn-sm{ min-height:42px; }
  .remove-row-btn{ width:42px; height:42px; border-radius:999px; }
}

.bulk-employee-list{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:10px;}
.bulk-employee-item{display:flex;align-items:flex-start;gap:12px;padding:12px 14px;border:1px solid rgba(255,255,255,.12);border-radius:16px;background:rgba(255,255,255,.03);cursor:pointer;transition:.18s ease;}
.bulk-employee-item:hover{border-color:rgba(104,173,255,.45);background:rgba(104,173,255,.08);}
.bulk-employee-item input[type="checkbox"]{margin-top:4px;transform:scale(1.15);accent-color:#59b7ff;flex:0 0 auto;}
.bulk-employee-main{min-width:0;}
.bulk-employee-name{font-weight:600;line-height:1.25;color:#fff;word-break:break-word;}
.bulk-employee-empty{padding:12px 14px;border:1px dashed rgba(255,255,255,.16);border-radius:14px;color:rgba(255,255,255,.75);}
@media (max-width: 768px){.bulk-employee-list{grid-template-columns:1fr;gap:8px;}.bulk-employee-item{padding:11px 12px;border-radius:14px;}}

</style>

<?php
$itemsJson = json_encode($items, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
if ($itemsJson === false) $itemsJson = '[]';
$groupsJson = json_encode($groups, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
if ($groupsJson === false) $groupsJson = '[]';
$subgroupsJson = json_encode($subgroups, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
if ($subgroupsJson === false) $subgroupsJson = '[]';
$employeesJson = json_encode($employees, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
if ($employeesJson === false) $employeesJson = '[]';
$pRes = $mysqli->query("SELECT id, name, project_status FROM projects ORDER BY name");
$pList = [];
while ($pRes && ($pr = $pRes->fetch_assoc())) $pList[] = $pr;
$projectsJson = json_encode($pList, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
if ($projectsJson === false) $projectsJson = '[]';
?>
<script>
window.itemsData = <?php echo $itemsJson; ?>;
window.groupsData = <?php echo $groupsJson; ?>;
window.subgroupsData = <?php echo $subgroupsJson; ?>;
window.hasSubgroups = <?php echo json_encode($hasSubgroups); ?>;
const employeesData = <?php echo $employeesJson; ?>;
let rowIndex = 0;
let laborIndex = 0;

const projectsData = <?php echo $projectsJson; ?>;

function escapeHtml(s){
    return String(s ?? '').replace(/[&<>\"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m]));
}
function norm(s){ return String(s ?? '').trim().toLowerCase(); }

function projectLabel(project){
    let label = project.name || '';
    if (project.project_status === 'closed') label += ' [DOVRŠEN]';
    return label;
}

function getFilteredProjects(term=''){
    term = norm(term);
    let list = (projectsData || []).filter(p => p.project_status !== 'closed');
    if (term) list = list.filter(p => norm(projectLabel(p)).includes(term) || norm(p.name).includes(term));
    list.sort((a,b) => norm(projectLabel(a)).localeCompare(norm(projectLabel(b))));
    return list.slice(0, 30);
}

function renderProjectResults(term=''){
    const box = document.querySelector('.project-results');
    if (!box) return;
    renderLookupResults(box, getFilteredProjects(term), 'project');
}

function applyProjectSelection(project){
    const hidden = document.getElementById('project_id');
    const input = document.getElementById('project_label');
    if (!hidden || !input) return;
    hidden.value = project.id;
    input.value = projectLabel(project);
    const box = document.querySelector('.project-results');
    if (box) {
        box.classList.add('d-none');
        box.innerHTML = '';
        box._matches = [];
        box._type = '';
    }
}

function subgroupOptions(groupId, selected=''){
    if (!window.hasSubgroups) return '<option value="">-- artikli iz cijele grupe --</option>';
    const list = (window.subgroupsData || []).filter(s => String(s.item_group_id) === String(groupId));
    let html = '<option value="">-- odaberi podgrupu --</option>';
    list.forEach(s => {
        html += `<option value="${s.id}" ${String(selected)===String(s.id)?'selected':''}>${escapeHtml(s.name)}</option>`;
    });
    return html;
}


function rowSummaryText(row){
    const groupVal = row.querySelector('.item-group-search')?.value || '';
    const subgroupVal = row.querySelector('.item-subgroup-search')?.value || '';
    const label = row.querySelector('.item-selected-label');
    const parts = [];
    if (groupVal) parts.push(groupVal);
    if (subgroupVal) parts.push(subgroupVal);
    if (label && label.value) parts.push(label.value);
    row.querySelector('.item-card-summary').textContent = parts.join(' / ') || 'Odaberi grupu, podgrupu i artikl';
}

function syncRowVisibility(row){
    const groupId = row.querySelector('.item-group-id')?.value || '';
    const subgroupId = row.querySelector('.item-subgroup-id')?.value || '';
    const subgroupWrap = row.querySelector('.subgroup-search-wrap');
    const itemWrap = row.querySelector('.item-search-wrap');
    if (!groupId) {
        subgroupWrap?.classList.add('mobile-hidden');
        itemWrap?.classList.add('mobile-hidden');
    } else if (window.hasSubgroups) {
        subgroupWrap?.classList.remove('mobile-hidden');
        if (subgroupId) itemWrap?.classList.remove('mobile-hidden');
        else itemWrap?.classList.add('mobile-hidden');
    } else {
        subgroupWrap?.classList.add('mobile-hidden');
        itemWrap?.classList.remove('mobile-hidden');
    }
}

function getFilteredGroups(term=''){
    term = norm(term);
    let list = window.groupsData || [];
    if (term) list = list.filter(g => norm(g.name).includes(term));
    list.sort((a,b) => norm(a.name).localeCompare(norm(b.name)));
    return list.slice(0, 30);
}

function getFilteredSubgroups(row, term=''){
    const groupId = row.querySelector('.item-group-id')?.value || '';
    term = norm(term);
    let list = (window.subgroupsData || []).filter(s => String(s.item_group_id) === String(groupId));
    if (term) list = list.filter(s => norm(s.name).includes(term));
    list.sort((a,b) => norm(a.name).localeCompare(norm(b.name)));
    return list.slice(0, 30);
}

function renderLookupResults(box, matches, type, selectedId=''){
    if (!matches.length) {
        box.innerHTML = '<div class="search-empty">Nema rezultata.</div>';
        box.classList.remove('d-none');
        box._matches = [];
        box._type = type;
        return;
    }
    box.innerHTML = matches.map((entry, idx) => {
        const label = type === 'item'
            ? `<strong>${escapeHtml(entry.code || '')}</strong> - ${escapeHtml(entry.name || '')}`
            : escapeHtml(entry.name || '');
        return `<button type="button" class="lookup-result-item ${String(selectedId)===String(entry.id)?'active':''}" data-idx="${idx}">${label}</button>`;
    }).join('');
    box._matches = matches;
    box._type = type;
    box.classList.remove('d-none');
}

function openGroupResults(row, term=''){
    renderLookupResults(row.querySelector('.group-results'), getFilteredGroups(term), 'group');
}

function openSubgroupResults(row, term=''){
    renderLookupResults(row.querySelector('.subgroup-results'), getFilteredSubgroups(row, term), 'subgroup');
}

function openItemResults(row, term=''){
    const input = row.querySelector('.item-search');
    if (!input) return;
    input.value = term !== undefined ? term : (input.value || '');
    filterItemsInRow(input, !String(term || '').trim());
}

function addLaborRow(prefill=null){}

function addRow(prefill=null) {
    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="item-card-summary">Odaberi grupu, podgrupu i artikl</div>
        <div class="row g-2 align-items-end">
            <div class="col-12 group-search-wrap">
                <label class="form-label small">Grupa</label>
                <input type="hidden" class="item-group-id" value="${prefill ? (prefill.item_group_id || '') : ''}">
                <input type="text" class="form-control form-control-sm item-group-search" placeholder="Odaberi ili pretraži grupu..." autocomplete="off" ${(typeof isLocked !== 'undefined' && isLocked) ? 'readonly' : ''}>
                <div class="lookup-results group-results d-none"></div>
            </div>
            <div class="col-12 subgroup-search-wrap ${window.hasSubgroups ? 'mobile-hidden' : 'mobile-hidden'}">
                <label class="form-label small">Podgrupa</label>
                <input type="hidden" class="item-subgroup-id" value="${prefill ? (prefill.item_subgroup_id || '') : ''}">
                <input type="text" class="form-control form-control-sm item-subgroup-search" placeholder="Odaberi ili pretraži podgrupu..." autocomplete="off" ${(typeof isLocked !== 'undefined' && isLocked) ? 'readonly' : ''}>
                <div class="lookup-results subgroup-results d-none"></div>
            </div>
            <div class="col-12 item-search-wrap mobile-hidden">
                <label class="form-label small">Artikl</label>
                <input type="hidden" name="item_id[]" class="item-id" value="${prefill ? (prefill.item_id || '') : ''}">
                <input type="hidden" name="has_warranty[]" class="item-has-warranty" value="${prefill ? (prefill.has_warranty || 0) : 0}">
                <input type="hidden" name="warranty_months[]" class="item-warranty-months" value="${prefill ? (prefill.warranty_months || '') : ''}">
                <input type="hidden" class="item-selected-label" value="${prefill ? escapeHtml((prefill.code || '') + ' - ' + (prefill.name || '')) : ''}">
                <input type="text" class="form-control form-control-sm item-search" placeholder="Odaberi ili pretraži artikl..." autocomplete="off" ${(typeof isLocked !== 'undefined' && isLocked) ? 'readonly' : ''}>
                <div class="lookup-results item-search-results d-none"></div>
                <div class="item-selected ${prefill ? '' : 'd-none'}"></div>
                <div class="item-warranty-badge ${prefill && prefill.has_warranty ? '' : 'd-none'}"></div>
            </div>
            <div class="col-8">
                <label class="form-label small">Količina</label>
                <input type="number" step="0.001" min="0" inputmode="decimal" enterkeyhint="done" name="quantity[]" class="form-control form-control-sm item-qty" value="${prefill ? (prefill.quantity || '') : ''}" ${(typeof isLocked !== 'undefined' && isLocked) ? 'readonly' : ''} required>
            </div>
            <div class="col-3">
                <label class="form-label small">JM</label>
                <input type="text" name="unit[]" class="form-control form-control-sm item-unit" value="${prefill ? (prefill.unit || '') : ''}" required readonly>
            </div>
            <div class="col-1 text-end">
                ${(typeof isLocked !== 'undefined' && isLocked) ? '' : `<button type="button" class="btn btn-outline-danger btn-sm btn-soft remove-row-btn" onclick="removeRow('${rowId}')">×</button>`}
            </div>
        </div>
    `;
    container.appendChild(row);

    const selectedBox = row.querySelector('.item-selected');
    if (prefill && prefill.code) {
        selectedBox.textContent = `${prefill.code} - ${prefill.name}`;
        selectedBox.classList.remove('d-none');
    }
    updateWarrantyDisplay(row, prefill);
    if (prefill && prefill.item_group_id) {
        const g = (window.groupsData || []).find(x => String(x.id) === String(prefill.item_group_id));
        if (g) {
            row.querySelector('.item-group-id').value = g.id;
            row.querySelector('.item-group-search').value = g.name;
        }
    }
    if (prefill && prefill.item_subgroup_id) {
        const sg = (window.subgroupsData || []).find(x => String(x.id) === String(prefill.item_subgroup_id));
        if (sg) {
            row.querySelector('.item-subgroup-id').value = sg.id;
            row.querySelector('.item-subgroup-search').value = sg.name;
        }
    }
    syncRowVisibility(row);
    if (prefill && prefill.item_id) {
        const item = (window.itemsData || []).find(x => String(x.id) === String(prefill.item_id));
        if (item) applyItemSelection(row, item);
    }
    rowSummaryText(row);
}

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

function getFilteredItems(row, term='') {
    const groupId = row.querySelector('.item-group-id')?.value || '';
    const subgroupId = row.querySelector('.item-subgroup-id')?.value || '';
    term = norm(term);
    let list = (window.itemsData || []).filter(i => {
        if (groupId && String(i.item_group_id || '') !== String(groupId)) return false;
        if (window.hasSubgroups && subgroupId && String(i.item_subgroup_id || '') !== String(subgroupId)) return false;
        return true;
    });
    if (term) list = list.filter(i => norm(i.name).includes(term) || norm(i.code).includes(term));
    list.sort((a,b) => norm(a.name).localeCompare(norm(b.name)));
    return list.slice(0, 30);
}

function filterItemsInRow(input, showAll=false, selectedItemId='') {
    const row = input.closest('.list-card');
    const box = row.querySelector('.item-search-results');
    const term = input.value || '';
    const matches = getFilteredItems(row, showAll ? '' : term);
    renderLookupResults(box, matches, 'item', selectedItemId);
    if (selectedItemId) {
        const selected = matches.find(i => String(i.id) === String(selectedItemId));
        if (selected) applyItemSelection(row, selected);
    }
}


function updateWarrantyDisplay(row, item = null) {
    const hasInput = row.querySelector('.item-has-warranty');
    const monthsInput = row.querySelector('.item-warranty-months');
    const badge = row.querySelector('.item-warranty-badge');
    if (!hasInput || !monthsInput || !badge) return;
    const hasWarranty = item ? parseInt(item.has_warranty || 0, 10) : parseInt(hasInput.value || '0', 10);
    const months = item ? parseInt(item.warranty_months || 0, 10) : parseInt(monthsInput.value || '0', 10);
    hasInput.value = hasWarranty ? '1' : '0';
    monthsInput.value = hasWarranty && months > 0 ? String(months) : '';
    if (hasWarranty) {
        badge.textContent = months > 0 ? `Garancija: ${months} mj` : 'Garancija';
        badge.classList.remove('d-none');
    } else {
        badge.textContent = '';
        badge.classList.add('d-none');
    }
}

function applyItemSelection(row, item) {
    row.querySelector('.item-id').value = item.id;
    row.querySelector('.item-unit').value = item.unit || '';
    row.querySelector('.item-search').value = `${item.code} - ${item.name}`;
    row.querySelector('.item-selected-label').value = `${item.code} - ${item.name}`;
    const selectedBox = row.querySelector('.item-selected');
    selectedBox.textContent = `${item.code} - ${item.name}`;
    selectedBox.classList.remove('d-none');
    updateWarrantyDisplay(row, item);
    closeResults(row);
    rowSummaryText(row);
    if (!(typeof isLocked !== 'undefined' && isLocked)) setTimeout(() => row.querySelector('.item-qty')?.focus(), 50);
}

function applyGroupSelection(row, group) {
    row.querySelector('.item-group-id').value = group.id;
    row.querySelector('.item-group-search').value = group.name;
    row.querySelector('.item-subgroup-id').value = '';
    row.querySelector('.item-subgroup-search').value = '';
    row.querySelector('.item-id').value = '';
    row.querySelector('.item-search').value = '';
    row.querySelector('.item-unit').value = '';
    row.querySelector('.item-selected-label').value = '';
    row.querySelector('.item-selected').textContent = '';
    row.querySelector('.item-selected').classList.add('d-none');
    updateWarrantyDisplay(row, {has_warranty:0, warranty_months:''});
    closeResults(row);
    syncRowVisibility(row);
    rowSummaryText(row);
}

function applySubgroupSelection(row, subgroup) {
    row.querySelector('.item-subgroup-id').value = subgroup.id;
    row.querySelector('.item-subgroup-search').value = subgroup.name;
    row.querySelector('.item-id').value = '';
    row.querySelector('.item-search').value = '';
    row.querySelector('.item-unit').value = '';
    row.querySelector('.item-selected-label').value = '';
    row.querySelector('.item-selected').textContent = '';
    row.querySelector('.item-selected').classList.add('d-none');
    updateWarrantyDisplay(row, {has_warranty:0, warranty_months:''});
    closeResults(row);
    syncRowVisibility(row);
    rowSummaryText(row);
}

function closeResults(row) {
    row.querySelectorAll('.lookup-results').forEach(box => {
        box.classList.add('d-none');
        box.innerHTML = '';
        box._matches = [];
        box._type = '';
    });
}

const itemsContainerEl = document.getElementById('itemsContainer');
itemsContainerEl.addEventListener('input', (e) => {
    if (typeof isLocked !== 'undefined' && isLocked) return;
    const row = e.target.closest('.list-card');
    if (!row) return;
    if (e.target.classList.contains('item-group-search')) {
        row.querySelector('.item-group-id').value = '';
        row.querySelector('.item-subgroup-id').value = '';
        row.querySelector('.item-subgroup-search').value = '';
        row.querySelector('.item-id').value = '';
        row.querySelector('.item-search').value = '';
        row.querySelector('.item-unit').value = '';
        row.querySelector('.item-selected-label').value = '';
        row.querySelector('.item-selected').textContent = '';
        row.querySelector('.item-selected').classList.add('d-none');
        updateWarrantyDisplay(row, {has_warranty:0, warranty_months:''});
        renderLookupResults(row.querySelector('.group-results'), getFilteredGroups(e.target.value || ''), 'group');
        syncRowVisibility(row);
        rowSummaryText(row);
        return;
    }
    if (e.target.classList.contains('item-subgroup-search')) {
        row.querySelector('.item-subgroup-id').value = '';
        row.querySelector('.item-id').value = '';
        row.querySelector('.item-search').value = '';
        row.querySelector('.item-unit').value = '';
        row.querySelector('.item-selected-label').value = '';
        row.querySelector('.item-selected').textContent = '';
        row.querySelector('.item-selected').classList.add('d-none');
        updateWarrantyDisplay(row, {has_warranty:0, warranty_months:''});
        renderLookupResults(row.querySelector('.subgroup-results'), getFilteredSubgroups(row, e.target.value || ''), 'subgroup');
        syncRowVisibility(row);
        rowSummaryText(row);
        return;
    }
    if (e.target.classList.contains('item-search')) {
        filterItemsInRow(e.target, false);
    }
});
itemsContainerEl.addEventListener('focus', (e) => {
    if (typeof isLocked !== 'undefined' && isLocked) return;
    const row = e.target.closest('.list-card');
    if (!row) return;
    if (e.target.classList.contains('item-group-search')) {
        openGroupResults(row, e.target.value || '');
        return;
    }
    if (e.target.classList.contains('item-subgroup-search')) {
        openSubgroupResults(row, e.target.value || '');
        return;
    }
    if (e.target.classList.contains('item-search')) {
        openItemResults(row, e.target.value || '');
    }
}, true);
itemsContainerEl.addEventListener('click', (e) => {
    if (typeof isLocked !== 'undefined' && isLocked) return;
    const row = e.target.closest('.list-card');
    if (!row) return;
    if (e.target.classList.contains('item-group-search')) {
        openGroupResults(row, e.target.value || '');
        return;
    }
    if (e.target.classList.contains('item-subgroup-search')) {
        openSubgroupResults(row, e.target.value || '');
        return;
    }
    if (e.target.classList.contains('item-search')) {
        openItemResults(row, e.target.value || '');
        return;
    }
});
itemsContainerEl.addEventListener('keydown', (e) => {
    if (typeof isLocked !== 'undefined' && isLocked) return;
    const row = e.target.closest('.list-card');
    if (!row) return;
    if (e.target.classList.contains('item-group-search') && e.key === 'ArrowDown') {
        e.preventDefault();
        openGroupResults(row, e.target.value || '');
        return;
    }
    if (e.target.classList.contains('item-subgroup-search') && e.key === 'ArrowDown') {
        e.preventDefault();
        openSubgroupResults(row, e.target.value || '');
        return;
    }
    if (e.target.classList.contains('item-search') && e.key === 'ArrowDown') {
        e.preventDefault();
        openItemResults(row, e.target.value || '');
        return;
    }
});
itemsContainerEl.addEventListener('click', (e) => {
    const btn = e.target.closest('.lookup-result-item');
    if (!btn) return;
    const row = btn.closest('.list-card');
    const box = btn.closest('.lookup-results');
    const matches = box ? (box._matches || []) : [];
    const idx = parseInt(btn.dataset.idx || '0', 10);
    const selected = matches[idx];
    if (!selected) return;
    if (box.classList.contains('group-results')) {
        applyGroupSelection(row, selected);
        if (window.hasSubgroups) row.querySelector('.item-subgroup-search')?.focus();
        else row.querySelector('.item-search')?.focus();
        return;
    }
    if (box.classList.contains('subgroup-results')) {
        applySubgroupSelection(row, selected);
        row.querySelector('.item-search')?.focus();
        return;
    }
    applyItemSelection(row, selected);
});
document.addEventListener('click', (e) => {
    document.querySelectorAll('#itemsContainer .list-card').forEach(row => {
        if (!row.contains(e.target)) closeResults(row);
    });
});

function inlineGroupChanged() {
    if (!window.hasSubgroups) return;
    const groupId = document.getElementById('inline_item_group_id').value;
    const wrap = document.getElementById('inline_subgroup_wrap');
    const sel = document.getElementById('inline_item_subgroup_id');
    if (!groupId) {
        wrap.classList.add('d-none');
        sel.innerHTML = '<option value="0">-- bez podgrupe --</option>';
        return;
    }
    const list = (window.subgroupsData || []).filter(s => String(s.item_group_id) === String(groupId));
    sel.innerHTML = '<option value="0">-- bez podgrupe --</option>' + list.map(s => `<option value="${s.id}">${escapeHtml(s.name)}</option>`).join('');
    wrap.classList.toggle('d-none', list.length === 0);
}

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 || '0';
    const subgroupIdEl = document.getElementById('inline_item_subgroup_id');
    const subgroupId = subgroupIdEl ? (subgroupIdEl.value || '0') : '0';

    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);
    formData.append('item_subgroup_id', subgroupId);

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

function addLaborRow(prefill=null){
    const c = document.getElementById('laborContainer');
    const id = 'labor_' + (laborIndex++);
    const eId  = prefill ? String(prefill.employee_id || '') : '';
    const hrs  = prefill ? (prefill.hours || '') : '';
    const rate = prefill ? (prefill.hourly_rate || '') : '';
    const note = prefill ? (prefill.note || '') : '';

    let opts = '<option value="">-- odaberi radnika --</option>';
    (employeesData || []).forEach(e => {
        const sel = (String(e.id) === eId) ? 'selected' : '';
        opts += `<option value="${e.id}" data-rate="${e.hourly_rate}" ${sel}>${e.first_name} ${e.last_name}</option>`;
    });

    const row = document.createElement('div');
    row.className = 'list-card';
    row.id = id;
    row.innerHTML = `
      <div class="row g-2 align-items-end">
        <div class="col-md-4 col-12">
          <label class="form-label small">Radnik</label>
          <select name="emp_id[]" class="form-select form-select-sm" onchange="laborEmpChanged(this)" required>${opts}</select>
        </div>
        <div class="col-md-2 col-6">
          <label class="form-label small">Sati</label>
          <input type="number" step="0.25" min="0" inputmode="decimal" name="hours[]" class="form-control form-control-sm" value="${hrs}" required>
        </div>
        <input type="hidden" name="rate[]" value="${rate}">
        <div class="col-md-5 col-10">
          <label class="form-label small">Napomena</label>
          <input type="text" name="labor_note[]" class="form-control form-control-sm" value="${note}">
        </div>
        <div class="col-md-1 col-2 text-end">
          <button type="button" class="btn btn-outline-danger btn-sm btn-soft remove-row-btn" onclick="document.getElementById('${id}').remove()">×</button>
        </div>
      </div>`;
    c.appendChild(row);

    const sel = row.querySelector('select');
    if (sel && sel.value && (!rate || parseFloat(rate)===0)) laborEmpChanged(sel);
}

function laborEmpChanged(sel){
    const row = sel.closest('.list-card');
    const rateInput = row.querySelector('input[name="rate[]"]');
    const opt = sel.options[sel.selectedIndex];
    const r = opt ? opt.getAttribute('data-rate') : '';
    if (r && rateInput && (!rateInput.value || parseFloat(rateInput.value)===0)) rateInput.value = r;
}



function minutesBetween(start, end){
    if (!start || !end || !String(start).includes(':') || !String(end).includes(':')) return null;
    const [sh, sm] = String(start).split(':').map(Number);
    const [eh, em] = String(end).split(':').map(Number);
    if ([sh,sm,eh,em].some(v => Number.isNaN(v))) return null;
    let startMin = sh * 60 + sm;
    let endMin = eh * 60 + em;
    if (endMin < startMin) endMin += 24 * 60;
    return endMin - startMin;
}

function calculateBulkHours(){
    const fromEl = document.getElementById('bulk_time_from');
    const toEl = document.getElementById('bulk_time_to');
    const breakEl = document.getElementById('bulk_break_min');
    const outEl = document.getElementById('bulk_hours');
    if (!outEl || !fromEl || !toEl || !breakEl) return 0;
    const diff = minutesBetween(fromEl.value, toEl.value);
    if (diff === null) { outEl.value = ''; return 0; }
    const breakMin = Math.max(0, parseFloat(breakEl.value || '0'));
    const finalMin = Math.max(0, diff - breakMin);
    const hrs = finalMin / 60;
    outEl.value = hrs.toFixed(2);
    return hrs;
}

function employeeFullName(e){
    return `${e.first_name || ''} ${e.last_name || ''}`.trim();
}

function renderBulkEmployees(term=''){
    const wrap = document.getElementById('bulkEmployeeList');
    if (!wrap) return;
    const q = norm(term || '');
    let list = (employeesData || []).slice();
    if (q) list = list.filter(e => norm(employeeFullName(e)).includes(q));
    if (!list.length) {
        wrap.innerHTML = '<div class="bulk-employee-empty">Nema radnika za prikaz.</div>';
        return;
    }
    wrap.innerHTML = list.map(e => {
        const name = escapeHtml(employeeFullName(e));
        return `<label class="bulk-employee-item" data-name="${escapeHtml(employeeFullName(e))}">
            <input type="checkbox" class="bulk-employee-check" value="${e.id}">
            <div class="bulk-employee-main">
              <div class="bulk-employee-name">${name}</div>
            </div>
        </label>`;
    }).join('');
}

function toggleBulkEmployees(state){
    const wrap = document.getElementById('bulkEmployeeList');
    if (!wrap) return;
    wrap.querySelectorAll('.bulk-employee-check').forEach(ch => { ch.checked = !!state; });
}

function addSelectedEmployees(){
    const wrap = document.getElementById('bulkEmployeeList');
    if (!wrap) return;
    const checked = [...wrap.querySelectorAll('.bulk-employee-check:checked')];
    if (!checked.length) { alert('Označi barem jednog radnika.'); return; }
    const hours = calculateBulkHours();
    if (!hours || hours <= 0) { alert('Provjeri vrijeme od/do i pauzu.'); return; }
    const noteEl = document.getElementById('bulk_labor_note');
    const fromEl = document.getElementById('bulk_time_from');
    const toEl = document.getElementById('bulk_time_to');
    const rangeText = (fromEl && toEl && fromEl.value && toEl.value) ? `${fromEl.value}-${toEl.value}` : '';
    const baseNote = noteEl ? (noteEl.value || '').trim() : '';
    const finalNote = [rangeText, baseNote].filter(Boolean).join(' | ');
    checked.forEach(ch => {
        const emp = (employeesData || []).find(e => String(e.id) === String(ch.value));
        if (!emp) return;
        addLaborRow({
            employee_id: emp.id,
            hours: hours.toFixed(2),
            hourly_rate: emp.hourly_rate || '',
            note: finalNote
        });
        ch.checked = false;
    });
}


const projectLabelInput = document.getElementById('project_label');
const projectResultsBox = document.querySelector('.project-results');
if (projectLabelInput) {
    projectLabelInput.addEventListener('input', function(){
        document.getElementById('project_id').value = '';
        renderProjectResults(this.value || '');
    });
    projectLabelInput.addEventListener('focus', function(){
        renderProjectResults(this.value || '');
    });
    projectLabelInput.addEventListener('click', function(){
        renderProjectResults(this.value || '');
    });
    projectLabelInput.addEventListener('keydown', function(e){
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            renderProjectResults(this.value || '');
        }
    });
}
document.addEventListener('click', function(e){
    if (projectLabelInput && projectResultsBox && !projectLabelInput.closest('.mb-3').contains(e.target)) {
        projectResultsBox.classList.add('d-none');
    }
});
document.addEventListener('click', function(e){
    const btn = e.target.closest('.project-results .lookup-result-item');
    if (!btn) return;
    const box = btn.closest('.lookup-results');
    const matches = box ? (box._matches || []) : [];
    const idx = parseInt(btn.dataset.idx || '0', 10);
    const selected = matches[idx];
    if (selected) applyProjectSelection(selected);
});


const bulkEmployeeSearch = document.getElementById('bulk_employee_search');
if (bulkEmployeeSearch) {
    bulkEmployeeSearch.addEventListener('input', function(){ renderBulkEmployees(this.value || ''); });
    bulkEmployeeSearch.addEventListener('focus', function(){ renderBulkEmployees(this.value || ''); });
    bulkEmployeeSearch.addEventListener('click', function(){ renderBulkEmployees(this.value || ''); });
}
['bulk_time_from','bulk_time_to','bulk_break_min'].forEach(id => {
    const el = document.getElementById(id);
    if (el) {
        el.addEventListener('input', calculateBulkHours);
        el.addEventListener('change', calculateBulkHours);
    }
});
calculateBulkHours();
renderBulkEmployees('');

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 => {
        if (!row.querySelector('.item-id').value) ok = false;
    });
    if (!ok) {
        e.preventDefault();
        alert('Za svaku stavku morate odabrati artikl iz pretrage.');
    }
});

addRow();
</script>

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