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

header('Content-Type: text/html; charset=utf-8');

if (!isset($_POST['query']) || !isset($_SESSION['user']['shop_id'])) {
    echo '<div class="list-group-item text-danger p-2">Invalid request</div>';
    exit;
}

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

try {
    $stmt = $pdo->prepare("
        SELECT p.id, p.sku, p.name, p.generic_name, 
               COALESCE(SUM(bs.current_qty), 0) as available_qty
        FROM products p
        LEFT JOIN batch_stock_view bs ON p.id = bs.product_id AND bs.shop_id = ?
        WHERE p.shop_id = ? 
          AND (p.name LIKE ? OR p.sku LIKE ? OR p.generic_name LIKE ?)
          AND p.is_active = 1
        GROUP BY p.id, p.sku, p.name, p.generic_name
        ORDER BY p.name
        LIMIT 20
    ");
    
    $stmt->execute([$shop_id, $shop_id, $query, $query, $query]);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (count($products) === 0) {
        echo '<div class="list-group-item text-muted p-3 text-center">
                <i class="fas fa-search mr-2"></i>No products found
              </div>';
        exit;
    }
    
    foreach ($products as $product) {
        $available = (int)$product['available_qty'];
        $stock_class = $available > 0 ? 'text-success' : 'text-danger';
        $stock_icon = $available > 0 ? 'fa-check-circle' : 'fa-exclamation-circle';
        
        echo '<a href="#" class="list-group-item list-group-item-action product-item p-3" 
                 data-id="' . $product['id'] . '"
                 data-name="' . htmlspecialchars($product['name']) . '"
                 data-sku="' . htmlspecialchars($product['sku']) . '"
                 data-generic="' . htmlspecialchars($product['generic_name']) . '">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-1">' . htmlspecialchars($product['name']) . '</h6>
                        <small class="text-muted">
                            <strong>SKU:</strong> ' . htmlspecialchars($product['sku']) . '
                            ' . ($product['generic_name'] ? ' | <strong>Generic:</strong> ' . htmlspecialchars($product['generic_name']) : '') . '
                        </small>
                    </div>
                    <div class="text-right">
                        <span class="badge ' . $stock_class . '">
                            <i class="fas ' . $stock_icon . ' mr-1"></i>
                            ' . $available . ' in stock
                        </span>
                    </div>
                </div>
              </a>';
    }
    
} catch (PDOException $e) {
    echo '<div class="list-group-item text-danger p-2">Database error</div>';
}
?>