<?php
/**
 * ============================================================================
 * ajax/search.php
 * Global search functionality
 * ============================================================================
 */
?>

<?php
define('AIMS_ACCESS', true);
require_once '../config/config.php';

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

if (!isLoggedIn()) {
    jsonError('Unauthorized', 401);
}

$searchTerm = sanitize($_GET['q'] ?? '');

if (empty($searchTerm)) {
    jsonSuccess('Search results', ['results' => []]);
}

$database = new Database();
$db = $database->getConnection();
$userId = getUserId();

$results = [];

// Search products
$sql = "SELECT 'product' as type, id, product_name as title, category, price_per_unit as price 
        FROM products 
        WHERE (product_name LIKE ? OR description LIKE ?) 
        AND status = 'available' 
        LIMIT 5";
$stmt = $db->prepare($sql);
$searchPattern = "%{$searchTerm}%";
$stmt->execute([$searchPattern, $searchPattern]);
$results['products'] = $stmt->fetchAll();

// Search users/farmers
$sql = "SELECT 'user' as type, id, full_name as title, village, district 
        FROM users 
        WHERE (full_name LIKE ? OR phone_number LIKE ?) 
        AND id != ? 
        LIMIT 5";
$stmt = $db->prepare($sql);
$stmt->execute([$searchPattern, $searchPattern, $userId]);
$results['users'] = $stmt->fetchAll();

jsonSuccess('Search results', ['results' => $results]);
?>

