# Employee Service Transit API Documentation

## Overview
The Employee Service Transit API enables employees to temporarily move from their current service assignment to another service location. This system tracks service-to-service transitions, providing real-time status updates and historical records of all transit assignments.

## Base URL
```
http://your-domain.com/api/v1/employee/transit
```

## Authentication
All endpoints require authentication using Laravel Sanctum. Include the following header:
```
Authorization: Bearer {token}
```

## API Endpoints

### 1. Get Available Services
**GET** `/available-services`

Retrieves a list of services available for transit assignment, excluding the employee's current service.

**Query Parameters:**
- `search` (optional): Search by service name or client name
- `per_page` (optional): Number of results per page (1-50, default: 20)

**Example Request:**
```
GET /available-services?search=security&per_page=10
```

**Response:**
```json
{
  "success": true,
  "message": "Retrieved available services for transit",
  "data": {
    "employee": {
      "id": 789,
      "name": "John Doe"
    },
    "current_service": {
      "id": 45,
      "name": "Main Building Security",
      "client": "ABC Corporation",
      "location": "123 Business Ave, Kolkata"
    },
    "available_services": [
      {
        "id": 67,
        "service_name": "Parking Lot Security",
        "service_type": "security_patrol",
        "client": {
          "id": 89,
          "name": "XYZ Properties"
        },
        "location": {
          "id": 101,
          "name": "Parking Area B",
          "address": "456 Parking Street, Kolkata"
        },
        "estimated_duration": 2,
        "priority_level": "medium"
      }
    ],
    "pagination": {
      "current_page": 1,
      "last_page": 3,
      "per_page": 10,
      "total": 25
    },
    "filters_applied": {
      "search": "security"
    }
  }
}
```

---

### 2. Start Transit
**POST** `/start`

Initiates a new transit assignment from the employee's current service to a target service.

**Request Body:**
```json
{
  "to_service_id": 67,
  "purpose": "Emergency coverage requested",
  "notes": "Covering for sick colleague"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Transit started successfully",
  "data": {
    "transit_id": 123,
    "from_location": "123 Business Ave, Kolkata",
    "to_location": "456 Parking Street, Kolkata",
    "start_time": "2024-01-15T14:30:00.000Z",
    "estimated_arrival": "2024-01-15T15:00:00.000Z",
    "purpose": "Emergency coverage requested",
    "status": "in_transit",
    "employee": {
      "id": 789,
      "name": "John Doe"
    },
    "client": {
      "id": 89,
      "name": "XYZ Properties"
    }
  }
}
```

**Error Response:**
```json
{
  "success": false,
  "message": "Failed to start transit: Employee already has an active transit assignment"
}
```

---

### 3. Update Location
**POST** `/location`

Updates the employee's current location during an active transit (optional tracking feature).

**Request Body:**
```json
{
  "latitude": 22.5726,
  "longitude": 88.3639,
  "accuracy": 10.5,
  "speed": 45.2,
  "heading": 90.0,
  "altitude": 15.0
}
```

**Response:**
```json
{
  "success": true,
  "message": "Location updated successfully",
  "data": {
    "location_id": 456,
    "timestamp": "2024-01-15T14:45:00.000Z",
    "coordinates": {
      "latitude": 22.5726,
      "longitude": 88.3639,
      "accuracy": 10.5
    },
    "movement": {
      "speed_kmh": 45.2,
      "heading_degrees": 90.0,
      "altitude_meters": 15.0
    }
  }
}
```

---

### 4. Complete Transit
**POST** `/complete`

Finalizes the transit assignment and records arrival at the target service location.

**Request Body:**
```json
{
  "notes": "Successfully arrived and briefed on security procedures"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Transit completed successfully",
  "data": {
    "transit_id": 123,
    "actual_arrival": "2024-01-15T14:58:00.000Z",
    "duration_minutes": 28,
    "distance_km": 3.2,
    "from_location": "123 Business Ave, Kolkata",
    "to_location": "456 Parking Street, Kolkata",
    "purpose": "Emergency coverage requested",
    "status": "arrived",
    "client": {
      "id": 89,
      "name": "XYZ Properties"
    }
  }
}
```

---

### 5. Get Transit Status
**GET** `/status`

Retrieves the current status of the employee's transit assignment.

**Response (No Active Transit):**
```json
{
  "success": true,
  "data": {
    "active_transit": false,
    "message": "No active transit",
    "action_required": "Start a new transit to begin service assignment"
  }
}
```

**Response (Active Transit):**
```json
{
  "success": true,
  "data": {
    "active_transit": true,
    "transit": {
      "id": 123,
      "from_location": "123 Business Ave, Kolkata",
      "to_location": "456 Parking Street, Kolkata",
      "start_time": "2024-01-15T14:30:00.000Z",
      "estimated_arrival": "2024-01-15T15:00:00.000Z",
      "purpose": "Emergency coverage requested",
      "status": "in_transit"
    },
    "current_location": {
      "latitude": 22.5726,
      "longitude": 88.3639,
      "updated_at": "2024-01-15T14:45:00.000Z"
    },
    "duration_so_far_minutes": 15,
    "is_delayed": false,
    "client": {
      "id": 89,
      "name": "XYZ Properties"
    }
  }
}
```

---

### 6. Get Transit History
**GET** `/history`

Retrieves historical transit assignments for the employee.

**Query Parameters:**
- `start_date` (optional): Start date filter (YYYY-MM-DD)
- `end_date` (optional): End date filter (YYYY-MM-DD)
- `per_page` (optional): Number of results per page (1-100, default: 20)

**Example Request:**
```
GET /history?start_date=2024-01-01&end_date=2024-01-31&per_page=15
```

**Response:**
```json
{
  "success": true,
  "data": {
    "transits": [
      {
        "id": 123,
        "date": "2024-01-15",
        "start_time": "2024-01-15T14:30:00.000Z",
        "actual_arrival": "2024-01-15T14:58:00.000Z",
        "duration_minutes": 28,
        "status": "arrived",
        "locations": {
          "from": "123 Business Ave, Kolkata",
          "to": "456 Parking Street, Kolkata"
        },
        "purpose": "Emergency coverage requested",
        "distance_km": 3.2,
        "client": {
          "id": 89,
          "name": "XYZ Properties"
        },
        "vehicle": "Company Vehicle A",
        "notes": "Successfully arrived and briefed on security procedures"
      }
    ],
    "summary": {
      "total_transits": 15,
      "completed_transits": 12,
      "active_transits": 1,
      "cancelled_transits": 2,
      "total_distance": 45.8,
      "average_distance": 3.05
    },
    "pagination": {
      "current_page": 1,
      "last_page": 2,
      "per_page": 15,
      "total": 15
    }
  }
}
```

## Transit Status Types

1. **in_transit**: Employee is currently traveling to the target service
2. **arrived**: Employee has successfully reached the destination
3. **delayed**: Transit is running behind estimated arrival time
4. **cancelled**: Transit was cancelled before completion

## Error Handling

All endpoints may return the following error responses:

**400 Bad Request:**
```json
{
  "success": false,
  "message": "Failed to start transit: Employee has no current service assignment"
}
```

**401 Unauthorized:**
```json
{
  "success": false,
  "message": "Unauthenticated"
}
```

**500 Internal Server Error:**
```json
{
  "success": false,
  "message": "Failed to get transit status: Database connection error"
}
```

## Data Validation

### Start Transit Validation
- `to_service_id`: Required, must exist in client_services table
- `purpose`: Optional, string, max 200 characters
- `notes`: Optional, string, max 500 characters

### Location Update Validation
- `latitude`: Required, numeric, between -90 and 90
- `longitude`: Required, numeric, between -180 and 180
- `accuracy`: Optional, numeric, 0-1000 meters
- `speed`: Optional, numeric, 0-500 km/h
- `heading`: Optional, numeric, 0-360 degrees
- `altitude`: Optional, numeric, -500 to 10000 meters

## Business Logic

### Transit Assignment Rules
1. Employees must have an active service assignment to start transit
2. Cannot start transit if already in active transit
3. Target service must be different from current service
4. Target service must be active and available

### Estimated Arrival Calculation
- Default estimation: 30 minutes
- Distance-based estimation: 50 km/h average speed
- Minimum estimation: 15 minutes

### Transit Logging
All transit actions are logged in the `transit_logs` table:
- `started`: Transit initiated
- `location_update`: Position update during transit
- `completed`: Transit successfully finished
- `cancelled`: Transit cancelled

## Integration Examples

### Complete Transit Flow
1. **Check Available Services**
   ```
   GET /available-services
   ```

2. **Start Transit Assignment**
   ```
   POST /start
   {
     "to_service_id": 67,
     "purpose": "Emergency coverage",
     "notes": "Covering for sick colleague"
   }
   ```

3. **Update Location (Optional)**
   ```
   POST /location
   {
     "latitude": 22.5726,
     "longitude": 88.3639,
     "accuracy": 8.5
   }
   ```

4. **Check Status**
   ```
   GET /status
   ```

5. **Complete Transit**
   ```
   POST /complete
   {
     "notes": "Arrived and briefed on procedures"
   }
   ```

6. **View History**
   ```
   GET /history?start_date=2024-01-15
   ```

### Mobile App Integration
```javascript
// Start transit flow
const startServiceTransit = async (serviceId, purpose) => {
  try {
    const response = await fetch('/api/v1/employee/transit/start', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        to_service_id: serviceId,
        purpose: purpose,
        notes: 'Mobile app initiated transit'
      })
    });
    
    const data = await response.json();
    if (data.success) {
      // Start location tracking
      startLocationTracking();
      // Show transit status UI
      showTransitStatus(data.data);
      // Set completion reminder
      setTransitReminder(data.data.estimated_arrival);
    }
  } catch (error) {
    console.error('Failed to start transit:', error);
  }
};
```

## Rate Limiting
- Service availability requests: 100 requests per hour
- Transit start/complete: 10 requests per hour
- Location updates: 1 request per 30 seconds
- Status checks: 60 requests per hour

## Security Considerations
- Employees can only transit to services they are authorized to access
- All transit actions are logged with employee ID and timestamp
- Location data is optional and only used for tracking purposes
- Service assignments are validated before transit initiation

## Reporting Features

### Transit Analytics
- Total transits per employee
- Average transit duration
- Most frequent service destinations
- Transit completion rates
- Distance traveled statistics

### Management Visibility
- Real-time transit status for supervisors
- Transit history for performance review
- Service coverage optimization insights
- Emergency response tracking

This comprehensive API provides all necessary functionality for employee service transit management with real-time tracking, historical reporting, and seamless integration with existing service management systems.
