# Admin Agent Location Tracking API

This document provides API endpoints for admins to view agent location logs and track agent movements on a map.

## Base URL
```
http://localhost:3000
```

## Authentication
All endpoints require admin authentication:
```
Authorization: Bearer <admin_auth_token>
```

---

## 1. Get Agent Location Logs (with filters)

### Endpoint
```
GET /admin/agent-location-logs
```

### Query Parameters
- `agent_id` (optional) - Filter by specific agent ID
- `start_date` (optional) - Start date filter (YYYY-MM-DD)
- `end_date` (optional) - End date filter (YYYY-MM-DD)
- `activity_type` (optional) - Filter by activity type: `collection`, `travel`, `check_in`, `check_out`, `other`
- `loan_id` (optional) - Filter by loan ID
- `receipt_id` (optional) - Filter by receipt ID
- `limit` (optional) - Number of records to return (default: 1000)
- `offset` (optional) - Offset for pagination (default: 0)

### cURL Example
```bash
curl -X GET "http://localhost:3000/admin/agent-location-logs?start_date=2025-01-01&end_date=2025-01-31&limit=100" \
  -H "Authorization: Bearer YOUR_ADMIN_AUTH_TOKEN"
```

### Response
```json
{
  "status": "success",
  "message": "Agent location logs retrieved successfully",
  "data": {
    "total_count": 150,
    "returned_count": 100,
    "filters": {
      "company_id": 8,
      "agent_id": null,
      "start_date": "2025-01-01",
      "end_date": "2025-01-31",
      "activity_type": null,
      "loan_id": null,
      "receipt_id": null
    },
    "map_data": [
      {
        "id": 1,
        "coordinates": {
          "latitude": 12.9716,
          "longitude": 77.5946,
          "accuracy": 10.5,
          "altitude": 920.5
        },
        "agent": {
          "id": 1,
          "name": "Agent Name",
          "mobile_no": "9876543210",
          "line": "Line 1"
        },
        "receipt": {
          "id": 1,
          "rec_no": "REC001",
          "rec_date": "2025-01-15",
          "loan_id": "DL2025001",
          "cust_name": "John Doe",
          "paid_amnt": 200.00
        },
        "activity_type": "collection",
        "address": "123 Main Street, City",
        "loan_id": "DL2025001",
        "remark": "Receipt collection - REC001",
        "timestamp": "2025-01-15T10:30:00.000Z"
      }
    ],
    "agent_summary": [
      {
        "agent_id": 1,
        "agent_name": "Agent Name",
        "agent_mobile": "9876543210",
        "total_locations": 50,
        "locations": [
          {
            "id": 1,
            "latitude": 12.9716,
            "longitude": 77.5946,
            "timestamp": "2025-01-15T10:30:00.000Z",
            "activity_type": "collection"
          }
        ]
      }
    ],
    "pagination": {
      "limit": 100,
      "offset": 0,
      "total": 150
    }
  }
}
```

---

## 2. Get Location Logs for Specific Agent

### Endpoint
```
GET /admin/agent-location-logs/:agent_id
```

### Path Parameters
- `agent_id` (required) - Agent ID

### Query Parameters
- `start_date` (optional) - Start date filter
- `end_date` (optional) - End date filter

### cURL Example
```bash
curl -X GET "http://localhost:3000/admin/agent-location-logs/1?start_date=2025-01-01&end_date=2025-01-31" \
  -H "Authorization: Bearer YOUR_ADMIN_AUTH_TOKEN"
```

### Response
```json
{
  "status": "success",
  "message": "Agent location logs retrieved successfully",
  "data": {
    "agent": {
      "id": 1,
      "name": "Agent Name",
      "mobile_no": "9876543210",
      "line": "Line 1",
      "address": "Agent Address"
    },
    "total_locations": 50,
    "map_data": [
      {
        "id": 1,
        "coordinates": {
          "latitude": 12.9716,
          "longitude": 77.5946,
          "accuracy": 10.5,
          "altitude": 920.5
        },
        "receipt": {
          "id": 1,
          "rec_no": "REC001",
          "rec_date": "2025-01-15",
          "loan_id": "DL2025001",
          "cust_name": "John Doe",
          "paid_amnt": 200.00
        },
        "activity_type": "collection",
        "address": "123 Main Street",
        "loan_id": "DL2025001",
        "remark": "Receipt collection - REC001",
        "timestamp": "2025-01-15T10:30:00.000Z"
      }
    ],
    "route_path": [
      [12.9716, 77.5946],
      [12.9720, 77.5950],
      [12.9725, 77.5955]
    ],
    "date_range": {
      "start": "2025-01-01T08:00:00.000Z",
      "end": "2025-01-31T18:00:00.000Z"
    }
  }
}
```

---

## 3. Get Real-Time Agent Locations

### Endpoint
```
GET /admin/real-time-agent-locations
```

### Query Parameters
- `line` (optional) - Filter by agent line

### cURL Example
```bash
curl -X GET "http://localhost:3000/admin/real-time-agent-locations?line=Line%201" \
  -H "Authorization: Bearer YOUR_ADMIN_AUTH_TOKEN"
```

### Response
```json
{
  "status": "success",
  "message": "Real-time agent locations retrieved successfully",
  "data": {
    "company_id": 8,
    "line": "Line 1",
    "total_agents": 5,
    "agents_with_location": 4,
    "real_time_locations": [
      {
        "agent": {
          "id": 1,
          "name": "Agent Name",
          "mobile_no": "9876543210",
          "line": "Line 1",
          "status": "active"
        },
        "location": {
          "latitude": 12.9716,
          "longitude": 77.5946,
          "accuracy": 10.5,
          "address": "123 Main Street",
          "activity_type": "collection",
          "timestamp": "2025-01-15T10:30:00.000Z"
        },
        "receipt": {
          "id": 1,
          "rec_no": "REC001",
          "loan_id": "DL2025001",
          "cust_name": "John Doe"
        }
      },
      {
        "agent": {
          "id": 2,
          "name": "Agent 2",
          "mobile_no": "9876543211",
          "line": "Line 1",
          "status": "active"
        },
        "location": null,
        "receipt": null
      }
    ],
    "timestamp": "2025-01-15T10:35:00.000Z"
  }
}
```

---

## Complete Example Script

### Bash Script
```bash
#!/bin/bash

# Configuration
BASE_URL="http://localhost:3000"
ADMIN_TOKEN="YOUR_ADMIN_AUTH_TOKEN"

echo "=== 1. Get All Agent Location Logs ==="
curl -X GET "${BASE_URL}/admin/agent-location-logs?start_date=2025-01-01&end_date=2025-01-31&limit=50" \
  -H "Authorization: Bearer ${ADMIN_TOKEN}" | jq '.'

echo -e "\n=== 2. Get Location Logs for Specific Agent ==="
curl -X GET "${BASE_URL}/admin/agent-location-logs/1" \
  -H "Authorization: Bearer ${ADMIN_TOKEN}" | jq '.'

echo -e "\n=== 3. Get Real-Time Agent Locations ==="
curl -X GET "${BASE_URL}/admin/real-time-agent-locations" \
  -H "Authorization: Bearer ${ADMIN_TOKEN}" | jq '.'

echo -e "\n=== 4. Get Location Logs Filtered by Activity Type ==="
curl -X GET "${BASE_URL}/admin/agent-location-logs?activity_type=collection&limit=100" \
  -H "Authorization: Bearer ${ADMIN_TOKEN}" | jq '.'
```

---

## Map Integration Examples

### Google Maps Integration
```javascript
// Using the map_data from API response
const mapData = response.data.map_data;

// Initialize map
const map = new google.maps.Map(document.getElementById('map'), {
  zoom: 12,
  center: { lat: mapData[0].coordinates.latitude, lng: mapData[0].coordinates.longitude }
});

// Add markers for each location
mapData.forEach(location => {
  const marker = new google.maps.Marker({
    position: {
      lat: location.coordinates.latitude,
      lng: location.coordinates.longitude
    },
    map: map,
    title: location.agent ? location.agent.name : 'Unknown',
    label: location.activity_type
  });

  // Add info window
  const infoWindow = new google.maps.InfoWindow({
    content: `
      <div>
        <h3>${location.agent ? location.agent.name : 'Unknown Agent'}</h3>
        <p>Activity: ${location.activity_type}</p>
        <p>Time: ${new Date(location.timestamp).toLocaleString()}</p>
        ${location.receipt ? `<p>Receipt: ${location.receipt.rec_no}</p>` : ''}
        ${location.address ? `<p>Address: ${location.address}</p>` : ''}
      </div>
    `
  });

  marker.addListener('click', () => {
    infoWindow.open(map, marker);
  });
});

// Draw route path if available
if (response.data.route_path) {
  const routePath = response.data.route_path.map(coord => ({
    lat: coord[0],
    lng: coord[1]
  }));

  const routePolyline = new google.maps.Polyline({
    path: routePath,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
  });

  routePolyline.setMap(map);
}
```

### Leaflet Integration
```javascript
// Using the map_data from API response
const mapData = response.data.map_data;

// Initialize map
const map = L.map('map').setView(
  [mapData[0].coordinates.latitude, mapData[0].coordinates.longitude],
  12
);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

// Add markers
mapData.forEach(location => {
  const marker = L.marker([
    location.coordinates.latitude,
    location.coordinates.longitude
  ]).addTo(map);

  marker.bindPopup(`
    <b>${location.agent ? location.agent.name : 'Unknown Agent'}</b><br>
    Activity: ${location.activity_type}<br>
    Time: ${new Date(location.timestamp).toLocaleString()}<br>
    ${location.receipt ? `Receipt: ${location.receipt.rec_no}<br>` : ''}
    ${location.address ? `Address: ${location.address}` : ''}
  `);
});

// Draw route path
if (response.data.route_path) {
  const routePath = response.data.route_path.map(coord => [coord[0], coord[1]]);
  L.polyline(routePath, { color: 'red' }).addTo(map);
}
```

---

## Error Responses

### Missing Authentication
```json
{
  "status": "error",
  "message": "Authentication token required"
}
```

### Invalid Token
```json
{
  "status": "error",
  "message": "Invalid or expired token"
}
```

### Agent Not Found
```json
{
  "status": "error",
  "message": "Agent not found"
}
```

---

## Notes

1. **Admin Authentication**: All endpoints require admin authentication using `authenticateAdmin` middleware.

2. **Company Filtering**: Results are automatically filtered by the admin's company ID.

3. **Pagination**: Use `limit` and `offset` parameters for large datasets.

4. **Date Format**: Use `YYYY-MM-DD` format for date filters.

5. **Route Path**: The route path is provided in `[latitude, longitude]` format for easy polyline drawing.

6. **Real-Time**: The real-time endpoint shows the latest location for each agent, useful for live tracking dashboards.

7. **Activity Types**: 
   - `collection` - Collection activity
   - `travel` - Travel between locations
   - `check_in` - Check-in at location
   - `check_out` - Check-out from location
   - `other` - Other activities

