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

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

$group_id      = (int)($_GET['group_id'] ?? 0);
$only_nonzero  = isset($_GET['only_nonzero']) && $_GET['only_nonzero'] === '1';
$search        = trim($_GET['q'] ?? '');

$where = [];
if ($group_id > 0) {
    $where[] = 'i.item_group_id = ' . $group_id;
}
if ($search !== '') {
    $esc = $mysqli->real_escape_string($search);
    $where[] = "(i.name LIKE '%{$esc}%' OR i.code LIKE '%{$esc}%')";
}
$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
SELECT
    i.id,
    i.code,
    i.name,
    i.unit,
    g.name AS group_name,
    COALESCE(rin.total_in, 0)  AS qty_in,
    COALESCE(rout.total_out, 0) AS qty_out,
    COALESCE(rin.total_in, 0) - COALESCE(rout.total_out, 0) AS qty_stock
FROM items i
LEFT JOIN item_groups g ON g.id = i.item_group_id
LEFT JOIN (
    SELECT ri.item_id, SUM(ri.quantity) AS total_in
    FROM receipt_items ri
    JOIN receipts r ON r.id = ri.receipt_id
    GROUP BY ri.item_id
) AS rin ON rin.item_id = i.id
LEFT JOIN (
    SELECT ci.item_id, SUM(ci.quantity) AS total_out
    FROM consumption_items ci
    JOIN consumption_orders o ON o.id = ci.order_id
    GROUP BY ci.item_id
) AS rout ON rout.item_id = i.id
{$where_sql}
";

if ($only_nonzero) {
    $sql .= " HAVING qty_stock <> 0";
}

$sql .= " ORDER BY i.name";

$result = $mysqli->query($sql);

$query_params = [
    'group_id'     => $group_id,
    'only_nonzero' => $only_nonzero ? '1' : '0',
    'q'            => $search
];
$export_query = http_build_query($query_params);
?>
<div class="row g-3 mb-3 align-items-center">
    <div class="col">
        <div class="section-title">Stanje skladišta</div>
        <div class="text-muted small">Ulaz (primke) – izlaz (nalozi) = stanje po artiklu</div>
    </div>
    <div class="col-auto d-flex flex-wrap gap-2">
        <a href="stock_pdf.php?<?php echo $export_query; ?>"
           class="btn btn-outline-secondary btn-soft btn-sm" target="_blank">
            PDF
        </a>
        <a href="stock_excel.php?<?php echo $export_query; ?>"
           class="btn btn-outline-success btn-soft btn-sm">
            Excel
        </a>
    </div>
</div>

<div class="card card-soft mb-3">
    <div class="card-header card-soft-header">
        <span class="fw-semibold">Filter</span>
    </div>
    <div class="card-body card-soft-body">
        <form method="get" class="row g-3">
            <div class="col-md-3 col-12">
                <label class="form-label">Grupa artikla</label>
                <select name="group_id" class="form-select form-select-sm">
                    <option value="0">-- sve grupe --</option>
                    <?php
                    $groupsRes->data_seek(0);
                    while ($g = $groupsRes->fetch_assoc()):
                        $sel = ($group_id == (int)$g['id']) ? 'selected' : '';
                    ?>
                        <option value="<?php echo $g['id']; ?>" <?php echo $sel; ?>>
                            <?php echo htmlspecialchars($g['name']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="col-md-4 col-12">
                <label class="form-label">Pretraga (naziv/šifra)</label>
                <input type="text" name="q" class="form-control form-control-sm"
                       value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="col-md-3 col-12 d-flex align-items-center">
                <div class="form-check mt-3">
                    <input class="form-check-input" type="checkbox" value="1"
                           id="only_nonzero" name="only_nonzero"
                           <?php echo $only_nonzero ? 'checked' : ''; ?>>
                    <label class="form-check-label small" for="only_nonzero">
                        Samo artikli s nenultim stanjem
                    </label>
                </div>
            </div>
            <div class="col-md-2 col-12 d-flex align-items-end">
                <button class="btn btn-outline-primary btn-soft w-100 btn-sm" type="submit">Primijeni</button>
            </div>
        </form>
    </div>
</div>

<div class="card card-soft">
    <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
        <span class="fw-semibold">Stanje po artiklima</span>
        <span class="pill-counter d-none d-sm-inline">
            <?php echo (int)$result->num_rows; ?> artikala
        </span>
    </div>
    <div class="card-body card-soft-body">

        <div class="d-md-none">
            <?php
            if ($result->num_rows === 0): ?>
                <div class="text-muted small">Nema artikala.</div>
            <?php endif;
            $result->data_seek(0);
            while ($row = $result->fetch_assoc()):
                $in    = (float)$row['qty_in'];
                $out   = (float)$row['qty_out'];
                $stock = (float)$row['qty_stock'];
            ?>
                <div class="list-card">
                    <div class="d-flex justify-content-between align-items-start mb-1">
                        <div>
                            <div class="list-card-title">
                                <a href="item_detail.php?id=<?php echo $row['id']; ?>">
                                    <?php echo htmlspecialchars($row['name']); ?>
                                </a>
                            </div>
                            <div class="list-card-sub">
                                Šifra:
                                <a href="item_detail.php?id=<?php echo $row['id']; ?>">
                                    <strong><?php echo htmlspecialchars($row['code']); ?></strong>
                                </a>
                            </div>
                            <?php if (!empty($row['group_name'])): ?>
                                <div class="mt-1">
                                    <span class="chip">
                                        <span class="chip-dot"></span>
                                        <?php echo htmlspecialchars($row['group_name']); ?>
                                    </span>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="text-end">
                            <div class="small text-muted">Stanje</div>
                            <div class="fw-semibold">
                                <?php echo number_format($stock, 3, ',', '.'); ?>
                                <?php echo htmlspecialchars($row['unit']); ?>
                            </div>
                        </div>
                    </div>
                    <div class="list-card-meta">
                        Ulaz: <?php echo number_format($in, 3, ',', '.'); ?> |
                        Izlaz: <?php echo number_format($out, 3, ',', '.'); ?>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>

        <div class="d-none d-md-block">
            <div class="table-responsive">
                <table class="table table-sm align-middle">
                    <thead class="small text-muted">
                    <tr>
                        <th>Šifra</th>
                        <th>Naziv</th>
                        <th>Grupa</th>
                        <th class="text-end">Ulaz</th>
                        <th class="text-end">Izlaz</th>
                        <th class="text-end">Stanje</th>
                        <th>JM</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    $result->data_seek(0);
                    while ($row = $result->fetch_assoc()):
                        $in    = (float)$row['qty_in'];
                        $out   = (float)$row['qty_out'];
                        $stock = (float)$row['qty_stock'];
                    ?>
                        <tr>
                            <td class="fw-semibold">
                                <a href="item_detail.php?id=<?php echo $row['id']; ?>">
                                    <?php echo htmlspecialchars($row['code']); ?>
                                </a>
                            </td>
                            <td>
                                <a href="item_detail.php?id=<?php echo $row['id']; ?>">
                                    <?php echo htmlspecialchars($row['name']); ?>
                                </a>
                            </td>
                            <td><?php echo htmlspecialchars($row['group_name']); ?></td>
                            <td class="text-end">
                                <?php echo number_format($in, 3, ',', '.'); ?>
                            </td>
                            <td class="text-end">
                                <?php echo number_format($out, 3, ',', '.'); ?>
                            </td>
                            <td class="text-end">
                                <?php echo number_format($stock, 3, ',', '.'); ?>
                            </td>
                            <td><?php echo htmlspecialchars($row['unit']); ?></td>
                        </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

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