<?php
if (!defined('APP_STARTED')) {
    die('No direct access');
}

function handleSearch(PDO $dbh, array $data): string {

    $sql = "SELECT id, titre FROM annonces WHERE 1=1";
    $params = [];

    if (!empty($data['category'])) {
        $sql .= " AND categorie LIKE ?";
        $params[] = "%{$data['category']}%";
    }
    if (!empty($data['city'])) {
        $sql .= " AND ville LIKE ?";
        $params[] = "%{$data['city']}%";
    }
    if (!empty($data['max_price'])) {
        $sql .= " AND prix <= ?";
        $params[] = $data['max_price'];
    }
    if (!empty($data['keywords'])) {
        $sql .= " AND titre LIKE ?";
        $params[] = "%{$data['keywords']}%";
    }

    $stmt = $dbh->prepare($sql." LIMIT 5");
    $stmt->execute($params);

    $out = "";
    foreach ($stmt as $row) {
        $out .= "📌 <b>{$row['titre']}</b><br>
        <a href='annonce.php?id={$row['id']}' target='_blank'>Voir l’annonce</a><br><br>";
    }

    return $out ?: "😕 Aucune annonce trouvée.";
}
