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

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;
}

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

$hasSubgroups       = table_exists($mysqli, 'item_subgroups');
$itemHasSubgroupCol = column_exists($mysqli, 'items', 'item_subgroup_id');
$hasWarrantyCols    = column_exists($mysqli, 'items', 'has_warranty') && column_exists($mysqli, 'items', 'warranty_months');

$sql = 'SELECT code, name, unit, item_group_id';
if ($itemHasSubgroupCol) $sql .= ', item_subgroup_id';
if ($hasWarrantyCols) $sql .= ', has_warranty, warranty_months';
$sql .= ' FROM items WHERE id = ?';

$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();

if ($itemHasSubgroupCol && $hasWarrantyCols) {
    $stmt->bind_result($code, $name, $unit, $group_id, $subgroup_id, $has_warranty, $warranty_months);
} elseif ($itemHasSubgroupCol) {
    $stmt->bind_result($code, $name, $unit, $group_id, $subgroup_id);
    $has_warranty = 0;
    $warranty_months = null;
} elseif ($hasWarrantyCols) {
    $stmt->bind_result($code, $name, $unit, $group_id, $has_warranty, $warranty_months);
    $subgroup_id = 0;
} else {
    $stmt->bind_result($code, $name, $unit, $group_id);
    $subgroup_id = 0;
    $has_warranty = 0;
    $warranty_months = null;
}

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();

$groups = $mysqli->query('SELECT id, name FROM item_groups ORDER BY name');
$subgroups = ($hasSubgroups && $itemHasSubgroupCol)
    ? $mysqli->query('SELECT id, item_group_id, name FROM item_subgroups ORDER BY name')
    : false;
$subgroupsData = [];
if ($subgroups) {
    while ($sg = $subgroups->fetch_assoc()) $subgroupsData[] = $sg;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name            = trim($_POST['name'] ?? '');
    $unit            = trim($_POST['unit'] ?? '');
    $group_id        = (int)($_POST['item_group_id'] ?? 0);
    $subgroup_id     = ($hasSubgroups && $itemHasSubgroupCol) ? (int)($_POST['item_subgroup_id'] ?? 0) : 0;
    $has_warranty    = $hasWarrantyCols ? (int)!empty($_POST['has_warranty']) : 0;
    $warranty_months = $hasWarrantyCols ? (int)($_POST['warranty_months'] ?? 0) : 0;
    $warranty_months = $has_warranty ? max(0, $warranty_months) : 0;

    if ($name === '' || $unit === '') {
        echo '<div class="alert alert-danger m-3">Naziv i JM su obavezni.</div>';
    } else {
        if ($itemHasSubgroupCol && $hasWarrantyCols) {
            $stmtU = $mysqli->prepare('UPDATE items SET name=?, unit=?, item_group_id=?, item_subgroup_id=?, has_warranty=?, warranty_months=? WHERE id=?');
            $stmtU->bind_param('ssiiiii', $name, $unit, $group_id, $subgroup_id, $has_warranty, $warranty_months, $id);
        } elseif ($itemHasSubgroupCol) {
            $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 ($hasWarrantyCols) {
            $stmtU = $mysqli->prepare('UPDATE items SET name=?, unit=?, item_group_id=?, has_warranty=?, warranty_months=? WHERE id=?');
            $stmtU->bind_param('ssiiii', $name, $unit, $group_id, $has_warranty, $warranty_months, $id);
        } else {
            $stmtU = $mysqli->prepare('UPDATE items SET name=?, unit=?, item_group_id=? WHERE id=?');
            $stmtU->bind_param('ssii', $name, $unit, $group_id, $id);
        }
        $stmtU->execute();
        $stmtU->close();
        header('Location: items.php?msg=' . urlencode('Artikl ažuriran.'));
        exit;
    }
}

$subgroupsJson = json_encode($subgroupsData, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
if ($subgroupsJson === false) $subgroupsJson = '[]';
?>
<div class="row g-3 mb-3">
    <div class="col">
        <div class="section-title">Uredi artikl</div>
    </div>
</div>
<?php if (!$hasWarrantyCols): ?>
<div class="alert alert-warning m-3 mb-0">Polja za garanciju još ne postoje u tablici <strong>items</strong>. Pokreni SQL migraciju pa će se prikazati i ova opcija.</div>
<?php endif; ?>
<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_edit" class="form-select form-select-sm">
                    <option value="0">-- bez grupe --</option>
                    <?php
                    $groups->data_seek(0);
                    while ($g = $groups->fetch_assoc()):
                        $sel = ($group_id == (int)$g['id']) ? 'selected' : '';
                    ?>
                        <option value="<?php echo (int)$g['id']; ?>" <?php echo $sel; ?>>
                            <?php echo htmlspecialchars($g['name']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <?php if ($hasSubgroups && $itemHasSubgroupCol): ?>
            <div class="mb-2">
                <label class="form-label">Podgrupa</label>
                <select name="item_subgroup_id" id="item_subgroup_id_edit" class="form-select form-select-sm">
                    <option value="0">-- bez podgrupe --</option>
                </select>
            </div>
            <?php endif; ?>
            <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>
            <?php if ($hasWarrantyCols): ?>
            <div class="form-check form-switch mb-2 mt-3">
                <input class="form-check-input" type="checkbox" role="switch" id="has_warranty_edit" name="has_warranty" value="1" <?php echo !empty($has_warranty) ? 'checked' : ''; ?>>
                <label class="form-check-label" for="has_warranty_edit">Artikl ima garanciju</label>
            </div>
            <div class="mb-2" id="warranty_months_wrap_edit" style="display:none;">
                <label class="form-label">Garancija (mjeseci)</label>
                <input type="number" min="0" step="1" name="warranty_months" id="warranty_months_edit" class="form-control"
                       value="<?php echo (int)$warranty_months > 0 ? (int)$warranty_months : ''; ?>"
                       placeholder="npr. 24">
            </div>
            <?php endif; ?>
            <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 itemSubgroupsEditData = <?php echo $subgroupsJson; ?>;
const initialEditSubgroupId = <?php echo (int)$subgroup_id; ?>;

function filterEditSubgroups() {
    const groupSel = document.getElementById('item_group_id_edit');
    const subgroupSel = document.getElementById('item_subgroup_id_edit');
    if (!groupSel || !subgroupSel) return;

    const groupId = String(groupSel.value || '0');
    let html = '<option value="0">-- bez podgrupe --</option>';
    itemSubgroupsEditData
        .filter(s => String(s.item_group_id) === groupId)
        .forEach(s => {
            const sel = String(initialEditSubgroupId) === String(s.id) ? 'selected' : '';
            html += `<option value="${s.id}" ${sel}>${String(s.name || '')}</option>`;
        });
    subgroupSel.innerHTML = html;
}

function toggleWarrantyEdit() {
    const chk = document.getElementById('has_warranty_edit');
    const wrap = document.getElementById('warranty_months_wrap_edit');
    const inp = document.getElementById('warranty_months_edit');
    if (!chk || !wrap || !inp) return;
    wrap.style.display = chk.checked ? '' : 'none';
    if (!chk.checked) inp.value = '';
}

document.addEventListener('DOMContentLoaded', function(){
    const groupSel = document.getElementById('item_group_id_edit');
    if (groupSel) {
        groupSel.addEventListener('change', function(){
            const subgroupSel = document.getElementById('item_subgroup_id_edit');
            if (subgroupSel) subgroupSel.dataset.manual = '1';
            filterEditSubgroups();
        });
        filterEditSubgroups();
    }
    const warrantyChk = document.getElementById('has_warranty_edit');
    if (warrantyChk) {
        warrantyChk.addEventListener('change', toggleWarrantyEdit);
        toggleWarrantyEdit();
    }
});
</script>
<?php require_once 'footer.php'; ?>
