# AI Search Algorithm for Homnex

This AI search algorithm provides intelligent search capabilities for the Homnex room rental platform. It learns from user interactions, personalizes results, and improves search relevance over time.

## Features

- **Personalized Search Results**: Tailors search results based on user preferences and past interactions
- **Learning Capability**: Learns from user behavior to improve future searches
- **Trend Analysis**: Identifies and incorporates popular search trends
- **Similar Room Recommendations**: Suggests similar rooms based on various factors
- **Interaction Tracking**: Tracks user interactions to improve recommendations

## How to Use

### Basic Search

To perform a basic AI-enhanced search:

```php
// Include the AI Search Algorithm
require_once 'includes/AISearchAlgorithm.php';

// Get user ID if logged in
$userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

// Prepare search parameters
$searchParams = [
    'location' => 'Accra',
    'room_type' => 'single',
    'price_max' => 1000,
    'amenities' => ['wifi', 'ac'],
    'nearby' => ['school'],
    'sort_by' => 'newest'
];

// Perform AI-enhanced search
$searchResults = aiSearch($searchParams, $db, $userId);
```

### Getting Recommendations

To get personalized room recommendations:

```php
// Get recommended rooms for the current user
$recommendedRooms = getRecommendedRooms($userId, 6, $db);
```

### Finding Similar Rooms

To find rooms similar to a specific room:

```php
// Get similar rooms to a specific room
$similarRooms = getSimilarRooms($roomId, 4, $db);
```

### Tracking User Interactions

Track various user interactions to improve the algorithm:

```php
// Track when a user views a room
trackRoomView($roomId, $userId, $db);

// Track when a user adds a room to wishlist
trackWishlistAction($roomId, $userId, $db);

// Track when a user initiates a booking
trackBookingAction($roomId, $userId, $db);

// Track when a user contacts about a room
trackContactAction($roomId, $userId, $db);

// Track when a user shares a room
trackShareAction($roomId, $userId, $db);
```

## Integration Examples

### In search.php

```php
// Include the AI Search Algorithm
require_once 'includes/AISearchAlgorithm.php';

// Get user ID if logged in
$userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

// Prepare search parameters from GET request
$searchParams = [
    'location' => $_GET['location'] ?? '',
    'room_type' => $_GET['room_type'] ?? '',
    'price_min' => $_GET['price_min'] ?? null,
    'price_max' => $_GET['price_max'] ?? null,
    'amenities' => $_GET['amenities'] ?? [],
    'nearby' => $_GET['nearby'] ?? [],
    'availability' => $_GET['availability'] ?? '',
    'sort_by' => $_GET['sort_by'] ?? 'newest'
];

// Pagination parameters
$roomsPerPage = 12;
$currentPage = isset($_GET['page_num']) ? max(1, intval($_GET['page_num'])) : 1;
$offset = ($currentPage - 1) * $roomsPerPage;

// Perform AI-enhanced search
$allRooms = aiSearch($searchParams, $db, $userId);

// Get total count for pagination
$totalRooms = count($allRooms);

// Apply pagination manually
$rooms = array_slice($allRooms, $offset, $roomsPerPage);
```

### In room_details.php

```php
// Include the AI Search Algorithm
require_once 'includes/AISearchAlgorithm.php';

// Get user ID if logged in
$userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

// Track room view
trackRoomView($roomId, $userId, $db);

// Get similar rooms
$similarRooms = getSimilarRooms($roomId, 4, $db);
```

### In home.php

```php
// Include the AI Search Algorithm
require_once 'includes/AISearchAlgorithm.php';

// Get user ID if logged in
$userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

// Get recommended rooms
$recommendedRooms = getRecommendedRooms($userId, 6, $db);
```

## Database Tables

The algorithm automatically creates the following tables if they don't exist:

1. `search_history` - Tracks all searches performed by users
2. `search_interactions` - Tracks user interactions with search results
3. `user_search_preferences` - Stores learned preferences for each user
4. `room_popularity_metrics` - Tracks room popularity for recommendations
5. `search_trends` - Stores aggregated search trends

## How It Works

1. **Search Tracking**: Every search is logged to learn from user behavior
2. **Interaction Learning**: User interactions (views, wishlists, bookings) are tracked
3. **Preference Building**: User preferences are built based on interactions
4. **Result Personalization**: Search results are personalized based on preferences
5. **Trend Analysis**: Global search trends are analyzed to improve results for all users

## Performance Considerations

- The algorithm uses database caching to minimize performance impact
- Personalization is applied after the base query to maintain search speed
- Trend analysis is performed asynchronously to avoid slowing down searches

For more examples, see `examples/search_example.php`.