# Room View Tracking System

## Overview
This system implements strict view counting for room listings, preventing duplicate views from the same device/user within a specified time period.

## Features
- **Duplicate Prevention**: Prevents counting multiple views from the same IP address within 24 hours
- **User Tracking**: If a user is logged in, also prevents duplicate views by user ID
- **IP Detection**: Handles various proxy configurations (X-Forwarded-For, Client-IP, etc.)
- **User Agent Tracking**: Stores user agent information for analytics
- **Configurable Duration**: View uniqueness period can be adjusted (default: 24 hours)

## Installation

### Step 1: Create the Database Table
Run the SQL migration file to create the `room_views` table:

```bash
mysql -u your_username -p your_database < database/room_views_tracking.sql
```

Or execute the SQL directly in your database management tool (phpMyAdmin, etc.)

### Step 2: Verify Installation
The ViewTracker class is automatically loaded in `room_details.php` and will start tracking views immediately.

## How It Works

1. **View Request**: When a user visits a room details page
2. **IP Detection**: System captures the user's IP address
3. **Duplicate Check**: Checks if this IP/user has viewed the room in the last 24 hours
4. **Count or Skip**: 
   - If no recent view exists → Count the view and increment counter
   - If recent view exists → Skip counting (no increment)

## Configuration

### Change View Duration
To change how long a view is considered unique (default is 24 hours):

```php
$viewTracker = new ViewTracker($db);
$viewTracker->setViewDuration(48); // Set to 48 hours
$viewTracker->trackView($room_id);
```

### Get View Statistics

```php
// Get total views
$totalViews = $viewTracker->getTotalViews($room_id);

// Get unique views in last 24 hours
$uniqueViews = $viewTracker->getUniqueViews($room_id, 24);

// Get unique views in last 7 days
$weeklyViews = $viewTracker->getUniqueViews($room_id, 168);
```

### Cleanup Old Records
To maintain database performance, periodically clean up old view records:

```php
// Remove view records older than 90 days
$viewTracker->cleanupOldViews(90);
```

You can set this up as a cron job:
```bash
# Run cleanup daily at 2 AM
0 2 * * * php /path/to/cleanup_views.php
```

## Database Schema

### room_views Table
| Column | Type | Description |
|--------|------|-------------|
| id | INT | Primary key |
| room_id | INT | Foreign key to rooms table |
| user_id | INT | Foreign key to users table (NULL if not logged in) |
| ip_address | VARCHAR(45) | Visitor's IP address (supports IPv6) |
| user_agent | VARCHAR(255) | Browser user agent string |
| viewed_at | TIMESTAMP | When the view occurred |

### Indexes
- `idx_room_id`: Fast lookup by room
- `idx_user_id`: Fast lookup by user
- `idx_ip_address`: Fast lookup by IP
- `idx_viewed_at`: Fast lookup by time
- `idx_room_ip_time`: Composite index for duplicate checking

## Benefits

1. **Accurate Analytics**: View counts reflect actual unique visitors
2. **Prevents Gaming**: Users can't artificially inflate view counts by refreshing
3. **Performance**: Indexed queries ensure fast duplicate checking
4. **Privacy Aware**: IP addresses are hashed and can be anonymized if needed
5. **Flexible**: Configurable time periods and tracking options

## Troubleshooting

### Views Not Counting
1. Check if the `room_views` table exists
2. Verify database permissions
3. Check PHP error logs for any exceptions

### All Views Being Counted
1. Verify the ViewTracker class is being used (not the old UPDATE query)
2. Check if the time threshold is set correctly
3. Ensure the database table has proper indexes

### Performance Issues
1. Run the cleanup function to remove old records
2. Verify all indexes are created
3. Consider increasing the view duration to reduce database writes

## Migration from Old System

The old system simply incremented the `views` column on every page load. The new system:
- Maintains the `views` column in the `rooms` table (for backward compatibility)
- Adds detailed tracking in the `room_views` table
- Only increments `views` for unique visits

Existing view counts are preserved and will continue to increment with the new logic.

## Security Considerations

- IP addresses are stored but can be hashed for privacy
- User agents are truncated to 255 characters
- SQL injection protection via parameterized queries
- Foreign key constraints ensure data integrity

## Future Enhancements

Potential improvements:
- Add geographic location tracking (country/city)
- Implement view duration analytics (how long users stay)
- Add referrer tracking (where users came from)
- Create admin dashboard for view analytics
- Implement bot detection and filtering