# Patrol QR Scan API Documentation

## Overview
This API provides comprehensive QR code scanning functionality for patrol management, enabling employees to scan checkpoints, validate schedules, and maintain patrol logs through a mobile application.

## Base URL
```
/api/v1/employee
```

## Authentication
All endpoints require authentication using Laravel Sanctum. Include the token in the Authorization header:
```
Authorization: Bearer {token}
```

## Endpoints

### 1. Get Active Patrol Schedules
**GET** `/patrol/schedules`

Retrieves active patrol schedules for the authenticated employee for the current day.

**Response:**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "schedule_name": "Night Patrol - Building A",
            "client": {
                "id": 1,
                "name": "ABC Corporation"
            },
            "service": {
                "id": 1,
                "name": "Security Patrol",
                "type": "patrolling"
            },
            "location": {
                "id": 1,
                "name": "Main Building"
            },
            "shift_type": "night",
            "time_slots": [
                {
                    "id": 1,
                    "day_of_week": "monday",
                    "start_time": "22:00",
                    "end_time": "06:00",
                    "is_current": true
                }
            ],
            "checkpoints": [
                {
                    "id": 1,
                    "name": "Main Entrance",
                    "code": "ENT001",
                    "type": "entrance",
                    "latitude": 40.7128,
                    "longitude": -74.0060,
                    "required_time": "22:30",
                    "tolerance_minutes": 15,
                    "order_sequence": 1,
                    "instructions": "Check all doors and windows"
                }
            ],
            "status": "active"
        }
    ]
}
```

### 2. Get Checkpoint by QR Code
**GET** `/patrol/checkpoint/by-qr`

Retrieves checkpoint details by scanning a QR code.

**Parameters:**
- `qr_data` (string, required): JSON string from QR code

**Response:**
```json
{
    "success": true,
    "data": {
        "checkpoint": {
            "id": 1,
            "name": "Main Entrance",
            "code": "ENT001",
            "type": "entrance",
            "latitude": 40.7128,
            "longitude": -74.0060,
            "required_time": "22:30",
            "tolerance_minutes": 15,
            "instructions": "Check all doors and windows"
        },
        "service": {
            "id": 1,
            "name": "Security Patrol",
            "client": {
                "id": 1,
                "name": "ABC Corporation"
            }
        },
        "qr_code": {
            "id": 1,
            "generated_at": "2024-01-15T10:00:00Z",
            "expires_at": "2024-02-15T10:00:00Z"
        }
    }
}
```

### 3. Scan QR Code
**POST** `/patrol/scan`

Processes a QR code scan and creates patrol logs or violations.

**Parameters:**
- `qr_data` (string, required): JSON string from QR code
- `latitude` (decimal, required): Current GPS latitude
- `longitude` (decimal, required): Current GPS longitude
- `accuracy` (decimal, optional): GPS accuracy in meters
- `photos` (array, optional): Array of photo URLs
- `notes` (string, optional): Additional notes

**Success Response:**
```json
{
    "success": true,
    "message": "Patrol checkpoint scanned successfully",
    "data": {
        "scan_id": 123,
        "patrol_log_id": 456,
        "checkpoint": {
            "name": "Main Entrance",
            "scanned_at": "2024-01-15T22:32:00Z"
        },
        "schedule": {
            "name": "Night Patrol - Building A"
        },
        "status": "on_time",
        "deviation_minutes": 2
    }
}
```

**Error Response (Validation Failed):**
```json
{
    "success": false,
    "message": "Current time is outside scheduled patrol hours",
    "data": {
        "scan_id": 124,
        "violation_id": 78,
        "violation_type": "time_violation",
        "checkpoint": {
            "name": "Main Entrance",
            "scanned_at": "2024-01-15T22:32:00Z"
        }
    }
}
```

### 4. Get Today's Patrol History
**GET** `/patrol/history`

Retrieves the employee's complete patrol history for the current day.

**Response:**
```json
{
    "success": true,
    "data": {
        "summary": {
            "total_scans": 15,
            "successful_scans": 14,
            "failed_scans": 1,
            "completed_checkpoints": 14,
            "violations": 1,
            "on_time_rate": 92.86
        },
        "scans": [
            {
                "id": 123,
                "scan_time": "2024-01-15T22:32:00Z",
                "result": "success",
                "notes": null,
                "checkpoint": {
                    "id": 1,
                    "name": "Main Entrance",
                    "service": "Security Patrol",
                    "client": "ABC Corporation"
                },
                "location": {
                    "latitude": 40.7128,
                    "longitude": -74.0060,
                    "accuracy": 5.2
                },
                "photos": []
            }
        ],
        "logs": [
            {
                "id": 456,
                "check_in_time": "2024-01-15T22:32:00Z",
                "status": "on_time",
                "deviation_minutes": 2,
                "checkpoint": {
                    "id": 1,
                    "name": "Main Entrance",
                    "service": "Security Patrol",
                    "client": "ABC Corporation"
                },
                "schedule": {
                    "id": 1,
                    "name": "Night Patrol - Building A"
                },
                "time_slot": {
                    "id": 1,
                    "start_time": "22:00",
                    "end_time": "06:00"
                }
            }
        ],
        "violations": [
            {
                "id": 78,
                "violation_time": "2024-01-15T23:15:00Z",
                "violation_type": "time_violation",
                "notes": "Current time is outside scheduled patrol hours",
                "is_resolved": false,
                "checkpoint": {
                    "id": 2,
                    "name": "Emergency Exit",
                    "service": "Security Patrol",
                    "client": "ABC Corporation"
                }
            }
        ]
    }
}
```

### 5. Get Nearby Checkpoints
**GET** `/patrol/nearby`

Retrieves checkpoints within a specified radius of the current location.

**Parameters:**
- `latitude` (decimal, required): Current GPS latitude
- `longitude` (decimal, required): Current GPS longitude
- `radius` (integer, optional): Search radius in meters (default: 200, max: 1000)

**Response:**
```json
{
    "success": true,
    "data": {
        "checkpoints": [
            {
                "id": 1,
                "name": "Main Entrance",
                "code": "ENT001",
                "type": "entrance",
                "latitude": 40.7128,
                "longitude": -74.0060,
                "distance_meters": 15.5,
                "required_time": "22:30",
                "tolerance_minutes": 15,
                "instructions": "Check all doors and windows",
                "service": {
                    "id": 1,
                    "name": "Security Patrol",
                    "client": {
                        "id": 1,
                        "name": "ABC Corporation"
                    }
                }
            }
        ],
        "search_location": {
            "latitude": 40.7128,
            "longitude": -74.0060,
            "radius_meters": 200
        }
    }
}
```

## QR Code Data Format

QR codes contain JSON data with the following structure:
```json
{
    "type": "patrol_checkpoint",
    "checkpoint_id": 1,
    "service_id": 1,
    "client_id": 1,
    "generated_at": "2024-01-15T10:00:00.000Z",
    "signature": "sha256_hash_signature"
}
```

## Validation Rules

The API performs comprehensive validation:

1. **QR Code Validity**: Checks if QR code is active and not expired
2. **Employee Assignment**: Validates employee is assigned to the service
3. **Schedule Time Window**: Ensures scan is within scheduled patrol hours
4. **Geofence Verification**: Validates location proximity to checkpoint
5. **Contract Compliance**: Checks if client contract allows patrol operations

## Error Handling

Common error responses:

- **400 Bad Request**: Invalid QR code format or validation failure
- **401 Unauthorized**: Missing or invalid authentication token
- **404 Not Found**: QR code not found or expired
- **422 Unprocessable Entity**: Validation errors in request data
- **500 Internal Server Error**: Server-side processing errors

## Security Features

- QR code signature verification using SHA256
- Geofence validation with configurable tolerance
- Tenant-based data isolation
- Rate limiting on scan endpoints
- Comprehensive audit logging

## Integration Notes

1. **Mobile App Integration**: Designed for mobile applications with GPS capabilities
2. **Offline Support**: QR codes can be generated offline but require online validation
3. **Real-time Updates**: All scans are processed in real-time with immediate feedback
4. **Photo Support**: Optional photo attachments for visual verification
5. **Geolocation Accuracy**: GPS accuracy tracking for quality assurance
