<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';
requireLogin();

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

$q = sanitize($conn, $_GET['q'] ?? '');
if (strlen($q) < 2) { echo '[]'; exit; }

$results = [];

$lost = $conn->query("SELECT item_name, category, location, image_path FROM lost_items WHERE item_name LIKE '%$q%' OR location LIKE '%$q%' ORDER BY created_at DESC LIMIT 6");
while ($r = $lost->fetch_assoc())
    $results[] = ['type'=>'lost','name'=>$r['item_name'],'category'=>$r['category'],'location'=>$r['location'],'image'=>$r['image_path']];

$found = $conn->query("SELECT item_name, category, location, image_path FROM found_items WHERE item_name LIKE '%$q%' OR location LIKE '%$q%' ORDER BY created_at DESC LIMIT 6");
while ($r = $found->fetch_assoc())
    $results[] = ['type'=>'found','name'=>$r['item_name'],'category'=>$r['category'],'location'=>$r['location'],'image'=>$r['image_path']];

echo json_encode(array_slice($results, 0, 10));
