<?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');

if (!$hasSubgroups) {
    echo '<div class="alert alert-warning mb-3">Nedostaje tablica <strong>item_subgroups</strong>. Pokreni SQL migraciju prije korištenja podgrupa.</div>';
}

// nova grupa
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_group'])) {
    $gname = trim($_POST['group_name'] ?? '');
    if ($gname === '') {
        echo '<div class="alert alert-danger mb-3">Naziv grupe je obavezan.</div>';
    } else {
        $stmt = $mysqli->prepare("INSERT INTO item_groups (name) VALUES (?)");
        $stmt->bind_param('s', $gname);
        $stmt->execute();
        $stmt->close();
        echo '<div class="alert alert-success mb-3">Grupa dodana.</div>';
    }
}

// nova podgrupa
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_subgroup'])) {
    $group_id = (int)($_POST['subgroup_group_id'] ?? 0);
    $sgname = trim($_POST['subgroup_name'] ?? '');

    if (!$hasSubgroups) {
        echo '<div class="alert alert-danger mb-3">Tablica item_subgroups ne postoji.</div>';
    } elseif ($group_id <= 0 || $sgname === '') {
        echo '<div class="alert alert-danger mb-3">Grupa i naziv podgrupe su obavezni.</div>';
    } else {
        $stmt = $mysqli->prepare("INSERT INTO item_subgroups (item_group_id, name) VALUES (?, ?)");
        $stmt->bind_param('is', $group_id, $sgname);
        $stmt->execute();
        $stmt->close();
        echo '<div class="alert alert-success mb-3">Podgrupa dodana.</div>';
    }
}

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

    if ($name === '' || $unit === '') {
        echo '<div class="alert alert-danger mb-3">Naziv i JM su obavezni.</div>';
    } else {
        $res = $mysqli->query("SELECT MAX(CAST(code AS UNSIGNED)) AS maxcode FROM items");
        $row = $res ? $res->fetch_assoc() : ['maxcode' => 0];
        $next = (int)($row['maxcode'] ?? 0) + 1;
        $code = (string)$next;

        if ($hasSubgroups) {
            if ($group_id > 0 && $subgroup_id > 0) {
                $stmt = $mysqli->prepare("INSERT INTO items (code, name, unit, item_group_id, item_subgroup_id) VALUES (?,?,?,?,?)");
                $stmt->bind_param('sssii', $code, $name, $unit, $group_id, $subgroup_id);
            } elseif ($group_id > 0) {
                $stmt = $mysqli->prepare("INSERT INTO items (code, name, unit, item_group_id, item_subgroup_id) VALUES (?,?,?, ?, NULL)");
                $stmt->bind_param('sssi', $code, $name, $unit, $group_id);
            } else {
                $stmt = $mysqli->prepare("INSERT INTO items (code, name, unit, item_group_id, item_subgroup_id) VALUES (?,?,?, NULL, NULL)");
                $stmt->bind_param('sss', $code, $name, $unit);
            }
        } else {
            if ($group_id > 0) {
                $stmt = $mysqli->prepare("INSERT INTO items (code, name, unit, item_group_id) VALUES (?,?,?,?)");
                $stmt->bind_param('sssi', $code, $name, $unit, $group_id);
            } else {
                $stmt = $mysqli->prepare("INSERT INTO items (code, name, unit) VALUES (?,?,?)");
                $stmt->bind_param('sss', $code, $name, $unit);
            }
        }
        $stmt->execute();
        $stmt->close();
        echo '<div class="alert alert-success mb-3">Artikl dodan. Šifra: ' . htmlspecialchars($code) . '</div>';
    }
}

// brisanje artikla
if (isset($_GET['delete_id'])) {
    $id = (int)($_GET['delete_id'] ?? 0);
    if ($id > 0) {
        try {
            $stmt = $mysqli->prepare("DELETE FROM items WHERE id = ?");
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $stmt->close();
            echo '<div class="alert alert-success mb-3">Artikl obrisan.</div>';
        } catch (mysqli_sql_exception $ex) {
            echo '<div class="alert alert-danger mb-3">Artikl nije moguće obrisati jer se koristi u nalozima ili primkama.</div>';
        }
    }
}

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

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

$search = trim($_GET['q'] ?? '');
$where = '';
if ($search !== '') {
    $esc = $mysqli->real_escape_string($search);
    $where = "WHERE i.code LIKE '%{$esc}%' OR i.name LIKE '%{$esc}%' OR g.name LIKE '%{$esc}%'";
    if ($hasSubgroups) {
        $where .= " OR sg.name LIKE '%{$esc}%'";
    }
}

$sql = "SELECT i.*, g.name AS group_name";
if ($hasSubgroups) $sql .= ", sg.name AS subgroup_name";
$sql .= "\n        FROM items i\n        LEFT JOIN item_groups g ON g.id = i.item_group_id\n";
if ($hasSubgroups) $sql .= "        LEFT JOIN item_subgroups sg ON sg.id = i.item_subgroup_id\n";
$sql .= "        {$where}\n        ORDER BY g.name, ";
$sql .= $hasSubgroups ? "sg.name, " : "";
$sql .= "i.name";
$items = $mysqli->query($sql);
?>
<div class="row g-3 mb-3 align-items-center">
    <div class="col">
        <div class="section-title">Artikli</div>
        <div class="text-muted small">Unos grupa, podgrupa i artikala</div>
    </div>
</div>

<div class="row g-3">
    <div class="col-12 col-lg-4">
        <div class="card card-soft mb-3">
            <div class="card-header card-soft-header"><span class="fw-semibold">Nova grupa artikala</span></div>
            <div class="card-body card-soft-body">
                <form method="post">
                    <input type="hidden" name="create_group" value="1">
                    <div class="mb-2">
                        <label class="form-label">Naziv grupe</label>
                        <input type="text" name="group_name" class="form-control" required>
                    </div>
                    <button class="btn btn-primary btn-soft w-100" type="submit">Spremi grupu</button>
                </form>
            </div>
        </div>

        <div class="card card-soft mb-3">
            <div class="card-header card-soft-header"><span class="fw-semibold">Nova podgrupa</span></div>
            <div class="card-body card-soft-body">
                <form method="post">
                    <input type="hidden" name="create_subgroup" value="1">
                    <div class="mb-2">
                        <label class="form-label">Grupa</label>
                        <select name="subgroup_group_id" class="form-select" required>
                            <option value="0">-- odaberi grupu --</option>
                            <?php foreach ($groups as $g): ?>
                                <option value="<?php echo (int)$g['id']; ?>"><?php echo htmlspecialchars($g['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Naziv podgrupe</label>
                        <input type="text" name="subgroup_name" class="form-control" required>
                    </div>
                    <button class="btn btn-outline-primary btn-soft w-100" type="submit" <?php echo $hasSubgroups ? '' : 'disabled'; ?>>Spremi podgrupu</button>
                </form>
            </div>
        </div>

        <div class="card card-soft">
            <div class="card-header card-soft-header"><span class="fw-semibold">Novi artikl</span></div>
            <div class="card-body card-soft-body">
                <form method="post">
                    <input type="hidden" name="create_item" value="1">
                    <div class="mb-2">
                        <label class="form-label">Grupa artikla</label>
                        <select name="item_group_id" class="form-select" id="item_group_id" onchange="refreshSubgroups()">
                            <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>
                    <div class="mb-2">
                        <label class="form-label">Podgrupa</label>
                        <select name="item_subgroup_id" class="form-select" id="item_subgroup_id" <?php echo $hasSubgroups ? '' : 'disabled'; ?>>
                            <option value="0">-- bez podgrupe --</option>
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Naziv</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Jedinica mjere</label>
                        <input type="text" name="unit" class="form-control" placeholder="kom, m, kg..." required>
                    </div>
                    <p class="small text-muted mb-2">Šifra se dodjeljuje automatski kao sljedeći broj u nizu.</p>
                    <button class="btn btn-primary btn-soft w-100" type="submit">Spremi artikl</button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-12 col-lg-8">
        <div class="card card-soft">
            <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
                <span class="fw-semibold">Popis artikala</span>
                <span class="pill-counter d-none d-sm-inline"><?php echo $items ? (int)$items->num_rows : 0; ?> artikala</span>
            </div>
            <div class="card-body card-soft-body">
                <div class="mb-3">
                    <form method="get" class="row g-2 align-items-end">
                        <div class="col-12 col-md-6">
                            <label class="form-label">Pretraga artikala</label>
                            <input type="text" name="q" class="form-control form-control-sm" placeholder="šifra, naziv, grupa ili podgrupa..." value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="col-auto"><button class="btn btn-outline-primary btn-soft btn-sm" type="submit">Primijeni</button></div>
                        <?php if ($search !== ''): ?>
                            <div class="col-auto"><a href="items.php" class="btn btn-outline-secondary btn-soft btn-sm">Reset</a></div>
                        <?php endif; ?>
                    </form>
                </div>

                <div class="table-responsive d-none d-md-block">
                    <table class="table table-sm align-middle">
                        <thead class="small text-muted">
                            <tr>
                                <th>Šifra</th>
                                <th>Naziv</th>
                                <th>Grupa</th>
                                <th>Podgrupa</th>
                                <th>JM</th>
                                <th class="text-end">Akcije</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($items): while ($i = $items->fetch_assoc()): ?>
                            <tr>
                                <td class="fw-semibold"><a href="item_detail.php?id=<?php echo (int)$i['id']; ?>"><?php echo htmlspecialchars($i['code']); ?></a></td>
                                <td><a href="item_detail.php?id=<?php echo (int)$i['id']; ?>"><?php echo htmlspecialchars($i['name']); ?></a></td>
                                <td><?php echo htmlspecialchars($i['group_name'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($i['subgroup_name'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($i['unit']); ?></td>
                                <td class="text-end">
                                    <a href="item_edit.php?id=<?php echo (int)$i['id']; ?>" class="btn btn-sm btn-outline-primary btn-soft">Uredi</a>
                                    <a href="items.php?delete_id=<?php echo (int)$i['id']; ?>" class="btn btn-sm btn-outline-danger btn-soft" onclick="return confirm('Obrisati artikl?');">Obriši</a>
                                </td>
                            </tr>
                        <?php endwhile; endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="d-md-none">
                    <?php if ($items && $items->num_rows > 0): $items->data_seek(0); while ($i = $items->fetch_assoc()): ?>
                        <div class="list-card mb-2">
                            <div class="d-flex justify-content-between gap-2">
                                <div>
                                    <div class="fw-semibold"><?php echo htmlspecialchars($i['name']); ?></div>
                                    <div class="small text-muted">Šifra: <?php echo htmlspecialchars($i['code']); ?></div>
                                    <div class="small text-muted">Grupa: <?php echo htmlspecialchars($i['group_name'] ?? '-'); ?></div>
                                    <div class="small text-muted">Podgrupa: <?php echo htmlspecialchars($i['subgroup_name'] ?? '-'); ?></div>
                                    <div class="small text-muted">JM: <?php echo htmlspecialchars($i['unit']); ?></div>
                                </div>
                                <div class="text-end">
                                    <a href="item_edit.php?id=<?php echo (int)$i['id']; ?>" class="btn btn-sm btn-outline-primary btn-soft mb-1">Uredi</a>
                                    <a href="items.php?delete_id=<?php echo (int)$i['id']; ?>" class="btn btn-sm btn-outline-danger btn-soft" onclick="return confirm('Obrisati artikl?');">Obriši</a>
                                </div>
                            </div>
                        </div>
                    <?php endwhile; else: ?>
                        <div class="text-muted">Nema artikala.</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
const subgroupsData = <?php echo json_encode($subgroups, JSON_UNESCAPED_UNICODE); ?>;
function refreshSubgroups() {
    const groupId = document.getElementById('item_group_id').value;
    const subgroup = document.getElementById('item_subgroup_id');
    if (!subgroup) return;
    let html = '<option value="0">-- bez podgrupe --</option>';
    (subgroupsData || []).forEach(s => {
        if (String(s.item_group_id) === String(groupId)) {
            html += `<option value="${s.id}">${String(s.name || '')}</option>`;
        }
    });
    subgroup.innerHTML = html;
}
refreshSubgroups();
</script>
<?php require_once 'footer.php'; ?>
