# Location Tracking Guide - Receipt API

## How to Pass Location Data

Location tracking is **optional** but recommended for collection receipts. When you provide location data, it will be automatically stored in the `agent_location_tracking` table and linked to the receipt.

---

## Location Fields (All Optional)

| Field | Type | Description | Example |
|-------|------|-------------|---------|
| `latitude` | decimal | GPS latitude coordinate | `11.3410` |
| `longitude` | decimal | GPS longitude coordinate | `77.7172` |
| `accuracy` | decimal | GPS accuracy in meters | `10.5` |
| `altitude` | decimal | Altitude above sea level in meters | `920.5` |
| `altitude_accuracy` | decimal | Altitude accuracy in meters | `5.0` |
| `heading` | decimal | Direction of travel in degrees (0-360) | `45.0` |
| `speed` | decimal | Speed in meters per second | `0.0` |
| `address` | string | Human-readable address | `"Erode, Tamil Nadu, India"` |

---

## Minimum Required for Location Tracking

**At minimum, you need `latitude` and `longitude`** for location tracking to work. All other fields are optional.

---

## Example 1: Basic Location (Latitude + Longitude Only)

```bash
curl -X POST "http://192.168.1.3:3000/receipt" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_AUTH_TOKEN" \
  -d '{
    "loan_id": "DL2025002",
    "receipt_date": "2025-12-05",
    "cust_id": 9,
    "cus_name": "Hari",
    "due_amt": 200,
    "paid_amt": 200,
    "paid_dues": 1,
    "latitude": 11.3410,
    "longitude": 77.7172
  }'
```

---

## Example 2: Complete Location Data

```bash
curl -X POST "http://192.168.1.3:3000/receipt" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_AUTH_TOKEN" \
  -d '{
    "loan_id": "DL2025002",
    "receipt_date": "2025-12-05",
    "cust_id": 9,
    "cus_name": "Hari",
    "due_amt": 200,
    "paid_amt": 200,
    "paid_dues": 1,
    "latitude": 11.3410,
    "longitude": 77.7172,
    "accuracy": 10.5,
    "altitude": 920.5,
    "altitude_accuracy": 5.0,
    "heading": 45.0,
    "speed": 0.0,
    "address": "Erode, Tamil Nadu, India"
  }'
```

---

## Example 3: JavaScript/React Native (Mobile App)

```javascript
// Get current location using Geolocation API
navigator.geolocation.getCurrentPosition(
  (position) => {
    const locationData = {
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      accuracy: position.coords.accuracy,
      altitude: position.coords.altitude || null,
      altitude_accuracy: position.coords.altitudeAccuracy || null,
      heading: position.coords.heading || null,
      speed: position.coords.speed || null
    };

    // Make API call with location data
    fetch('http://192.168.1.3:3000/receipt', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
      },
      body: JSON.stringify({
        loan_id: "DL2025002",
        receipt_date: "2025-12-05",
        cust_id: 9,
        cus_name: "Hari",
        due_amt: 200,
        paid_amt: 200,
        paid_dues: 1,
        ...locationData,
        address: "Erode, Tamil Nadu, India" // Optional: Get from reverse geocoding
      })
    })
    .then(response => response.json())
    .then(data => {
      console.log('Receipt created:', data);
      if (data.location_tracked) {
        console.log('Location tracked with ID:', data.location_track_id);
      }
    })
    .catch(error => console.error('Error:', error));
  },
  (error) => {
    console.error('Location error:', error);
    // Still create receipt without location
  },
  {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
  }
);
```

---

## Example 4: React Native with Expo Location

```javascript
import * as Location from 'expo-location';

async function createReceiptWithLocation() {
  try {
    // Request location permissions
    let { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== 'granted') {
      console.log('Permission to access location was denied');
      return;
    }

    // Get current location
    let location = await Location.getCurrentPositionAsync({
      accuracy: Location.Accuracy.High
    });

    // Get address from coordinates (reverse geocoding)
    let address = await Location.reverseGeocodeAsync({
      latitude: location.coords.latitude,
      longitude: location.coords.longitude
    });

    const addressString = address[0] 
      ? `${address[0].street}, ${address[0].city}, ${address[0].region}, ${address[0].country}`
      : null;

    // Create receipt with location
    const response = await fetch('http://192.168.1.3:3000/receipt', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
      },
      body: JSON.stringify({
        loan_id: "DL2025002",
        receipt_date: new Date().toISOString().split('T')[0],
        cust_id: 9,
        cus_name: "Hari",
        due_amt: 200,
        paid_amt: 200,
        paid_dues: 1,
        latitude: location.coords.latitude,
        longitude: location.coords.longitude,
        accuracy: location.coords.accuracy,
        altitude: location.coords.altitude,
        altitude_accuracy: location.coords.altitudeAccuracy,
        heading: location.coords.heading,
        speed: location.coords.speed,
        address: addressString
      })
    });

    const data = await response.json();
    console.log('Receipt created:', data);
  } catch (error) {
    console.error('Error:', error);
  }
}
```

---

## Example 5: Android (Java/Kotlin)

```kotlin
// Get location using FusedLocationProviderClient
val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)

fusedLocationClient.lastLocation.addOnSuccessListener { location ->
    if (location != null) {
        val receiptData = JSONObject().apply {
            put("loan_id", "DL2025002")
            put("receipt_date", "2025-12-05")
            put("cust_id", 9)
            put("cus_name", "Hari")
            put("due_amt", 200)
            put("paid_amt", 200)
            put("paid_dues", 1)
            put("latitude", location.latitude)
            put("longitude", location.longitude)
            put("accuracy", location.accuracy)
            put("altitude", location.altitude)
            put("speed", location.speed)
            put("bearing", location.bearing)
        }
        
        // Make API call
        // ... HTTP request code
    }
}
```

---

## Response with Location Tracking

When location data is provided, the response will include:

```json
{
  "success": true,
  "message": "Loan inserted successfully",
  "loan_id": "DL2025002",
  "customer_id": 9,
  "receipt_no": "REC1764932744675",
  "receipt_id": 45,
  "location_tracked": true,
  "location_track_id": 12
}
```

**Fields:**
- `location_tracked`: `true` if location was successfully tracked
- `location_track_id`: ID of the location tracking entry in the database

---

## Notes

1. **Location is Optional**: You can create receipts without location data. The API will work fine.

2. **Minimum Requirements**: Only `latitude` and `longitude` are required for location tracking. All other fields are optional.

3. **Error Handling**: If location tracking fails (e.g., database error), the receipt will still be created. The error is logged but doesn't fail the entire operation.

4. **Address Field**: The `address` field is optional. You can get it from reverse geocoding services (Google Maps API, etc.) or leave it null.

5. **GPS Accuracy**: Higher accuracy values mean less precise location. Lower values (e.g., 5-10 meters) are better.

6. **Real-time Tracking**: Location is tracked at the moment of receipt creation, providing an audit trail of where collections were made.

---

## Testing Location Tracking

You can test with sample coordinates:

```bash
# Erode, Tamil Nadu coordinates
curl -X POST "http://192.168.1.3:3000/receipt" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_AUTH_TOKEN" \
  -d '{
    "loan_id": "DL2025002",
    "receipt_date": "2025-12-05",
    "cust_id": 9,
    "cus_name": "Hari",
    "due_amt": 200,
    "paid_amt": 200,
    "paid_dues": 1,
    "latitude": 11.3410,
    "longitude": 77.7172,
    "accuracy": 10.5,
    "address": "Erode, Tamil Nadu, India"
  }'
```

---

## Viewing Tracked Locations

You can view all tracked locations using the Admin Location Tracking API:

```bash
GET /admin/agent-location-logs
```

See `ADMIN_LOCATION_TRACKING_API.md` for more details.


