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

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

$shop_id = $_SESSION['user']['shop_id'];
$searchTerm = trim($_GET['query'] ?? '');

if ($searchTerm === '') {
    echo '';
    exit;
}

// Search by product name only
$sql = "SELECT p.id, p.name, p.selling_price, p.vat_percent,
        COALESCE(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
        ), 0) AS current_stock
        FROM products p
        LEFT JOIN product_batches pb ON pb.product_id = p.id AND pb.shop_id = ?
        LEFT JOIN inventory_movements im ON pb.id = im.batch_id
        WHERE p.shop_id = ? AND p.name LIKE ?
        GROUP BY p.id, p.name, p.selling_price, p.vat_percent
        HAVING current_stock > 0
        LIMIT 10";

$stmt = $pdo->prepare($sql);
$stmt->execute([$shop_id, $shop_id, "%$searchTerm%"]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($results) {
    foreach ($results as $product) {
        echo '<a href="#" class="list-group-item list-group-item-action add-to-cart" 
                data-id="' . $product['id'] . '"
                data-name="' . htmlspecialchars($product['name']) . '"
                data-price="' . $product['selling_price'] . '"
                data-vat="' . $product['vat_percent'] . '"
                data-stock="' . $product['current_stock'] . '">
                ' . htmlspecialchars($product['name']) . ' 
                (Stock: ' . $product['current_stock'] . ' - TZS ' . number_format($product['selling_price'],2) . ')
              </a>';
    }
} else {
    echo '<div class="list-group-item text-muted">No products found</div>';
}
