# WebSocket Setup for Mobile API - Room Functionality

This document explains how to set up and use the WebSocket functionality for real-time room joining and leaving in mobile applications.

## Prerequisites

1. **Pusher Account**: You'll need a Pusher account to handle WebSocket connections
2. **Mobile WebSocket Libraries**: Use appropriate libraries for your mobile platform

## Installation

The required backend packages have been installed:

```bash
# Backend packages
composer require pusher/pusher-php-server
```

## Configuration

### 1. Environment Variables

Add the following variables to your `.env` file:

```env
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your_pusher_app_id
PUSHER_APP_KEY=your_pusher_app_key
PUSHER_APP_SECRET=your_pusher_app_secret
PUSHER_APP_CLUSTER=your_pusher_cluster
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_ENCRYPTED=true
```

## Backend Implementation

### Events

The system includes two main events:

1. **UserJoinedRoom**: Fired when a user joins a room
2. **UserLeftRoom**: Fired when a user leaves a room

These events are automatically dispatched in the `UserRoomController`:

```php
// When user joins a room
event(new UserJoinedRoom($joinRoom, $user, $room));

// When user leaves a room
event(new UserLeftRoom($joinRoom, $user, $room));
```

### API Endpoints

The following API endpoints are available for mobile clients:

- `POST /api/v1/user/join-room` - Join a room
- `POST /api/v1/user/leave-room` - Leave a room
- `GET /api/v1/user/get-joined-room-users/{id}` - Get users in a room
- `GET /api/v1/user/websocket-config` - Get WebSocket configuration

## Mobile Implementation

### Channel Naming

Events are broadcast on channels named `room.{room_id}`. For example:
- Room ID: `123456789` → Channel: `room.123456789`

### Event Data Structure

#### UserJoinedRoom Event
```json
{
    "type": "user_joined",
    "join_room": {
        "id": 1,
        "joined_at": "2024-01-01T12:00:00.000000Z",
        "is_host": false
    },
    "user": {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com"
    },
    "room": {
        "id": 1,
        "room_id": "123456789",
        "room_name": "My Room"
    },
    "message": "John Doe joined the room",
    "timestamp": "2024-01-01T12:00:00.000000Z"
}
```

#### UserLeftRoom Event
```json
{
    "type": "user_left",
    "join_room": {
        "id": 1,
        "left_at": "2024-01-01T12:00:00.000000Z",
        "is_host": false
    },
    "user": {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com"
    },
    "room": {
        "id": 1,
        "room_id": "123456789",
        "room_name": "My Room"
    },
    "message": "John Doe left the room",
    "timestamp": "2024-01-01T12:00:00.000000Z"
}
```

## Mobile Platform Libraries

### Flutter/Dart
```yaml
dependencies:
  pusher_client: ^2.0.0
```

### React Native
```bash
npm install pusher-js
```

### iOS (Swift)
```swift
// Add via CocoaPods
pod 'PusherSwift'
```

### Android (Kotlin/Java)
```gradle
implementation 'com.pusher:pusher-java-client:2.2.1'
```

## Testing

### API Testing
Use tools like Postman or curl to test the API endpoints:

```bash
# Get WebSocket config
curl -X GET /api/v1/user/websocket-config \
  -H "Authorization: Bearer YOUR_TOKEN"

# Join room
curl -X POST /api/v1/user/join-room \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"room_id": "123456789"}'
```

### WebSocket Testing
Use Pusher's debug console or a WebSocket testing tool to verify events are being broadcast correctly.

## Security Considerations

1. **Authentication**: All API endpoints require authentication
2. **Channel Authorization**: Consider using private channels for sensitive data
3. **User Validation**: Always validate user permissions before allowing room access
4. **Rate Limiting**: Implement rate limiting on room join/leave endpoints

## Performance

1. **Connection Limits**: Monitor the number of concurrent WebSocket connections
2. **Memory Usage**: Clean up event listeners when users leave rooms
3. **Database Queries**: Optimize database queries for room user lists

## Troubleshooting

### Common Issues

1. **Events not broadcasting**: Check your Pusher credentials and ensure `BROADCAST_DRIVER=pusher`
2. **Mobile not receiving events**: Verify the channel name matches the room ID
3. **Authentication issues**: Ensure the user is authenticated when making API calls

### Debugging

Enable Pusher debugging by adding to your `.env`:

```env
PUSHER_APP_DEBUG=true
```

Check the Laravel logs for any errors.

## Complete Documentation

For detailed mobile implementation examples and complete API documentation, see `MOBILE_API_DOCUMENTATION.md`. 