<?php
// modules/sales/ajax/get_products.php
session_start();
require_once '../../assets/db_connect.php';

if (!isset($_SESSION['user'])) {
    echo '<div class="col-12 text-center text-danger">Unauthorized</div>';
    exit();
}

$shop_id = $_GET['shop_id'] ?? $_SESSION['user']['shop_id'];

// Get products with stock
$sql = "SELECT 
            p.id,
            p.sku,
            p.name,
            p.generic_name,
            p.category,
            p.unit,
            p.selling_price,
            COALESCE(SUM(pb.qty), 0) as current_stock
        FROM products p
        LEFT JOIN product_batches pb ON p.id = pb.product_id
        WHERE p.shop_id = ? AND p.is_active = 1
        GROUP BY p.id, p.sku, p.name, p.generic_name, p.category, p.unit, p.selling_price
        HAVING current_stock > 0
        ORDER BY p.name";

$stmt = $pdo->prepare($sql);
$stmt->execute([$shop_id]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($products)) {
    echo '<div class="col-12 text-center py-4">
            <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
            <h5>No products available</h5>
            <p class="text-muted">Add products with stock to start selling</p>
          </div>';
    exit();
}

foreach ($products as $product):
    $stock_class = $product['current_stock'] <= 10 ? 'badge-warning' : 'badge-success';
?>
<div class="col-md-3 col-sm-4 col-6 mb-3">
    <div class="product-card" 
         onclick="addProductToCart(<?= $product['id'] ?>)"
         data-category="<?= htmlspecialchars($product['category']) ?>">
        <div class="product-name fw-bold mb-1"><?= htmlspecialchars($product['name']) ?></div>
        <div class="product-details small text-muted mb-2">
            <?php if ($product['generic_name']): ?>
                <div><?= htmlspecialchars($product['generic_name']) ?></div>
            <?php endif; ?>
            <div><?= htmlspecialchars($product['category']) ?></div>
            <div>SKU: <?= htmlspecialchars($product['sku']) ?></div>
        </div>
        <div class="d-flex justify-content-between align-items-center">
            <span class="text-success fw-bold">TZS <?= number_format($product['selling_price'], 2) ?></span>
            <span class="badge <?= $stock_class ?>"><?= $product['current_stock'] ?> <?= $product['unit'] ?></span>
        </div>
    </div>
</div>
<?php endforeach; ?>