<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner_or_admin();
require_once __DIR__ . '/../includes/header_admin.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$products = $pdo->query('SELECT p.id, p.name, p.stock, p.is_active, c.name AS category_name
    FROM products p
    LEFT JOIN categories c ON c.id = p.category_id
    ORDER BY p.stock ASC, p.name ASC')->fetchAll();
?>

<h2 class="fw-bold mb-4">Laporan Stok</h2>

<div class="card shadow-sm">
    <div class="card-body table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>Produk</th>
                    <th>Kategori</th>
                    <th>Stok</th>
                    <th>Status</th>
                    <th>Stok Menipis</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!$products): ?>
                    <tr><td colspan="5">Belum ada data.</td></tr>
                <?php endif; ?>
                <?php foreach ($products as $product): ?>
                    <?php $low = (int) $product['stock'] <= 5; ?>
                    <tr>
                        <td><?= sanitize($product['name']); ?></td>
                        <td><?= sanitize($product['category_name'] ?? '-'); ?></td>
                        <td><?= (int) $product['stock']; ?></td>
                        <td><?= (int) $product['is_active'] === 1 ? 'Aktif' : 'Nonaktif'; ?></td>
                        <td><?= $low ? 'Ya' : 'Tidak'; ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_admin.php'; ?>
