<?php
session_start();
require '../assets/db_connect.php';

if (!isset($_POST['query']) || !isset($_POST['shop_id'])) {
    exit;
}

$query = '%' . $_POST['query'] . '%';
$shop_id = (int)$_POST['shop_id'];

$stmt = $pdo->prepare("
    SELECT p.id, p.name, p.sku, 
           SUM(
               CASE 
                   WHEN im.movement_type IN ('PURCHASE', 'RETURN') THEN im.change_qty
                   WHEN im.movement_type IN ('SALE', 'ADJUSTMENT') THEN -im.change_qty
                   ELSE 0
               END
           ) as total_stock
    FROM products p
    LEFT JOIN product_batches pb ON p.id = pb.product_id
    LEFT JOIN inventory_movements im ON pb.id = im.batch_id
    WHERE p.shop_id = ? 
      AND p.is_active = 1
      AND (p.name LIKE ? OR p.sku LIKE ?)
    GROUP BY p.id, p.name, p.sku
    HAVING total_stock > 0
    ORDER BY p.name
    LIMIT 10
");

$stmt->execute([$shop_id, $query, $query]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($products)) {
    echo '<div class="list-group-item text-muted">No products found</div>';
} else {
    foreach ($products as $product) {
        $stock = $product['total_stock'] ?? 0;
        echo '<a href="#" class="list-group-item list-group-item-action product-item" 
                data-id="' . $product['id'] . '" 
                data-name="' . htmlspecialchars($product['name']) . '" 
                data-sku="' . htmlspecialchars($product['sku']) . '">
                <strong>' . htmlspecialchars($product['name']) . '</strong>
                <small class="text-muted d-block">SKU: ' . htmlspecialchars($product['sku']) . ' | Stock: ' . $stock . '</small>
              </a>';
    }
}
?>