# Agent Check-In Notification Feature

This document describes the agent check-in notification feature that sends push notifications to admins when agents check in.

## Overview

When an agent checks in, the system:
1. Records the check-in location in the database
2. Sends a push notification to all admins in the same company
3. Returns check-in confirmation with notification status

## API Endpoints

### 1. Check-In Endpoint (Recommended)

**Endpoint:** `POST /check_in`

**Authentication:** Required (Agent token)

**Request Body:**
```json
{
  "latitude": 12.9716,
  "longitude": 77.5946,
  "address": "123 Main Street, City",
  "accuracy": 10.5,
  "altitude": 920.0,
  "remark": "Starting collection route"
}
```

**Required Fields:**
- `latitude` (number) - GPS latitude coordinate
- `longitude` (number) - GPS longitude coordinate

**Optional Fields:**
- `address` (string) - Human-readable address
- `accuracy` (number) - GPS accuracy in meters
- `altitude` (number) - Altitude above sea level
- `altitude_accuracy` (number) - Altitude accuracy
- `heading` (number) - Direction of travel (0-360 degrees)
- `speed` (number) - Speed in m/s
- `remark` (string) - Additional notes

**cURL Example:**
```bash
curl -X POST http://localhost:3000/check_in \
  -H "Authorization: Bearer YOUR_AGENT_AUTH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "latitude": 12.9716,
    "longitude": 77.5946,
    "address": "123 Main Street, Bangalore",
    "remark": "Starting daily collection"
  }'
```

**Response:**
```json
{
  "status": "success",
  "message": "Check-in successful",
  "data": {
    "location_track_id": 123,
    "agent_id": 5,
    "agent_name": "John Doe",
    "company_id": 1,
    "latitude": 12.9716,
    "longitude": 77.5946,
    "address": "123 Main Street, Bangalore",
    "activity_type": "check_in",
    "created_at": "2025-01-15T10:30:00.000Z",
    "notification": {
      "sent": true,
      "message": "Notification sent to admins"
    }
  }
}
```

### 2. Track Location with Check-In Activity Type

**Endpoint:** `POST /track_location`

**Authentication:** Required (Agent token)

**Request Body:**
```json
{
  "latitude": 12.9716,
  "longitude": 77.5946,
  "activity_type": "check_in",
  "address": "123 Main Street, City"
}
```

**Note:** When `activity_type` is set to `"check_in"`, a notification will automatically be sent to admins.

## Notification Details

### Notification Sent to Admins

**Title:** "Agent Check-In"

**Body:** "{Agent Name} has checked in {at Address}" (if address provided)

**Data Payload:**
```json
{
  "agent_id": "5",
  "agent_name": "John Doe",
  "agent_mobile": "1234567890",
  "agent_line": "Line A",
  "company_id": "1",
  "activity_type": "check_in",
  "location_track_id": "123",
  "latitude": "12.9716",
  "longitude": "77.5946",
  "address": "123 Main Street, Bangalore",
  "timestamp": "2025-01-15T10:30:00.000Z"
}
```

### Notification Behavior

- Notifications are sent to **all admins** in the same company as the agent
- Only admins with registered FCM tokens will receive notifications
- If no admins have FCM tokens, the check-in still succeeds but no notification is sent
- Notification failures don't affect the check-in process (check-in is recorded even if notification fails)

## Usage Examples

### Example 1: Simple Check-In

```javascript
// React Native example
const checkIn = async () => {
  try {
    // Get current location
    const location = await getCurrentPosition();
    
    // Send check-in request
    const response = await fetch('http://your-api.com/check_in', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${agentAuthToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        latitude: location.coords.latitude,
        longitude: location.coords.longitude,
        address: location.address || null,
        accuracy: location.coords.accuracy || null
      })
    });

    const result = await response.json();
    
    if (result.status === 'success') {
      console.log('Check-in successful');
      if (result.data.notification.sent) {
        console.log('Admins have been notified');
      } else {
        console.log('Notification not sent:', result.data.notification.message);
      }
    }
  } catch (error) {
    console.error('Check-in failed:', error);
  }
};
```

### Example 2: Check-In with Address Lookup

```javascript
const checkInWithAddress = async () => {
  try {
    // Get current location
    const location = await getCurrentPosition();
    
    // Reverse geocode to get address
    const address = await reverseGeocode(
      location.coords.latitude,
      location.coords.longitude
    );
    
    // Send check-in
    const response = await fetch('http://your-api.com/check_in', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${agentAuthToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        latitude: location.coords.latitude,
        longitude: location.coords.longitude,
        address: address,
        accuracy: location.coords.accuracy,
        remark: 'Morning check-in - Starting collection route'
      })
    });

    const result = await response.json();
    return result;
  } catch (error) {
    console.error('Check-in failed:', error);
    throw error;
  }
};
```

### Example 3: Using track_location for Check-In

```javascript
// Using track_location endpoint with activity_type
const checkInViaTrackLocation = async () => {
  const location = await getCurrentPosition();
  
  const response = await fetch('http://your-api.com/track_location', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${agentAuthToken}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
      activity_type: 'check_in',  // This triggers notification
      address: location.address
    })
  });

  const result = await response.json();
  // Check result.data.notification_sent to see if notification was sent
  return result;
};
```

## Admin Mobile App Integration

Admins will receive a push notification when agents check in. Handle it in your mobile app:

```javascript
// React Native - Handle check-in notifications
import messaging from '@react-native-firebase/messaging';

messaging().onMessage(async remoteMessage => {
  if (remoteMessage.data && remoteMessage.data.activity_type === 'check_in') {
    const { agent_name, address, latitude, longitude } = remoteMessage.data;
    
    // Show notification
    Alert.alert(
      'Agent Check-In',
      `${agent_name} has checked in${address ? ' at ' + address : ''}`,
      [
        { text: 'View on Map', onPress: () => openMap(latitude, longitude) },
        { text: 'OK' }
      ]
    );
    
    // Optionally refresh agent locations list
    refreshAgentLocations();
  }
});
```

## Database Storage

Check-ins are stored in the `agent_location_tracking` table with:
- `activity_type` = `'check_in'`
- Location coordinates (latitude, longitude)
- Address (if provided)
- Timestamp
- Agent ID and Company ID

## Error Handling

### Common Errors

1. **401 Unauthorized**
   - Agent authentication token is missing or invalid
   - Solution: Re-authenticate the agent

2. **400 Bad Request**
   - Missing required fields (latitude, longitude)
   - Solution: Ensure location data is provided

3. **404 Not Found**
   - Agent not found
   - Solution: Verify agent exists in database

4. **Notification Failures**
   - Notification failures don't affect check-in success
   - Check `notification.sent` field in response
   - Common reasons:
     - No admins have registered FCM tokens
     - Firebase service account not configured
     - Invalid FCM tokens

## Best Practices

1. **Always Include Address**: Provides better context for admins
2. **Handle Notification Status**: Check if notification was sent and log if needed
3. **Retry on Failure**: Implement retry logic for network failures
4. **Location Accuracy**: Use accurate GPS coordinates for better tracking
5. **Regular Check-Ins**: Agents should check in at the start of their shift

## Related Endpoints

- `POST /track_location` - General location tracking (supports check_in activity_type)
- `GET /location_history` - Get agent's location history
- `GET /admin/real-time-agent-locations` - Admins can view all agent locations

## Notes

- Check-ins are immutable once recorded (cannot be deleted or modified)
- Multiple check-ins per day are allowed
- Admins receive notifications in real-time when agents check in
- Location tracking history can be viewed by admins via admin endpoints

