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

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

// novi artikl
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_item'])) {
    $group_id = (int)($_POST['item_group_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 {
        // automatska šifra (max+1)
        $res = $mysqli->query("SELECT MAX(CAST(code AS UNSIGNED)) AS maxcode FROM items");
        $row = $res->fetch_assoc();
        $next = (int)($row['maxcode'] ?? 0) + 1;
        $code = (string)$next;

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

// grupe
$groupsRes = $mysqli->query("SELECT id, name FROM item_groups ORDER BY name");

// pretraga artikala
$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}%'";
}

$sql = "SELECT i.*, g.name AS group_name
        FROM items i
        LEFT JOIN item_groups g ON g.id = i.item_group_id
        {$where}
        ORDER BY i.code";
$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, grupe i popis 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">
            <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">
                            <option value="0">-- bez grupe --</option>
                            <?php
                            $groupsRes->data_seek(0);
                            while ($g = $groupsRes->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</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 (int)$items->num_rows; ?> 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 ili grupa..."
                                   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>JM</th>
                            <th class="text-end">Akcije</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php while ($i = $items->fetch_assoc()): ?>
                            <tr>
                                <td class="fw-semibold">
                                    <a href="item_detail.php?id=<?php echo $i['id']; ?>">
                                        <?php echo htmlspecialchars($i['code']); ?>
                                    </a>
                                </td>
                                <td>
                                    <a href="item_detail.php?id=<?php echo $i['id']; ?>">
                                        <?php echo htmlspecialchars($i['name']); ?>
                                    </a>
                                </td>
                                <td><?php echo htmlspecialchars($i['group_name']); ?></td>
                                <td><?php echo htmlspecialchars($i['unit']); ?></td>
                                <td class="text-end">
                                    <a href="item_edit.php?id=<?php echo $i['id']; ?>"
                                       class="btn btn-sm btn-outline-primary btn-soft">Uredi</a>
                                    <a href="items.php?delete_id=<?php echo $i['id']; ?>"
                                       class="btn btn-sm btn-outline-danger btn-soft"
                                       onclick="return confirm('Obrisati artikl?');">Obriši</a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>

                <div class="d-md-none">
                    <?php
                    $items->data_seek(0);
                    if ($items->num_rows === 0): ?>
                        <div class="text-muted small">Nema artikala.</div>
                    <?php endif; ?>
                    <?php while ($i = $items->fetch_assoc()): ?>
                        <div class="list-card">
                            <div class="list-card-title">
                                <?php echo htmlspecialchars($i['name']); ?>
                            </div>
                            <div class="list-card-sub">
                                Šifra: <?php echo htmlspecialchars($i['code']); ?>
                            </div>
                            <div class="list-card-meta">
                                Grupa: <?php echo htmlspecialchars($i['group_name']); ?> •
                                JM: <?php echo htmlspecialchars($i['unit']); ?>
                            </div>
                            <div class="d-flex justify-content-end gap-1 mt-1">
                                <a href="item_edit.php?id=<?php echo $i['id']; ?>"
                                   class="btn btn-outline-primary btn-sm">Uredi</a>
                                <a href="items.php?delete_id=<?php echo $i['id']; ?>"
                                   class="btn btn-outline-danger btn-sm"
                                   onclick="return confirm('Obrisati artikl?');">X</a>
                            </div>
                        </div>
                    <?php endwhile; ?>
                </div>

            </div>
        </div>
    </div>
</div>

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