<?php
require_once __DIR__ . '/config.php';
requireAdmin();
$pdo = getDB();
$stmt = $pdo->query("SELECT p.id, p.name, p.slug, p.image, p.is_active, c.name AS cat_name FROM products p LEFT JOIN product_categories c ON p.category_id = c.id ORDER BY p.sort_order, p.id");
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
$pageTitle = 'Products';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>Products <a href="product-edit.php" class="btn">Add Product</a></h1>
    <table class="admin-table">
        <thead>
            <tr><th>ID</th><th>Image</th><th>Name</th><th>Category</th><th>Status</th><th>Actions</th></tr>
        </thead>
        <tbody>
            <?php foreach ($products as $p): ?>
            <tr>
                <td><?php echo (int)$p['id']; ?></td>
                <td>
                    <?php if (!empty($p['image'])): ?>
                    <img src="<?php echo ADMIN_SITE_ROOT . '/' . UPLOAD_URL . 'products/' . htmlspecialchars($p['image']); ?>" alt="" style="max-width:60px;height:auto;">
                    <?php else: ?>—<?php endif; ?>
                </td>
                <td><?php echo htmlspecialchars($p['name']); ?></td>
                <td><?php echo htmlspecialchars($p['cat_name'] ?? '—'); ?></td>
                <td><?php echo $p['is_active'] ? 'Active' : 'Inactive'; ?></td>
                <td>
                    <a href="product-edit.php?id=<?php echo (int)$p['id']; ?>">Edit</a>
                    <a href="product-delete.php?id=<?php echo (int)$p['id']; ?>" onclick="return confirm('Delete this product?');">Delete</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php if (empty($products)): ?>
    <p>No products. <a href="product-edit.php">Add one</a>.</p>
    <?php endif; ?>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
