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

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

$query = isset($_POST['query']) ? trim($_POST['query']) : '';
$shop_id = isset($_POST['shop_id']) ? (int)$_POST['shop_id'] : 0;

if (strlen($query) < 2) {
    echo '<div class="list-group-item text-muted p-2">Type at least 2 characters to search</div>';
    exit;
}

try {
    // Debug logging
    error_log("Search query: " . $query . ", Shop ID: " . $shop_id);
    
    // Search products by name, SKU, or generic name
    $sql = "
        SELECT 
            p.id,
            p.sku,
            p.name,
            p.generic_name,
            p.selling_price,
            p.category,
            COALESCE((
                SELECT 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
                )
                FROM product_batches pb
                LEFT JOIN inventory_movements im ON pb.id = im.batch_id
                WHERE pb.product_id = p.id 
                AND pb.shop_id = :shop_id 
                AND pb.is_active = 1
            ), 0) as total_stock
        FROM products p
        WHERE (p.sku LIKE :query OR p.name LIKE :query OR p.generic_name LIKE :query)
        AND (p.shop_id = :shop_id OR p.shop_id IS NULL)
        AND p.is_active = 1
        ORDER BY p.name
        LIMIT 15
    ";
    
    $stmt = $pdo->prepare($sql);
    $searchTerm = "%" . $query . "%";
    $stmt->bindParam(':query', $searchTerm, PDO::PARAM_STR);
    $stmt->bindParam(':shop_id', $shop_id, PDO::PARAM_INT);
    $stmt->execute();
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    error_log("Found " . count($products) . " products");
    
    if (empty($products)) {
        echo '<div class="list-group-item text-muted p-2">No products found for "' . htmlspecialchars($query) . '"</div>';
        exit;
    }
    
    foreach ($products as $product) {
        $stock_qty = (int)$product['total_stock'];
        $stock_color = $stock_qty > 0 ? 'text-success' : 'text-danger';
        $stock_icon = $stock_qty > 0 ? 'fa-check-circle' : 'fa-times-circle';
        $stock_text = $stock_qty > 0 ? "In stock: {$stock_qty}" : "Out of stock";
        $price = number_format(floatval($product['selling_price']), 2);
        
        echo '
        <a href="javascript:void(0)" class="list-group-item list-group-item-action product-item p-2" 
           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 style="flex: 1;">
                    <h6 class="mb-1 font-weight-bold text-primary">' . htmlspecialchars($product['name']) . '</h6>
                    <div class="text-muted small mb-1">
                        <i class="fas fa-barcode mr-1"></i>SKU: ' . htmlspecialchars($product['sku']) . ' | 
                        <i class="fas fa-pills mr-1"></i>' . htmlspecialchars($product['generic_name'] ?: 'N/A') . '
                    </div>
                    <div class="small">
                        <span class="badge badge-light">' . htmlspecialchars($product['category'] ?: 'Uncategorized') . '</span>
                    </div>
                </div>
                <div class="text-right ml-3">
                    <div class="font-weight-bold text-success">TSh ' . $price . '</div>
                    <div class="small ' . $stock_color . '">
                        <i class="fas ' . $stock_icon . ' mr-1"></i>' . $stock_text . '
                    </div>
                </div>
            </div>
        </a>
        ';
    }
    
} catch (PDOException $e) {
    error_log("Search error: " . $e->getMessage());
    echo '<div class="list-group-item text-danger p-2">Error searching products. Please try again.</div>';
} catch (Exception $e) {
    error_log("General error: " . $e->getMessage());
    echo '<div class="list-group-item text-danger p-2">Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
}
?>