# Employee Transit API Documentation - Admin Controlled System

## Overview
The Employee Transit API works with an admin-controlled assignment system. Admins create and approve transit assignments through the web interface, and employees can only view and execute approved transits through the mobile API.

## 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}
```

## Transit Flow (Admin-Controlled)

### Step 1: Admin Creates Transit (Web Interface)
- Admin accesses: `/transit` (EmployeeAssignmentTransitController)
- Creates transit assignment with:
  - Employee selection
  - From service (current assignment)
  - To service (target location)
  - Transit date and time
  - Reason for transit
- Status: `pending`

### Step 2: Admin Approves Transit
- Admin reviews pending transits
- Approves or rejects with notes
- Status changes to: `approved`

### Step 3: Employee Views & Executes Transit (Mobile API)
- Employee views approved transits
- Starts transit when ready
- Completes transit upon arrival

## API Endpoints

### 1. Get Employee Transits
**GET** `/`

Retrieves all transits assigned to the employee with filtering options.

**Query Parameters:**
- `date` (optional): Filter by specific date (YYYY-MM-DD)
- `status` (optional): Filter by status - `pending`, `approved`, `in_progress`, `completed`, `rejected`, `all` (default: `approved`)
- `per_page` (optional): Number of results per page (1-50, default: 20)

**Example Request:**
```
GET /?status=approved&date=2024-01-15
```

**Response:**
```json
{
  "success": true,
  "message": "Retrieved employee transits",
  "data": {
    "employee": {
      "id": 789,
      "name": "John Doe"
    },
    "transits": [
      {
        "id": 123,
        "transit_date": "2024-01-15",
        "start_time": null,
        "end_time": null,
        "duration_minutes": null,
        "reason": "Emergency coverage requested",
        "status": "approved",
        "from_service": {
          "id": 45,
          "name": "Main Building Security",
          "client": {
            "id": 67,
            "name": "ABC Corporation"
          },
          "location": {
            "id": 89,
            "name": "Main Office",
            "address": "123 Business Ave, Kolkata"
          }
        },
        "to_service": {
          "id": 67,
          "name": "Parking Lot Security",
          "client": {
            "id": 89,
            "name": "XYZ Properties"
          },
          "location": {
            "id": 101,
            "name": "Parking Area B",
            "address": "456 Parking Street, Kolkata"
          }
        },
        "approval_info": {
          "approved_by": "Admin User",
          "approved_at": "2024-01-15T10:30:00.000Z",
          "approval_notes": "Approved for emergency coverage"
        },
        "actions_available": {
          "can_start": true,
          "can_complete": false,
          "is_today": true
        },
        "created_at": "2024-01-15T09:15:00.000Z"
      }
    ],
    "summary": {
      "total_transits": 1,
      "pending_count": 0,
      "approved_count": 1,
      "completed_count": 0,
      "today_count": 1
    },
    "filters_applied": {
      "date": "2024-01-15",
      "status": "approved"
    },
    "pagination": {
      "current_page": 1,
      "last_page": 1,
      "per_page": 20,
      "total": 1
    }
  }
}
```

---

### 2. Get Transit Status
**GET** `/status`

Retrieves the current status of the employee's most relevant transit (approved or in progress).

**Response (No Active Transit):**
```json
{
  "success": true,
  "data": {
    "active_transit": false,
    "message": "No active or approved transits",
    "action_required": "Contact admin to create transit assignment"
  }
}
```

**Response (Has Approved Transit):**
```json
{
  "success": true,
  "data": {
    "active_transit": true,
    "transit": {
      "id": 123,
      "transit_date": "2024-01-15",
      "start_time": null,
      "end_time": null,
      "duration_minutes": null,
      "reason": "Emergency coverage requested",
      "status": "approved",
      "from_service": {
        "id": 45,
        "name": "Main Building Security",
        "client": "ABC Corporation"
      },
      "to_service": {
        "id": 67,
        "name": "Parking Lot Security",
        "client": "XYZ Properties"
      }
    },
    "current_status": "approved",
    "duration_so_far_minutes": null,
    "is_today": true,
    "actions_available": {
      "can_start": true,
      "can_complete": false
    }
  }
}
```

---

### 3. Start Transit
**POST** `/{transitId}/start`

Starts an admin-approved transit assignment.

**Parameters:**
- `transitId` (path): ID of the approved transit to start

**Response:**
```json
{
  "success": true,
  "message": "Transit started successfully",
  "data": {
    "transit_id": 123,
    "start_time": "2024-01-15T14:30:00.000Z",
    "status": "in_progress",
    "from_service": {
      "id": 45,
      "name": "Main Building Security",
      "client": "ABC Corporation"
    },
    "to_service": {
      "id": 67,
      "name": "Parking Lot Security",
      "client": "XYZ Properties"
    },
    "employee": {
      "id": 789,
      "name": "John Doe"
    }
  }
}
```

**Error Response:**
```json
{
  "success": false,
  "message": "Failed to start transit: No approved transit found or transit not accessible"
}
```

---

### 4. Complete Transit
**POST** `/{transitId}/complete`

Completes an in-progress transit assignment.

**Parameters:**
- `transitId` (path): ID of the in-progress transit to complete

**Request Body:**
```json
{
  "notes": "Successfully arrived and briefed on security procedures"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Transit completed successfully",
  "data": {
    "transit_id": 123,
    "end_time": "2024-01-15T14:58:00.000Z",
    "duration_minutes": 28,
    "from_service": {
      "id": 45,
      "name": "Main Building Security",
      "client": "ABC Corporation"
    },
    "to_service": {
      "id": 67,
      "name": "Parking Lot Security",
      "client": "XYZ Properties"
    },
    "status": "completed"
  }
}
```

---

### 5. 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
```

**Response:**
```json
{
  "success": true,
  "data": {
    "transits": [
      {
        "id": 123,
        "transit_date": "2024-01-15",
        "start_time": "2024-01-15T14:30:00.000Z",
        "end_time": "2024-01-15T14:58:00.000Z",
        "duration_minutes": 28,
        "status": "completed",
        "reason": "Emergency coverage requested",
        "from_service": {
          "id": 45,
          "name": "Main Building Security",
          "client": "ABC Corporation"
        },
        "to_service": {
          "id": 67,
          "name": "Parking Lot Security",
          "client": "XYZ Properties"
        },
        "approval_info": {
          "approved_by": "Admin User",
          "approved_at": "2024-01-15T10:30:00.000Z",
          "approval_notes": "Approved for emergency coverage"
        }
      }
    ],
    "summary": {
      "total_transits": 15,
      "completed_transits": 12,
      "pending_transits": 1,
      "approved_transits": 1,
      "rejected_transits": 1,
      "total_duration_minutes": 420,
      "average_duration_minutes": 35
    },
    "pagination": {
      "current_page": 1,
      "last_page": 2,
      "per_page": 20,
      "total": 15
    }
  }
}
```

## Transit Status Types

1. **pending**: Admin created but not yet approved
2. **approved**: Admin approved, ready for employee to start
3. **in_progress**: Employee has started the transit
4. **completed**: Employee has completed the transit
5. **rejected**: Admin rejected the transit request

## Business Logic

### Admin Responsibilities
- Create transit assignments with proper from/to services
- Approve or reject pending transits
- Manage transit schedules and assignments
- View real-time transit status and history

### Employee Capabilities
- View approved transits assigned to them
- Start approved transits (changes status to in_progress)
- Complete in-progress transits (changes status to completed)
- View personal transit history

### Transit Assignment Rules
- Employees can only start transits with `approved` status
- Only one transit can be `in_progress` at a time per employee
- Transit automatically handles service assignment changes:
  - Ends previous assignment when completed
  - Activates new assignment automatically

### System Integration
- Uses existing `EmployeeAssignmentTransit` model
- Integrates with `EmployeeAssignment` for service management
- Maintains audit trail with approver information
- Supports tenant-based multi-tenancy

## Mobile App Integration

### Complete Employee Flow
```javascript
// 1. Check for approved transits
const checkTransitStatus = async () => {
  const response = await fetch('/api/v1/employee/transit/status', {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  
  const data = await response.json();
  if (data.success && data.data.active_transit) {
    if (data.data.actions_available.can_start) {
      // Show "Start Transit" button
      showStartButton(data.data.transit.id);
    } else if (data.data.actions_available.can_complete) {
      // Show "Complete Transit" button
      showCompleteButton(data.data.transit.id);
    }
  }
};

// 2. Start approved transit
const startTransit = async (transitId) => {
  const response = await fetch(`/api/v1/employee/transit/${transitId}/start`, {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${token}` }
  });
  
  const data = await response.json();
  if (data.success) {
    // Update UI to show transit in progress
    showTransitInProgress(data.data);
    // Start location tracking if needed
    startLocationTracking();
  }
};

// 3. Complete transit
const completeTransit = async (transitId, notes) => {
  const response = await fetch(`/api/v1/employee/transit/${transitId}/complete`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ notes })
  });
  
  const data = await response.json();
  if (data.success) {
    // Show completion summary
    showTransitCompleted(data.data);
    // Refresh transit list
    refreshTransitList();
  }
};
```

## Error Handling

**Common Error Responses:**
```json
{
  "success": false,
  "message": "Failed to start transit: No approved transit found or transit not accessible"
}
```

```json
{
  "success": false,
  "message": "Failed to complete transit: No active transit found or transit not accessible"
}
```

## Rate Limiting
- Transit status checks: 60 requests per hour
- Start/complete transit: 10 requests per hour
- History requests: 30 requests per hour

## Security Features
- Employees can only access their own transits
- Admin approval required before transit execution
- Complete audit trail with approver information
- Tenant-based data isolation

This API provides employees with controlled access to admin-approved transit assignments while maintaining proper security and audit trails through the existing admin transit management system.
