# Staff Check-In/Check-Out Management API

This API provides endpoints for staff management including check-in, check-out, history tracking, and current status monitoring.

## Endpoints Overview

1. **POST** `/admin/staff/check-in` - Staff check-in
2. **POST** `/admin/staff/check-out` - Staff check-out
3. **GET** `/admin/staff/check-in-out/history` - Get check-in/out history
4. **GET** `/admin/staff/:id/check-in-out/history` - Get history for specific staff
5. **GET** `/admin/staff/check-in-status` - Get current check-in status

## Authentication

All endpoints require admin authentication via JWT token or `auth_token` in the Authorization header.

---

## 1. Staff Check-In

Check in a staff member (or self-check-in if no staff_id provided).

### Endpoint
```
POST /admin/staff/check-in
```

### Request Body
```json
{
  "staff_id": 1,              // Optional: Staff ID (defaults to authenticated admin's ID)
  "latitude": 11.3410,        // Optional: Check-in latitude
  "longitude": 77.7172,       // Optional: Check-in longitude
  "location": "Office, Erode", // Optional: Check-in location address
  "notes": "Morning check-in" // Optional: Additional notes
}
```

### Success Response (200 OK)
```json
{
  "status": "success",
  "message": "Check-in successful",
  "data": {
    "check_in_id": 123,
    "staff_id": 1,
    "staff_name": "John Doe",
    "check_in_time": "2025-01-15T09:00:00.000Z",
    "check_in_location": "Office, Erode",
    "check_in_latitude": 11.3410,
    "check_in_longitude": 77.7172,
    "status": "checked_in",
    "notes": "Morning check-in"
  }
}
```

### Error Responses

#### 400 Bad Request - Already Checked In
```json
{
  "status": "error",
  "message": "Staff member is already checked in",
  "data": {
    "check_in_id": 122,
    "check_in_time": "2025-01-15T08:30:00.000Z",
    "check_in_location": "Office, Erode"
  }
}
```

#### 404 Not Found - Staff Not Found
```json
{
  "status": "error",
  "message": "Staff member not found"
}
```

### cURL Example
```bash
curl -X POST "http://192.168.1.3:3000/admin/staff/check-in" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN" \
  -d '{
    "latitude": 11.3410,
    "longitude": 77.7172,
    "location": "Office, Erode",
    "notes": "Morning check-in"
  }'
```

### PowerShell Example
```powershell
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$session.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1"

Invoke-WebRequest -UseBasicParsing `
  -Uri "http://192.168.1.3:3000/admin/staff/check-in" `
  -Method "POST" `
  -WebSession $session `
  -Headers @{
    "Accept"="application/json"
    "Authorization"="Bearer YOUR_ADMIN_JWT_TOKEN"
  } `
  -ContentType "application/json" `
  -Body '{
    "latitude": 11.3410,
    "longitude": 77.7172,
    "location": "Office, Erode",
    "notes": "Morning check-in"
  }'
```

---

## 2. Staff Check-Out

Check out a staff member (or self-check-out if no staff_id provided).

### Endpoint
```
POST /admin/staff/check-out
```

### Request Body
```json
{
  "staff_id": 1,              // Optional: Staff ID (defaults to authenticated admin's ID)
  "latitude": 11.3410,        // Optional: Check-out latitude
  "longitude": 77.7172,        // Optional: Check-out longitude
  "location": "Office, Erode", // Optional: Check-out location address
  "notes": "End of day"        // Optional: Additional notes
}
```

### Success Response (200 OK)
```json
{
  "status": "success",
  "message": "Check-out successful",
  "data": {
    "check_in_id": 123,
    "staff_id": 1,
    "staff_name": "John Doe",
    "check_in_time": "2025-01-15T09:00:00.000Z",
    "check_out_time": "2025-01-15T18:00:00.000Z",
    "check_in_location": "Office, Erode",
    "check_out_location": "Office, Erode",
    "duration": {
      "hours": 9,
      "minutes": 0,
      "total_minutes": 540,
      "total_seconds": 32400
    },
    "status": "checked_out",
    "notes": "End of day"
  }
}
```

### Error Responses

#### 400 Bad Request - No Active Check-In
```json
{
  "status": "error",
  "message": "No active check-in found. Please check in first."
}
```

### cURL Example
```bash
curl -X POST "http://192.168.1.3:3000/admin/staff/check-out" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN" \
  -d '{
    "latitude": 11.3410,
    "longitude": 77.7172,
    "location": "Office, Erode",
    "notes": "End of day"
  }'
```

---

## 3. Get Check-In/Check-Out History

Retrieve check-in/check-out history with filtering options.

### Endpoint
```
GET /admin/staff/check-in-out/history
GET /admin/staff/:id/check-in-out/history
```

### Query Parameters
- `staff_id` (optional): Filter by staff ID
- `start_date` (optional): Start date filter (YYYY-MM-DD)
- `end_date` (optional): End date filter (YYYY-MM-DD)
- `status` (optional): Filter by status (`checked_in` or `checked_out`)
- `limit` (optional): Maximum number of records (default: 1000)

### Success Response (200 OK)
```json
{
  "status": "success",
  "message": "Check-in/out history retrieved successfully",
  "data": {
    "filters": {
      "staff_id": null,
      "start_date": "2025-01-01",
      "end_date": "2025-01-31",
      "status": null,
      "limit": null
    },
    "summary": {
      "total_records": 150,
      "checked_in": 5,
      "checked_out": 145,
      "total_duration_minutes": 64800,
      "average_duration_minutes": 447
    },
    "records": [
      {
        "id": 123,
        "staff_id": 1,
        "staff_name": "John Doe",
        "staff_username": "johndoe",
        "check_in_time": "2025-01-15T09:00:00.000Z",
        "check_out_time": "2025-01-15T18:00:00.000Z",
        "check_in_location": "Office, Erode",
        "check_out_location": "Office, Erode",
        "check_in_latitude": 11.3410,
        "check_in_longitude": 77.7172,
        "check_out_latitude": 11.3410,
        "check_out_longitude": 77.7172,
        "status": "checked_out",
        "duration": {
          "hours": 9,
          "minutes": 0,
          "total_minutes": 540,
          "total_seconds": 32400
        },
        "notes": "End of day",
        "created_at": "2025-01-15T09:00:00.000Z",
        "updated_at": "2025-01-15T18:00:00.000Z"
      }
    ]
  }
}
```

### cURL Examples

#### Get All History
```bash
curl -X GET "http://192.168.1.3:3000/admin/staff/check-in-out/history" \
  -H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN"
```

#### Get History with Date Range
```bash
curl -X GET "http://192.168.1.3:3000/admin/staff/check-in-out/history?start_date=2025-01-01&end_date=2025-01-31" \
  -H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN"
```

#### Get History for Specific Staff
```bash
curl -X GET "http://192.168.1.3:3000/admin/staff/1/check-in-out/history?start_date=2025-01-01&end_date=2025-01-31" \
  -H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN"
```

#### Get Only Checked-In Records
```bash
curl -X GET "http://192.168.1.3:3000/admin/staff/check-in-out/history?status=checked_in" \
  -H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN"
```

---

## 4. Get Current Check-In Status

Get list of all staff members currently checked in.

### Endpoint
```
GET /admin/staff/check-in-status
```

### Query Parameters
- `staff_id` (optional): Filter by specific staff ID

### Success Response (200 OK)
```json
{
  "status": "success",
  "message": "Current check-in status retrieved successfully",
  "data": {
    "total_checked_in": 3,
    "checked_in_staff": [
      {
        "check_in_id": 123,
        "staff_id": 1,
        "staff_name": "John Doe",
        "staff_username": "johndoe",
        "check_in_time": "2025-01-15T09:00:00.000Z",
        "check_in_location": "Office, Erode",
        "check_in_latitude": 11.3410,
        "check_in_longitude": 77.7172,
        "current_duration": {
          "hours": 5,
          "minutes": 30,
          "total_minutes": 330,
          "total_seconds": 19800
        },
        "notes": "Morning check-in"
      }
    ],
    "timestamp": "2025-01-15T14:30:00.000Z"
  }
}
```

### cURL Example
```bash
curl -X GET "http://192.168.1.3:3000/admin/staff/check-in-status" \
  -H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN"
```

### Get Status for Specific Staff
```bash
curl -X GET "http://192.168.1.3:3000/admin/staff/check-in-status?staff_id=1" \
  -H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN"
```

---

## Features

1. **Self Check-In/Out**: If `staff_id` is not provided, the authenticated admin can check themselves in/out
2. **Location Tracking**: Optional latitude/longitude and location address for check-in and check-out
3. **Duration Calculation**: Automatic calculation of work duration on check-out
4. **History Tracking**: Complete history with filtering by date, staff, and status
5. **Current Status**: Real-time view of who's currently checked in
6. **Statistics**: Summary statistics including total duration and averages
7. **Validation**: Prevents duplicate check-ins and validates staff belongs to company

## Database Schema

The `staff_check_in_out` table includes:
- `id`: Primary key
- `staff_id`: Foreign key to `staff.uid`
- `com_id`: Company ID
- `check_in_time`: Check-in timestamp
- `check_out_time`: Check-out timestamp (nullable)
- `check_in_location`: Check-in location address
- `check_out_location`: Check-out location address
- `check_in_latitude` / `check_in_longitude`: Check-in coordinates
- `check_out_latitude` / `check_out_longitude`: Check-out coordinates
- `status`: ENUM('checked_in', 'checked_out')
- `notes`: Additional notes
- `created_at` / `updated_at`: Timestamps

## Migration

Run the migration script to create the table:

```bash
node create_staff_check_in_out_table.js
```

## Use Cases

1. **Daily Attendance**: Track staff daily check-in and check-out times
2. **Location-Based Attendance**: Record check-in/out locations for remote work tracking
3. **Work Hours Calculation**: Automatic calculation of work duration
4. **Attendance Reports**: Generate reports with filtering and statistics
5. **Real-Time Monitoring**: See who's currently at work
6. **Compliance**: Maintain attendance records for payroll and compliance

## Notes

- Staff can only have one active check-in at a time
- Check-out requires an active check-in
- All endpoints verify that staff belongs to the admin's company
- Duration is calculated in hours, minutes, total minutes, and total seconds
- History records are sorted by check-in time (most recent first)
- Location fields are optional but recommended for accurate tracking

