# Patrol Setup Wizard - Complete Implementation Guide

## System Architecture

### 4-Step Wizard Flow

```
Step 1: Employee Selection
  ├─ Get from Dotnet System (API Integration)
  ├─ Get from Laravel System (Local Database)
  └─ Create New Employee

Step 2: Site Assignment
  ├─ Get Clients from Dotnet (via Employee Branch)
  ├─ Sync Dotnet Clients to Laravel
  ├─ Get Available Services (LocalClientServices)
  └─ Create EmployeeAssignment

Step 3: Schedule Creation
  ├─ Define Patrol Schedule (times, interval)
  ├─ Create Patrol Checkpoints
  ├─ Generate QR Codes for Checkpoints
  ├─ Create Time Slots
  └─ Attach Checkpoints to Schedule

Step 4: Geofencing Setup
  ├─ Create Geofence (radius/polygon)
  ├─ Set Geofence Restrictions
  └─ Assign to Service
```

## API Endpoints

### Base URL
```
/api/v1/admin/wizard
```

### Authentication
All endpoints require Sanctum authentication:
```
Authorization: Bearer {token}
```

### Step 1: Employee Management

#### Get Employees from Dotnet
```
GET /api/v1/admin/wizard/employees
```

**Response:**
```json
{
  "success": true,
  "message": "Employees retrieved successfully",
  "count": 5,
  "data": [
    {
      "id": 1,
      "code": "EMP001",
      "name": "John Doe",
      "phone": "9876543210",
      "mobile": "9876543210",
      "branch": "FWG0001-HYD",
      "client": "Acme Corp",
      "department": "Security",
      "designation": "Guard"
    }
  ]
}
```

#### Create New Employee
```
POST /api/v1/admin/wizard/employees
Content-Type: application/json

{
  "name": "Jane Smith",
  "email": "jane.smith@example.com",
  "phone": "9123456789",
  "mobile": "9123456789",
  "password": "secure_password_123"
}
```

### Step 2: Site Assignment

#### Get Clients from Dotnet
```
GET /api/v1/admin/wizard/clients?branch_code=FWG0001-HYD
```

**Response:**
```json
{
  "success": true,
  "message": "Clients retrieved and synced successfully",
  "count": 3,
  "synced": [
    {
      "dotnet_code": "CLI001",
      "laravel_id": 1,
      "name": "Acme Corp"
    }
  ],
  "data": [
    {
      "code": "CLI001",
      "name": "Acme Corp",
      "branch": "FWG0001-HYD",
      "address": "123 Main St, Hyderabad"
    }
  ]
}
```

#### Get Available Services
```
GET /api/v1/admin/wizard/services
```

**Response:**
```json
{
  "success": true,
  "message": "Services retrieved successfully",
  "data": [
    {
      "id": 1,
      "name": "Head Office Security",
      "client_id": 1,
      "client_name": "Acme Corp",
      "location": "Hyderabad, Telangana",
      "type": "patrolling"
    }
  ]
}
```

#### Assign Employee to Site
```
POST /api/v1/admin/wizard/assign-site
Content-Type: application/json

{
  "employee_id": 5,
  "service_id": 1,
  "start_date": "2026-06-04",
  "end_date": "2027-06-04"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Employee assigned to site successfully",
  "data": {
    "assignment_id": 10,
    "employee": {
      "id": 5,
      "name": "Jane Smith"
    },
    "service": {
      "id": 1,
      "name": "Head Office Security"
    },
    "client": {
      "id": 1,
      "name": "Acme Corp"
    }
  }
}
```

### Step 3: Schedule Creation

#### Get Checkpoints for Service
```
GET /api/v1/admin/wizard/services/{serviceId}/checkpoints
```

#### Get Existing Schedules
```
GET /api/v1/admin/wizard/services/{serviceId}/schedules
```

#### Create Patrol Schedule
```
POST /api/v1/admin/wizard/create-schedule
Content-Type: application/json

{
  "service_id": 1,
  "schedule_name": "Morning Patrol",
  "start_time": "08:00",
  "end_time": "16:00",
  "interval_hours": 2,
  "checkpoints": [
    {
      "name": "Main Gate",
      "lat": 17.3850,
      "lng": 78.4867
    },
    {
      "name": "Building A",
      "lat": 17.3855,
      "lng": 78.4870
    },
    {
      "name": "Building B",
      "lat": 17.3860,
      "lng": 78.4875
    }
  ]
}
```

**Response:**
```json
{
  "success": true,
  "message": "Patrol schedule created successfully",
  "data": {
    "schedule_id": 5,
    "schedule_name": "Morning Patrol",
    "checkpoints_created": 3,
    "start_time": "08:00",
    "end_time": "16:00"
  }
}
```

### Step 4: Geofencing

#### Get Geofences for Service
```
GET /api/v1/admin/wizard/services/{serviceId}/geofences
```

#### Create Geofence
```
POST /api/v1/admin/wizard/create-geofence
Content-Type: application/json

{
  "service_id": 1,
  "name": "Acme Corp Perimeter",
  "type": "radius",
  "latitude": 17.3850,
  "longitude": 78.4867,
  "radius": 500
}
```

**Response:**
```json
{
  "success": true,
  "message": "Geofence created successfully",
  "data": {
    "geofence_id": 3,
    "name": "Acme Corp Perimeter",
    "type": "radius",
    "coordinates": {
      "lat": 17.3850,
      "lng": 78.4867
    },
    "radius": 500
  }
}
```

### Complete Setup (All Steps)

#### Complete Patrol Setup
```
POST /api/v1/admin/wizard/complete
Content-Type: application/json

{
  "employee_id": 5,
  "service_id": 1,
  "schedule": {
    "start_time": "08:00",
    "end_time": "16:00"
  },
  "geofence": {
    "type": "radius",
    "latitude": 17.3850,
    "longitude": 78.4867,
    "radius": 500
  }
}
```

## Database Models

### Key Relationships

```
Employee (User)
  ├─ EmployeeAssignment
  │   ├─ Client
  │   └─ ClientService
  │       ├─ PatrolSchedule
  │       │   ├─ PatrolCheckpoint
  │       │   │   ├─ CheckpointQRCode
  │       │   │   └─ PatrolTimeSlot
  │       │   └─ PatrolViolation
  │       └─ Geofence
  │           ├─ GeofenceLog
  │           └─ GeofenceViolation
```

### PatrolSchedule
```php
{
  id,
  service_id (FK → ClientService),
  schedule_name,
  start_time,     // 08:00
  end_time,       // 16:00
  interval_hours, // 2
  is_active,
  created_at,
  updated_at
}
```

### PatrolCheckpoint
```php
{
  id,
  service_id (FK → ClientService),
  checkpoint_name,   // "Main Gate"
  checkpoint_code,   // "CP001"
  latitude,
  longitude,
  order_sequence,
  is_active,
  created_at,
  updated_at
}
```

### CheckpointQRCode
```php
{
  id,
  checkpoint_id (FK → PatrolCheckpoint),
  qr_code,          // JSON with signature
  qr_code_path,
  is_active,
  generated_at,
  expires_at,
  created_at,
  updated_at
}
```

### Geofence
```php
{
  id,
  service_id (FK → ClientService),
  name,
  geofence_type,  // "radius|polygon|rectangle"
  coordinates,    // JSON {"lat": 17.3850, "lng": 78.4867}
  radius,         // For radius type
  is_active,
  created_at,
  updated_at
}
```

## Service Classes

### PatrolWizardService
Location: `app/Services/PatrolWizardService.php`

**Methods:**
- `getEmployeesFromDotNet()` - Fetch employees from dotnet API
- `getClientsFromDotNet($branchCode)` - Fetch clients by branch
- `syncClientsFromDotNet($dotnetClients)` - Sync clients to Laravel
- `getAvailableServices()` - Get all active services
- `getCheckpointsForService($serviceId)` - Get checkpoints
- `getSchedulesForService($serviceId)` - Get schedules
- `getGeofencesForService($serviceId)` - Get geofences
- `validatePatrolAssignment(...)` - Validate assignment data

### PatrolSetupService
Location: `app/Services/PatrolSetupService.php`

**Methods:**
- `setupPatrolForLocation(...)` - Complete patrol setup
- `createCheckpoints(...)` - Create multiple checkpoints
- `createCheckpoint(...)` - Create single checkpoint
- `addCheckpointToSchedule(...)` - Add checkpoint to schedule
- `createSchedule(...)` - Create patrol schedule
- `createTimeSlots(...)` - Create time slots

## Configuration

### Environment Variables
```env
DOTNET_API_URL=http://localhost:5000/api
DOTNET_API_TIMEOUT=30
```

### Services Configuration
File: `config/services.php`
```php
'dotnet' => [
    'api_url' => env('DOTNET_API_URL', 'http://localhost:5000/api'),
    'timeout' => env('DOTNET_API_TIMEOUT', 30),
]
```

## Error Handling

All API endpoints return standardized JSON responses:

### Success Response
```json
{
  "success": true,
  "message": "Operation completed successfully",
  "data": { }
}
```

### Error Response
```json
{
  "success": false,
  "message": "Error description",
  "errors": { }
}
```

## Workflow Examples

### Complete Flow: Select Dotnet Employee → Sync Client → Create Schedule → Setup Geofence

```bash
# Step 1: Get employees from dotnet
curl -X GET "http://localhost:8000/api/v1/admin/wizard/employees" \
  -H "Authorization: Bearer {token}"

# Step 2: Get clients for employee's branch
curl -X GET "http://localhost:8000/api/v1/admin/wizard/clients?branch_code=FWG0001-HYD" \
  -H "Authorization: Bearer {token}"

# Step 3: Assign employee to service
curl -X POST "http://localhost:8000/api/v1/admin/wizard/assign-site" \
  -H "Authorization: Bearer {token}" \
  -H "Content-Type: application/json" \
  -d '{
    "employee_id": 5,
    "service_id": 1
  }'

# Step 4: Create schedule with checkpoints
curl -X POST "http://localhost:8000/api/v1/admin/wizard/create-schedule" \
  -H "Authorization: Bearer {token}" \
  -H "Content-Type: application/json" \
  -d '{
    "service_id": 1,
    "start_time": "08:00",
    "end_time": "16:00",
    "interval_hours": 2,
    "checkpoints": [...]
  }'

# Step 5: Setup geofence
curl -X POST "http://localhost:8000/api/v1/admin/wizard/create-geofence" \
  -H "Authorization: Bearer {token}" \
  -H "Content-Type: application/json" \
  -d '{
    "service_id": 1,
    "type": "radius",
    "latitude": 17.3850,
    "longitude": 78.4867,
    "radius": 500
  }'
```

## Testing Checklist

- [ ] Employees fetch from dotnet successfully
- [ ] Clients sync from dotnet to Laravel
- [ ] Employee assignment creates without duplicates
- [ ] Schedule creation with checkpoints validates times
- [ ] QR codes generate for all checkpoints
- [ ] Geofence creation with proper coordinates
- [ ] Complete setup endpoint works end-to-end
- [ ] Error handling for invalid data
- [ ] Transaction rollback on failures
- [ ] Validation of latitude/longitude ranges
- [ ] Client sync respects existing records

## Future Enhancements

1. **Batch Operations** - Create multiple assignments at once
2. **Scheduled Imports** - Automatic dotnet employee sync on schedule
3. **Advanced Geofencing** - Polygon and rectangle geofence support
4. **Checkpoint Validation** - Distance-based validation between checkpoints
5. **Multi-Service Assignment** - Assign employee to multiple services
6. **Schedule Recurrence** - Daily/weekly/monthly patrol patterns
7. **Mobile Integration** - Mobile app patrol checkin with QR scanning
8. **Real-time Monitoring** - Live patrol tracking with geofence monitoring
