<?php
require 'db.php';

// Get parameters
$location = $_GET['location'] ?? '';
$type = $_GET['type'] ?? '';
$bedrooms = $_GET['bedrooms'] ?? '';
$price_range = $_GET['price_range'] ?? '';

// Log search
$log_stmt = $conn->prepare("INSERT INTO search_logs (location, type, price_range) VALUES (?, ?, ?)");
$log_stmt->bind_param("sss", $location, $type, $price_range);
$log_stmt->execute();
$log_stmt->close();

// Build SQL
$sql = "SELECT * FROM properties WHERE 1=1";
$params = [];
$types = "";

// Location filter
if (!empty($location)) {
    $sql .= " AND location LIKE ?";
    $params[] = "%$location%";
    $types .= "s";
}

// Type filter
if (!empty($type)) {
    $sql .= " AND type = ?";
    $params[] = $type;
    $types .= "s";
}

// Bedrooms filter
if (!empty($bedrooms)) {
    $sql .= " AND bedrooms = ?";
    $params[] = $bedrooms;
    $types .= "i";
}

// Price range filter
if (!empty($price_range)) {
    $range = explode("-", $price_range);
    if (count($range) == 2) {
        $sql .= " AND price BETWEEN ? AND ?";
        $params[] = (int)$range[0];
        $params[] = (int)$range[1];
        $types .= "ii";
    }
}

// Prepare query
$stmt = $conn->prepare($sql);

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();
?>
