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

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

$hasSubgroups = table_exists($mysqli, 'item_subgroups');

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

if ($hasSubgroups) {
    $stmt = $mysqli->prepare('SELECT code, name, unit, item_group_id, item_subgroup_id FROM items WHERE id = ?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $stmt->bind_result($code, $name, $unit, $group_id, $subgroup_id);
} else {
    $stmt = $mysqli->prepare('SELECT code, name, unit, item_group_id FROM items WHERE id = ?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $stmt->bind_result($code, $name, $unit, $group_id);
    $subgroup_id = 0;
}
if (!$stmt->fetch()) {
    $stmt->close();
    echo '<div class="alert alert-danger m-3">Artikl nije pronađen.</div>';
    require_once 'footer.php';
    exit;
}
$stmt->close();

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $unit = trim($_POST['unit'] ?? '');
    $group_id = (int)($_POST['item_group_id'] ?? 0);
    $subgroup_id = (int)($_POST['item_subgroup_id'] ?? 0);

    if ($name === '' || $unit === '') {
        echo '<div class="alert alert-danger m-3">Naziv i JM su obavezni.</div>';
    } else {
        if ($hasSubgroups) {
            if ($group_id > 0 && $subgroup_id > 0) {
                $stmtU = $mysqli->prepare('UPDATE items SET name=?, unit=?, item_group_id=?, item_subgroup_id=? WHERE id=?');
                $stmtU->bind_param('ssiii', $name, $unit, $group_id, $subgroup_id, $id);
            } elseif ($group_id > 0) {
                $stmtU = $mysqli->prepare('UPDATE items SET name=?, unit=?, item_group_id=?, item_subgroup_id=NULL WHERE id=?');
                $stmtU->bind_param('ssii', $name, $unit, $group_id, $id);
            } else {
                $stmtU = $mysqli->prepare('UPDATE items SET name=?, unit=?, item_group_id=NULL, item_subgroup_id=NULL WHERE id=?');
                $stmtU->bind_param('ssi', $name, $unit, $id);
            }
        } else {
            if ($group_id > 0) {
                $stmtU = $mysqli->prepare('UPDATE items SET name=?, unit=?, item_group_id=? WHERE id=?');
                $stmtU->bind_param('ssii', $name, $unit, $group_id, $id);
            } else {
                $stmtU = $mysqli->prepare('UPDATE items SET name=?, unit=?, item_group_id=NULL WHERE id=?');
                $stmtU->bind_param('ssi', $name, $unit, $id);
            }
        }
        $stmtU->execute();
        $stmtU->close();
        header('Location: items.php?msg=' . urlencode('Artikl ažuriran.'));
        exit;
    }
}
?>
<div class="row g-3 mb-3"><div class="col"><div class="section-title">Uredi artikl</div></div></div>
<div class="card card-soft">
    <div class="card-body card-soft-body">
        <form method="post">
            <div class="mb-2">
                <label class="form-label">Šifra</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($code); ?>" disabled>
            </div>
            <div class="mb-2">
                <label class="form-label">Grupa</label>
                <select name="item_group_id" id="item_group_id" class="form-select form-select-sm" onchange="refreshSubgroups()">
                    <option value="0">-- bez grupe --</option>
                    <?php foreach ($groups as $g): ?>
                        <option value="<?php echo (int)$g['id']; ?>" <?php echo ((int)$group_id === (int)$g['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($g['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-2">
                <label class="form-label">Podgrupa</label>
                <select name="item_subgroup_id" id="item_subgroup_id" class="form-select form-select-sm" <?php echo $hasSubgroups ? '' : 'disabled'; ?>></select>
            </div>
            <div class="mb-2">
                <label class="form-label">Naziv</label>
                <input type="text" name="name" class="form-control" required value="<?php echo htmlspecialchars($name); ?>">
            </div>
            <div class="mb-2">
                <label class="form-label">Jedinica mjere</label>
                <input type="text" name="unit" class="form-control" required value="<?php echo htmlspecialchars($unit); ?>">
            </div>
            <button class="btn btn-primary btn-soft" type="submit">Spremi</button>
            <a href="items.php" class="btn btn-outline-secondary btn-soft">Natrag</a>
        </form>
    </div>
</div>
<script>
const subgroupsData = <?php echo json_encode($subgroups, JSON_UNESCAPED_UNICODE); ?>;
const selectedSubgroupId = <?php echo json_encode((string)$subgroup_id); ?>;
function refreshSubgroups() {
    const groupId = document.getElementById('item_group_id').value;
    const sel = document.getElementById('item_subgroup_id');
    if (!sel) return;
    let html = '<option value="0">-- bez podgrupe --</option>';
    (subgroupsData || []).forEach(s => {
        if (String(s.item_group_id) === String(groupId)) {
            const selected = String(selectedSubgroupId) === String(s.id) ? 'selected' : '';
            html += `<option value="${s.id}" ${selected}>${String(s.name || '')}</option>`;
        }
    });
    sel.innerHTML = html;
}
refreshSubgroups();
</script>
<?php require_once 'footer.php'; ?>
