# Geofencing API Documentation

## Overview

The Geofencing API provides comprehensive location-based monitoring and violation detection for employee transit and patrol operations. It supports circular, polygonal, and rectangular geofences with real-time tracking, violation detection, and analytics.

## API Endpoints

### Base URL
```
/api/v1/employee/geofence
```

### Authentication
All endpoints require authentication via Sanctum token. Include the token in the Authorization header:
```
Authorization: Bearer {token}
```

## Endpoints

### 1. Check Geofence Status
**POST** `/check`

Check current location against all active geofences and detect violations.

**Request Body:**
```json
{
  "latitude": 19.0760,
  "longitude": 72.8777,
  "accuracy": 10.5
}
```

**Response:**
```json
{
  "success": true,
  "message": "Geofence check completed",
  "data": {
    "timestamp": "2026-01-10T08:30:00.000Z",
    "location": {
      "latitude": 19.0760,
      "longitude": 72.8777,
      "accuracy": 10.5
    },
    "geofence_status": {
      "inside_any_geofence": true,
      "inside_geofences": [
        {
          "geofence_id": 1,
          "name": "Mumbai Office",
          "type": "radius",
          "client": "Acme Corp",
          "distance_from_center": 45.2
        }
      ],
      "nearby_geofences": [],
      "violations": []
    },
    "alerts": []
  }
}
```

### 2. Get Employee Geofences
**GET** `/`

Retrieve all active geofences assigned to the employee.

**Response:**
```json
{
  "success": true,
  "data": {
    "geofences": [
      {
        "id": 1,
        "name": "Mumbai Office",
        "type": "radius",
        "client": {
          "id": 1,
          "name": "Acme Corp"
        },
        "location": {
          "id": 1,
          "name": "Head Office",
          "address": "123 Main St, Mumbai"
        },
        "geometry": {
          "type": "radius",
          "coordinates": {"lat": 19.0760, "lng": 72.8777},
          "bounds": null,
          "radius": 100,
          "tolerance": 10
        },
        "restrictions": {
          "allowed_hours": null,
          "max_stay_duration": null,
          "speed_limit_kmh": null
        },
        "is_active": true
      }
    ],
    "summary": {
      "total_geofences": 1,
      "circular_geofences": 1,
      "polygonal_geofences": 0,
      "active_geofences": 1
    }
  }
}
```

### 3. Get Geofence History
**GET** `/history`

Retrieve historical geofence entry/exit events and violations.

**Query Parameters:**
- `start_date` (optional): Filter by start date (YYYY-MM-DD)
- `end_date` (optional): Filter by end date (YYYY-MM-DD)
- `geofence_id` (optional): Filter by specific geofence
- `event_type` (optional): Filter by event type (entry, exit, violation)
- `per_page` (optional): Results per page (1-100, default: 50)

**Response:**
```json
{
  "success": true,
  "data": {
    "events": [
      {
        "id": 1,
        "timestamp": "2026-01-10T08:00:00.000Z",
        "event_type": "entry",
        "location": {
          "latitude": 19.0760,
          "longitude": 72.8777,
          "accuracy": 10.5
        },
        "geofence": {
          "id": 1,
          "name": "Mumbai Office",
          "type": "radius",
          "client": "Acme Corp"
        },
        "duration_seconds": null,
        "violation_details": null
      }
    ],
    "summary": {
      "total_events": 1,
      "entries": 1,
      "exits": 0,
      "violations": 0
    },
    "pagination": {
      "current_page": 1,
      "last_page": 1,
      "per_page": 50,
      "total": 1
    }
  }
}
```

### 4. Get Active Alerts
**GET** `/alerts`

Retrieve all active geofence alerts and violations requiring attention.

**Response:**
```json
{
  "success": true,
  "data": {
    "alerts": [
      {
        "id": 1,
        "type": "violation",
        "severity": "critical",
        "title": "Unauthorized Entry Detected",
        "message": "unauthorized_entry",
        "timestamp": "2026-01-10T08:15:00.000Z",
        "geofence": {
          "id": 2,
          "name": "Restricted Area",
          "client": "Acme Corp"
        },
        "location": {
          "latitude": 19.0765,
          "longitude": 72.8780
        },
        "action_required": true,
        "acknowledged": false,
        "acknowledged_at": null
      }
    ],
    "summary": {
      "total_alerts": 1,
      "unacknowledged": 1,
      "critical_alerts": 1,
      "violation_alerts": 1
    }
  }
}
```

### 5. Acknowledge Alert
**POST** `/alerts/{alertId}/acknowledge`

Acknowledge and resolve a geofence alert.

**Request Body:**
```json
{
  "notes": "False alarm - was authorized by supervisor"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Alert acknowledged successfully",
  "data": {
    "alert_id": 1,
    "acknowledged_at": "2026-01-10T08:30:00.000Z",
    "acknowledged_by": "John Doe",
    "notes": "False alarm - was authorized by supervisor"
  }
}
```

### 6. Get Analytics
**GET** `/analytics`

Retrieve comprehensive geofence analytics and compliance metrics.

**Query Parameters:**
- `start_date` (optional): Analysis start date (YYYY-MM-DD)
- `end_date` (optional): Analysis end date (YYYY-MM-DD)
- `geofence_id` (optional): Filter by specific geofence

**Response:**
```json
{
  "success": true,
  "data": {
    "time_period": {
      "start_date": "2025-12-11",
      "end_date": "2026-01-10",
      "days_analyzed": 30
    },
    "compliance": {
      "total_entries": 150,
      "authorized_entries": 145,
      "unauthorized_entries": 5,
      "compliance_rate": 96.67
    },
    "violations": {
      "total_violations": 8,
      "by_type": {
        "unauthorized_entry": 3,
        "entry_violation": 2,
        "exit_violation": 2,
        "missed_checkpoint": 1
      },
      "by_severity": {
        "critical": 3,
        "high": 2,
        "medium": 2,
        "low": 1
      },
      "trend": {
        "current_week": 2,
        "previous_week": 3,
        "trend": "decreasing"
      }
    },
    "time_analysis": {
      "peak_hours": {
        "8": 25,
        "9": 22,
        "17": 20
      },
      "average_stay_duration": 2847.5,
      "frequency_by_day": {
        "Monday": 22,
        "Tuesday": 24,
        "Wednesday": 21,
        "Thursday": 23,
        "Friday": 20,
        "Saturday": 8,
        "Sunday": 5
      }
    },
    "geofence_performance": [
      {
        "geofence_name": "Mumbai Office",
        "total_entries": 89,
        "total_exits": 87,
        "violations": 2,
        "compliance_rate": 97.75
      }
    ]
  }
}
```

## Geofence Types

### 1. Circular (Radius)
- Defined by center point and radius in meters
- Suitable for point locations like buildings, checkpoints

### 2. Polygonal
- Defined by array of coordinate points forming a polygon
- Suitable for irregular areas like property boundaries

### 3. Rectangular
- Defined by bounding box (north, south, east, west)
- Suitable for rectangular areas like fields, zones

## Violation Types

| Type | Description | Severity |
|------|-------------|----------|
| `unauthorized_entry` | Entry into geofence without authorization | Critical |
| `entry_violation` | Entry during restricted hours | High |
| `exit_violation` | Unauthorized exit from geofence | Medium |
| `missed_checkpoint` | Failure to check in at required location | Low |

## Alert Severity Levels

- **Critical**: Immediate attention required (unauthorized entry)
- **High**: Important but not immediate (entry violations)
- **Medium**: Standard violations (exit violations)
- **Low**: Minor issues (missed checkpoints)

## Integration with Transit Tracking

The geofencing API integrates seamlessly with the transit tracking system:

1. **Automatic Checks**: Transit locations are automatically checked against geofences
2. **Violation Logging**: Violations are logged during transit tracking
3. **Route Compliance**: Ensures transit routes stay within authorized areas
4. **Checkpoint Validation**: Validates patrol checkpoint visits

## Error Handling

### Common Error Responses

**400 Bad Request:**
```json
{
  "success": false,
  "message": "The given data was invalid.",
  "errors": {
    "latitude": ["Latitude is required for geofence check"],
    "longitude": ["Longitude must be between -180 and 180"]
  }
}
```

**401 Unauthorized:**
```json
{
  "success": false,
  "message": "Unauthenticated."
}
```

**404 Not Found:**
```json
{
  "success": false,
  "message": "Alert not found or already acknowledged"
}
```

**500 Server Error:**
```json
{
  "success": false,
  "message": "Geofence check failed: Database connection error"
}
```

## Rate Limiting

- Geofence check endpoint: 60 requests per minute
- Other endpoints: 100 requests per minute

## Best Practices

1. **Location Accuracy**: Always provide GPS accuracy when available
2. **Batch Processing**: Use history endpoint for bulk data retrieval
3. **Real-time Updates**: Implement WebSocket for real-time alerts
4. **Error Handling**: Implement proper error handling and retry logic
5. **Battery Optimization**: Consider battery impact of frequent location checks

## Webhook Integration

For real-time notifications, configure webhooks to receive:

- New violations
- Alert acknowledgments
- Geofence entries/exits

Webhook payload structure:
```json
{
  "event": "geofence.violation",
  "data": {
    "violation_id": 123,
    "employee_id": 456,
    "geofence_id": 78,
    "violation_type": "unauthorized_entry",
    "timestamp": "2026-01-10T08:15:00.000Z",
    "location": {
      "latitude": 19.0765,
      "longitude": 72.8780
    }
  }
}
```
