# Client Service Module - Universal Service Management

## Overview

The updated Client Service module provides a clean, universal approach to managing client services across the FWG admin system. It has been refactored to support multiple service types (Patrol, Security, Cleaning, Maintenance) while maintaining a clean separation of concerns.

## Architecture

### Core Components

#### 1. **ClientService Model** (`app/Models/ClientService.php`)
The primary model representing a client service with universal properties and methods.

**Key Features:**
- Multi-tenant support
- Soft deletes
- Relationships to checkpoints, schedules, assignments, reports
- Operational status tracking
- Utility methods for common operations

**Key Methods:**
- `isActiveAndValid()` - Check if service is operational
- `canOperate()` - Validate service can function
- `getOperationalStatus()` - Get detailed status
- `hasCheckpoints()` - Check for associated checkpoints
- `hasActiveSchedules()` - Check for active schedules
- `getActiveCheckpointsCount()` - Count active checkpoints
- `getAssignedEmployeesCount()` - Count assigned employees

**Relationships:**
```php
- client() -> BelongsTo Client
- location() -> BelongsTo ClientLocation
- checkpoints() -> HasMany PatrolCheckpoint
- patrolSchedules() -> HasMany PatrolSchedule
- employeeAssignments() -> HasMany EmployeeAssignment
- patrolReports() -> HasMany PatrolReport
- qrCodes() -> HasMany CheckpointQRCode
- geofences() -> HasMany Geofence
```

#### 2. **ClientServiceManager** (`app/Services/ClientServiceManager.php`)
Universal service management service implementing `ServiceOperationsInterface`.

**Responsibilities:**
- Create, read, update, delete operations on services
- Service activation/deactivation with cascading effects
- Service validation and health checks
- Statistics and metrics collection
- Dependency tracking

**Key Methods:**
```php
createService(Client $client, array $data): ClientService
updateService(ClientService $service, array $data): ClientService
deleteService(ClientService $service): bool
activateService(ClientService $service): ClientService
deactivateService(ClientService $service): ClientService
getClientServices(Client $client, array $filters = []): Collection
validateService(ClientService $service, string $operation = 'use'): bool
getServiceStats(ClientService $service): array
getServicesStats(Client $client): Collection
hasDependencies(ClientService $service): bool
getDependencies(ClientService $service): array
```

#### 3. **ServiceFactory** (`app/Services/ServiceFactory.php`)
Factory for service type-specific handlers.

**Provides:**
- Type-specific handler resolution
- Service-type specific operations
- Configuration and capability detection
- Universal service type operations

**Available Service Types:**
- `patrol` - Patrol & Guard Services
- `security` - Security Services
- `cleaning` - Cleaning Services
- `maintenance` - Maintenance Services

**Key Methods:**
```php
ServiceFactory::getHandlerForType(string $serviceType): ServiceHandlerInterface
ServiceFactory::getHandler(ClientService $service): ServiceHandlerInterface
ServiceFactory::processServiceCreation(ClientService $service): void
ServiceFactory::processServiceActivation(ClientService $service): void
ServiceFactory::processServiceDeactivation(ClientService $service): void
ServiceFactory::getAvailableTypes(): array
ServiceFactory::getTypeConfiguration(string $serviceType): array
ServiceFactory::validateServiceData(string $serviceType, array $data): array
```

#### 4. **Service Handlers**
Specific implementations for each service type in `app/Services/Handlers/`.

**Available Handlers:**
- `GenericServiceHandler` - Base handler for unknown types
- `PatrolServiceHandler` - Patrol-specific operations
- `SecurityServiceHandler` - Security-specific operations
- `CleaningServiceHandler` - Cleaning-specific operations
- `MaintenanceServiceHandler` - Maintenance-specific operations

Each handler implements `ServiceHandlerInterface` and provides:
- Type-specific lifecycle management
- Requirements and capabilities definition
- Validation logic
- Configuration details

#### 5. **Interfaces**

**ServiceOperationsInterface** (`app/Contracts/ServiceOperationsInterface.php`)
Defines contract for universal service operations.

**ServiceHandlerInterface** (`app/Services/ServiceHandlerInterface.php`)
Defines contract for service-type specific handlers.

## Usage Examples

### Client Portal API Login

Use `POST /api/v1/client/auth/login` for client portal API authentication. Send
the login email (or registered phone number) and password as JSON:

```json
{
    "login": "client@example.com",
    "password": "your-password"
}
```

The account must have the `Client` role and an active client service linked to
it. Employee assignments are not required for client portal login. A successful
response includes a Sanctum bearer token, the linked client record, and the
active service's branch code and name. If the branch name is not set, the branch
code is returned as the name.

### Creating a Service

```php
$manager = new ClientServiceManager();

$service = $manager->createService($client, [
    'location_id' => $location->id,
    'service_name' => 'Morning Patrol',
    'service_type' => 'patrol',
    'zone_area' => 'Main Building',
    'description' => 'Morning patrol of main building',
    'is_active' => true,
]);
```

### Updating a Service

```php
$manager->updateService($service, [
    'service_name' => 'Morning Patrol - Updated',
    'description' => 'Updated description',
]);
```

### Activating/Deactivating Services

```php
// Activate
$manager->activateService($service);

// Deactivate (cascades to employee assignments)
$manager->deactivateService($service);
```

### Getting Service Statistics

```php
$stats = $manager->getServiceStats($service);
// Returns:
[
    'id' => 1,
    'name' => 'Morning Patrol',
    'type' => 'patrol',
    'location' => 'Main Building',
    'is_active' => true,
    'checkpoint_count' => 5,
    'active_checkpoint_count' => 5,
    'schedule_count' => 3,
    'active_schedule_count' => 2,
    'employee_assignment_count' => 4,
    'active_employee_count' => 3,
    'created_at' => '2026-01-08T10:00:00Z',
    'updated_at' => '2026-01-08T10:00:00Z',
]
```

### Getting Service Type Information

```php
// Get handler for a specific service type
$handler = ServiceFactory::getHandlerForType('patrol');

// Get type configuration
$config = ServiceFactory::getTypeConfiguration('patrol');
// Returns requirements, capabilities, etc.

// Get available service types
$types = ServiceFactory::getAvailableTypes();
// Returns ['patrol' => 'Patrol & Guard Services', ...]

// Validate data for a service type
$errors = ServiceFactory::validateServiceData('patrol', [
    'service_name' => 'New Patrol',
    'location_id' => null,
]);
```

### Checking Service Status

```php
$service->isActiveAndValid(); // bool
$service->canOperate(); // bool
$service->getOperationalStatus(); // string: 'operational', 'inactive', 'client_inactive', 'no_location'
```

### Checking Dependencies

```php
$manager->hasDependencies($service); // bool
$manager->getDependencies($service);
// Returns:
[
    'checkpoints' => 5,
    'schedules' => 3,
    'assignments' => 4,
]
```

## Service Type Configuration

### Patrol Service
- **Requires:** Location
- **Supports:** 
  - Geofencing
  - Checkpoints with QR codes
  - Patrol schedules with time slots
  - Time tracking
  - Reporting
- **Capabilities:** Tracking, QR scanning, scheduling, employee assignment

### Security Service
- **Requires:** Location, Employee assignment
- **Supports:**
  - Geofencing
  - Patrol scheduling
  - Incident logging
- **Capabilities:** Tracking, geofencing, scheduling, incident management

### Cleaning Service
- **Requires:** Location, Employee assignment
- **Supports:**
  - Task scheduling
  - Task tracking
  - Reporting
- **Capabilities:** Scheduling, task tracking, reporting

### Maintenance Service
- **Requires:** Location, Employee assignment
- **Supports:**
  - Task scheduling
  - Maintenance tracking
  - Reporting
- **Capabilities:** Scheduling, task tracking, maintenance logging

## Database Schema

### ClientService Table
```sql
- id (Primary Key)
- client_id (Foreign Key)
- location_id (Foreign Key)
- service_name (string)
- zone_area (string, nullable)
- service_type (enum: patrol, security, cleaning, maintenance)
- description (text, nullable)
- is_active (boolean)
- tenant_id (Foreign Key)
- created_at (timestamp)
- updated_at (timestamp)
- deleted_at (timestamp, soft delete)
```

## Scopes Available

```php
// Get services for a specific tenant
ClientService::byTenant($tenantId)

// Get only active services
ClientService::active()

// Get services by type
ClientService::byServiceType('patrol')
```

## Integration Points

### With PatrolSetupService
The `PatrolSetupService` continues to work with `ClientService` for patrol-specific setup operations like creating checkpoints and schedules.

### With Controllers
Controllers should use `ClientServiceManager` for generic operations and `ServiceFactory` for type-specific operations.

### With Database Migrations
Add to your migrations:
```php
Schema::table('client_services', function (Blueprint $table) {
    $table->enum('service_type', ['patrol', 'security', 'cleaning', 'maintenance'])->default('patrol');
});
```

## Migration from Old Approach

If you have existing code using direct `ClientService` model operations:

### Old Way (Direct)
```php
$service = ClientService::create($data);
```

### New Way (Using Manager)
```php
$manager = new ClientServiceManager();
$service = $manager->createService($client, $data);
```

**Benefits:**
- Centralized validation
- Consistent logging
- Proper error handling
- Type-specific processing
- Easier testing and debugging

## Best Practices

1. **Always use ClientServiceManager** for CRUD operations instead of direct model creation
2. **Validate service type** before operations using `ServiceFactory`
3. **Check operational status** before critical operations with `isActiveAndValid()`
4. **Handle deactivation carefully** as it cascades to assignments
5. **Log important operations** for audit trail
6. **Use filters** in `getClientServices()` to reduce dataset size
7. **Monitor dependencies** before deletion using `getDependencies()`

## Error Handling

All manager methods include try-catch with logging:
```php
try {
    $service = $manager->createService($client, $data);
} catch (\Exception $e) {
    Log::error('Failed to create service', [
        'client_id' => $client->id,
        'error' => $e->getMessage(),
    ]);
    // Handle error appropriately
}
```

## Future Enhancements

1. **Service Templates** - Pre-configured service types
2. **Service Versioning** - Track service configuration changes
3. **Service Metrics** - Performance and usage analytics
4. **Service Notifications** - Status change notifications
5. **Service Synchronization** - Multi-location coordination
6. **Custom Service Types** - User-defined service types

## Support

For issues or questions about the Client Service module, refer to:
- Model documentation in `ClientService` class
- Service documentation in `ClientServiceManager` class
- Handler documentation in respective handler classes
- Integration tests in `tests/` directory
