<?php
require_once __DIR__ . '/../functions.php';
requireAdmin();
$page_title = 'Products';
$db = db();

$products = $db->query("
    SELECT p.*, c.name as category_name,
           (SELECT image_path FROM product_images WHERE product_id = p.id AND is_primary = 1 LIMIT 1) as image
    FROM products p LEFT JOIN categories c ON p.category_id = c.id
    ORDER BY p.created_at DESC
")->fetchAll();

require_once __DIR__ . '/../includes/admin-header.php';
?>
<div class="flex items-center justify-between mb-6"><h2 class="text-lg font-semibold text-gray-800">All Products</h2><a href="product-form.php" class="bg-primary-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-primary-700"><i class="fas fa-plus mr-1"></i> Add Product</a></div>
<div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
    <table class="w-full text-sm">
        <thead><tr class="text-left bg-gray-50 text-gray-500"><th class="px-4 py-3 font-medium">Product</th><th class="px-4 py-3 font-medium">Category</th><th class="px-4 py-3 font-medium">Price</th><th class="px-4 py-3 font-medium">Stock</th><th class="px-4 py-3 font-medium">Status</th><th class="px-4 py-3 font-medium"></th></tr></thead>
        <tbody>
            <?php foreach ($products as $p): ?>
            <tr class="border-t">
                <td class="px-4 py-3"><div class="flex items-center gap-3"><div class="w-10 h-10 bg-gray-50 rounded overflow-hidden shrink-0 flex items-center justify-center"><?php if ($p['image']): ?><img src="<?= BASE_PATH ?>/<?= h($p['image']) ?>" alt="" class="w-full h-full object-cover"><?php else: ?><i class="fas fa-box text-gray-300"></i><?php endif; ?></div><div><p class="font-medium text-gray-800"><?= h($p['name']) ?></p><p class="text-xs text-gray-400">SKU: <?= h($p['sku'] ?: '-') ?></p></div></div></td>
                <td class="px-4 py-3 text-gray-500"><?= h($p['category_name'] ?: '-') ?></td>
                <td class="px-4 py-3 font-medium"><?= formatPrice($p['price']) ?></td>
                <td class="px-4 py-3"><?php if ($p['stock_quantity'] <= $p['low_stock_threshold']): ?><span class="text-red-600 font-medium"><?= $p['stock_quantity'] ?></span><?php else: ?><?= $p['stock_quantity'] ?><?php endif; ?></td>
                <td class="px-4 py-3"><?= $p['is_active'] ? '<span class="text-green-600 text-xs font-medium">Active</span>' : '<span class="text-gray-400 text-xs font-medium">Inactive</span>' ?></td>
                <td class="px-4 py-3"><a href="product-form.php?id=<?= $p['id'] ?>" class="text-primary-600 hover:underline text-sm">Edit</a></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
