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

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

// 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 ($hasSubgroups && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_subgroup'])) {
    $group_id = (int)($_POST['subgroup_group_id'] ?? 0);
    $sgname   = trim($_POST['subgroup_name'] ?? '');

    if ($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  = ($hasSubgroups && $itemHasSubgroupCol) ? (int)($_POST['item_subgroup_id'] ?? 0) : 0;
    $name         = trim($_POST['name'] ?? '');
    $unit         = trim($_POST['unit'] ?? '');
    $has_warranty = $hasWarrantyCols ? (int)!empty($_POST['has_warranty']) : 0;
    $warranty_m   = $hasWarrantyCols ? (int)($_POST['warranty_months'] ?? 0) : 0;
    $warranty_m   = $has_warranty ? max(0, $warranty_m) : 0;

    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 ($hasWarrantyCols && $hasSubgroups && $itemHasSubgroupCol) {
            $stmt = $mysqli->prepare("INSERT INTO items (code, name, unit, item_group_id, item_subgroup_id, has_warranty, warranty_months) VALUES (?,?,?,?,?,?,?)");
            $groupForDb = $group_id > 0 ? $group_id : null;
            $subgroupForDb = $subgroup_id > 0 ? $subgroup_id : null;
            $stmt->bind_param('sssiiii', $code, $name, $unit, $groupForDb, $subgroupForDb, $has_warranty, $warranty_m);
        } elseif ($hasWarrantyCols) {
            $stmt = $mysqli->prepare("INSERT INTO items (code, name, unit, item_group_id, has_warranty, warranty_months) VALUES (?,?,?,?,?,?)");
            $groupForDb = $group_id > 0 ? $group_id : null;
            $stmt->bind_param('sssiii', $code, $name, $unit, $groupForDb, $has_warranty, $warranty_m);
        } elseif ($hasSubgroups && $itemHasSubgroupCol) {
            $stmt = $mysqli->prepare("INSERT INTO items (code, name, unit, item_group_id, item_subgroup_id) VALUES (?,?,?,?,?)");
            $groupForDb = $group_id > 0 ? $group_id : null;
            $subgroupForDb = $subgroup_id > 0 ? $subgroup_id : null;
            $stmt->bind_param('sssii', $code, $name, $unit, $groupForDb, $subgroupForDb);
        } elseif ($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 / podgrupe
$groupsRes = $mysqli->query("SELECT id, name FROM item_groups ORDER BY name");
$subgroupsRes = $hasSubgroups ? $mysqli->query("SELECT id, item_group_id, name FROM item_subgroups ORDER BY name") : false;
$subgroupsData = [];
if ($subgroupsRes) {
    while ($sg = $subgroupsRes->fetch_assoc()) $subgroupsData[] = $sg;
}

// 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}%'";
    if ($hasSubgroups && $itemHasSubgroupCol) {
        $where .= " OR sg.name LIKE '%{$esc}%'";
    }
}

$selectWarranty = $hasWarrantyCols ? ", i.has_warranty, i.warranty_months" : ", 0 AS has_warranty, NULL AS warranty_months";
$joinSubgroup   = ($hasSubgroups && $itemHasSubgroupCol)
    ? "LEFT JOIN item_subgroups sg ON sg.id = i.item_subgroup_id"
    : "";
$selectSubgroup = ($hasSubgroups && $itemHasSubgroupCol)
    ? ", sg.name AS subgroup_name"
    : ", NULL AS subgroup_name";

$sql = "SELECT i.*, g.name AS group_name{$selectSubgroup}{$selectWarranty}
        FROM items i
        LEFT JOIN item_groups g ON g.id = i.item_group_id
        {$joinSubgroup}
        {$where}
        ORDER BY CAST(i.code AS UNSIGNED), i.code";
$items = $mysqli->query($sql);
$subgroupsJson = json_encode($subgroupsData, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
if ($subgroupsJson === false) $subgroupsJson = '[]';
?>
<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, podgrupe i garancija artikala</div>
    </div>
</div>

<?php if (!$hasWarrantyCols): ?>
    <div class="alert alert-warning mb-3">
        Polja za garanciju još ne postoje u tablici <strong>items</strong>. Pokreni SQL migraciju ispod pa će se prikazati unos garancije.
    </div>
<?php endif; ?>

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

        <?php if ($hasSubgroups): ?>
        <div class="card card-soft mb-3">
            <div class="card-header card-soft-header">
                <span class="fw-semibold">Nova podgrupa artikala</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
                            $groupsRes->data_seek(0);
                            while ($g = $groupsRes->fetch_assoc()): ?>
                                <option value="<?php echo (int)$g['id']; ?>"><?php echo htmlspecialchars($g['name']); ?></option>
                            <?php endwhile; ?>
                        </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-primary btn-soft w-100" type="submit">Spremi podgrupu</button>
                </form>
            </div>
        </div>
        <?php endif; ?>

        <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" id="item_group_id_create" class="form-select">
                            <option value="0">-- bez grupe --</option>
                            <?php
                            $groupsRes->data_seek(0);
                            while ($g = $groupsRes->fetch_assoc()): ?>
                                <option value="<?php echo (int)$g['id']; ?>">
                                    <?php echo htmlspecialchars($g['name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <?php if ($hasSubgroups && $itemHasSubgroupCol): ?>
                    <div class="mb-2">
                        <label class="form-label">Podgrupa artikla</label>
                        <select name="item_subgroup_id" id="item_subgroup_id_create" class="form-select">
                            <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>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Jedinica mjere</label>
                        <input type="text" name="unit" class="form-control" placeholder="kom, m, kg..." required>
                    </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_create" name="has_warranty" value="1">
                        <label class="form-check-label" for="has_warranty_create">Artikl ima garanciju</label>
                    </div>
                    <div class="mb-3" id="warranty_months_wrap_create" style="display:none;">
                        <label class="form-label">Garancija (mjeseci)</label>
                        <input type="number" min="0" step="1" name="warranty_months" id="warranty_months_create" class="form-control" placeholder="npr. 24">
                    </div>
                    <?php endif; ?>
                    <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, 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>
                            <?php if ($hasSubgroups && $itemHasSubgroupCol): ?><th>Podgrupa</th><?php endif; ?>
                            <th>JM</th>
                            <th>Garancija</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((string)$i['group_name']); ?></td>
                                <?php if ($hasSubgroups && $itemHasSubgroupCol): ?><td><?php echo htmlspecialchars((string)$i['subgroup_name']); ?></td><?php endif; ?>
                                <td><?php echo htmlspecialchars($i['unit']); ?></td>
                                <td>
                                    <?php if (!empty($i['has_warranty'])): ?>
                                        <span class="badge rounded-pill text-bg-success">
                                            <?php echo (int)$i['warranty_months'] > 0 ? ((int)$i['warranty_months'] . ' mj') : 'Da'; ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-muted small">Ne</span>
                                    <?php endif; ?>
                                </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((string)$i['group_name']); ?>
                                <?php if ($hasSubgroups && $itemHasSubgroupCol && !empty($i['subgroup_name'])): ?> • Podgrupa: <?php echo htmlspecialchars((string)$i['subgroup_name']); ?><?php endif; ?>
                                • JM: <?php echo htmlspecialchars($i['unit']); ?>
                            </div>
                            <div class="small mt-1">
                                Garancija:
                                <?php if (!empty($i['has_warranty'])): ?>
                                    <span class="badge rounded-pill text-bg-success">
                                        <?php echo (int)$i['warranty_months'] > 0 ? ((int)$i['warranty_months'] . ' mj') : 'Da'; ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-muted">Ne</span>
                                <?php endif; ?>
                            </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>

<script>
const itemSubgroupsData = <?php echo $subgroupsJson; ?>;

function filterCreateSubgroups() {
    const groupSel = document.getElementById('item_group_id_create');
    const subgroupSel = document.getElementById('item_subgroup_id_create');
    if (!groupSel || !subgroupSel) return;

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

function toggleWarrantyCreate() {
    const chk = document.getElementById('has_warranty_create');
    const wrap = document.getElementById('warranty_months_wrap_create');
    const inp = document.getElementById('warranty_months_create');
    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_create');
    if (groupSel) {
        groupSel.addEventListener('change', filterCreateSubgroups);
        filterCreateSubgroups();
    }
    const warrantyChk = document.getElementById('has_warranty_create');
    if (warrantyChk) {
        warrantyChk.addEventListener('change', toggleWarrantyCreate);
        toggleWarrantyCreate();
    }
});
</script>

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