<?php
/**
 * ============================================================================
 * api/search-products.php - Live Product Search API
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

// Check if user is logged in
if (!isLoggedIn()) {
    jsonError('Unauthorized', 401);
}

$query = $_GET['q'] ?? '';
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;

if (strlen($query) < 2) {
    jsonSuccess('Search query too short', ['products' => []]);
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $sql = "SELECT 
                p.id,
                p.product_name,
                p.category,
                p.price_per_unit,
                p.unit,
                p.quantity,
                p.images,
                p.location,
                u.full_name as seller_name
            FROM products p
            LEFT JOIN users u ON p.seller_id = u.id
            WHERE p.status = 'available'
            AND (
                p.product_name LIKE ? OR
                p.description LIKE ? OR
                p.category LIKE ? OR
                p.location LIKE ?
            )
            ORDER BY 
                CASE 
                    WHEN p.product_name LIKE ? THEN 1
                    WHEN p.description LIKE ? THEN 2
                    ELSE 3
                END,
                p.created_at DESC
            LIMIT ?";
    
    $searchTerm = '%' . $query . '%';
    $exactMatch = $query . '%';
    
    $stmt = $db->prepare($sql);
    $stmt->execute([
        $searchTerm,
        $searchTerm,
        $searchTerm,
        $searchTerm,
        $exactMatch,
        $exactMatch,
        $limit
    ]);
    
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process images
    foreach ($products as &$product) {
        $product['images'] = json_decode($product['images'], true) ?? [];
    }
    
    jsonSuccess('Products found', ['products' => $products]);
    
} catch (Exception $e) {
    logError('Search API error: ' . $e->getMessage());
    jsonError('Search failed', 500);
}
?>