# Huabao Device Service - Legacy Conversion

## Overview
This document describes the conversion of the legacy `get_huabao_devices` method from the old PHP application to a modern Laravel service.

## Files Created/Modified

### 1. **HuabaoDeviceService.php** (New)
- **Location**: `app/Services/HuabaoDeviceService.php`
- **Purpose**: Encapsulates all logic for retrieving and processing Huabao device data

#### Key Methods:
- `getHuabaoDevices($email, $ignitionFilter, $batteryFilter)`: Main method that retrieves devices for a user
- `searchXmlTag($xml, $tag)`: Parses XML tags from the device's 'other' field
- `manipulateTime($datetime, $format)`: Handles timezone adjustments using Carbon
- `getDeviceStatus($params)`: Determines device status (moving, idle, stopped, offline, etc.)
- `getVoltage($traccarDeviceId, $power)`: Calculates battery voltage and percentage
- `getAddressFromLatLng($lat, $lng)`: Reverse geocoding using Google Maps API

#### Features:
- Uses Laravel's DB facade with the 'remote' connection
- Implements proper dependency injection
- Uses Carbon for date/time manipulation
- Integrates with Google Maps Geocoding API for address lookup
- Supports filtering by ignition status and battery level

### 2. **EscooterController.php** (Modified)
- **Location**: `app/Http/Controllers/Modules/EscooterController.php`
- **Changes**:
  - Injected `HuabaoDeviceService` via constructor
  - Updated `index()` method to:
    - Get authenticated user's email
    - Accept query parameters for filters (`ignition`, `battery`)
    - Call the service to retrieve devices
    - Pass data to the view

## Usage

### Basic Usage
```php
// In controller
$devices = $this->huabaoDeviceService->getHuabaoDevices($email);
```

### With Filters
```php
// Filter by ignition status
$devices = $this->huabaoDeviceService->getHuabaoDevices($email, 'true', null);

// Filter by battery level
$devices = $this->huabaoDeviceService->getHuabaoDevices($email, null, 'danger');

// Both filters
$devices = $this->huabaoDeviceService->getHuabaoDevices($email, 'false', 'warning');
```

### URL Examples
```
# All devices
/escooter

# Only devices with ignition on
/escooter?ignition=true

# Only devices with low battery (red)
/escooter?battery=danger

# Only devices with warning battery (red or orange)
/escooter?battery=warning

# Devices with ignition off and low battery
/escooter?ignition=false&battery=danger
```

## Configuration Required

### Google Maps API Key
Add to your `.env` file:
```env
GOOGLE_MAPS_API_KEY=your_google_maps_api_key_here
```

### Remote Database Connection
Ensure your `.env` has the remote database credentials:
```env
REMOTE_DB_CONNECTION=mysql
REMOTE_DB_HOST=your_remote_host
REMOTE_DB_PORT=3306
REMOTE_DB_DATABASE=your_database_name
REMOTE_DB_USERNAME=your_username
REMOTE_DB_PASSWORD=your_password
```

## Data Structure

### Returned Device Array
Each device in the returned array contains:
```php
[
    'device_id' => int,              // Traccar device ID
    'name' => string,                // Device name
    'lastupdate' => string,          // Last update timestamp
    'groupid' => int,                // Group ID
    'sim_number' => string,          // SIM card number
    'pdatetime' => string,           // Position datetime
    'lat' => float,                  // Latitude
    'lng' => float,                  // Longitude
    'other' => string,               // XML data
    'speed' => string,               // Speed (formatted)
    'matricule' => null,             // License plate (reserved)
    'ww' => null,                    // Reserved
    'vin' => null,                   // VIN (reserved)
    'flotte' => null,                // Fleet (reserved)
    'status' => string,              // Device status
    'pdatetime_tfix' => string,      // Timezone-adjusted datetime
    'pdatetime_tfix_format' => string, // Formatted datetime
    'odometer' => int,               // Odometer reading (km)
    'batteryTension' => float,       // Battery voltage
    'batteryLevel' => int,           // Battery percentage
    'batteryColor' => string,        // 'red', 'orange', or 'green'
    'ignition' => bool,              // Ignition status
    'address' => string              // Reverse geocoded address
]
```

## Device Status Values
- `no_signal`: No GPS coordinates
- `offline`: Last update > 24 hours ago
- `moving`: Speed > 5 km/h
- `idle`: Ignition on, not moving
- `stopped`: Ignition off, not moving
- `unknown`: Unable to determine status

## Battery Color Codes
- `red`: Battery < 20%
- `orange`: Battery 20-49%
- `green`: Battery >= 50%

## Differences from Legacy Code

### Improvements:
1. **Modern Laravel Practices**: Uses dependency injection, facades, and service pattern
2. **Carbon for Dates**: Replaced manual date manipulation with Carbon
3. **HTTP Client**: Uses Laravel's HTTP client instead of custom GoogleApi class
4. **Type Hints**: Added proper type hints for better IDE support
5. **Documentation**: Added comprehensive PHPDoc comments
6. **Error Handling**: Improved try-catch blocks

### Maintained Functionality:
- All original filtering logic
- XML tag parsing
- Battery voltage calculation
- Device status determination
- Timezone adjustments
- Sorting by battery tension

## Testing Recommendations

1. **Test with different users**: Verify data isolation
2. **Test filters**: Ensure ignition and battery filters work correctly
3. **Test edge cases**: Empty results, missing data, invalid coordinates
4. **Test API integration**: Verify Google Maps API responses
5. **Performance**: Monitor query performance with large datasets

## Future Enhancements

1. **Caching**: Add Redis caching for address lookups
2. **Queue Jobs**: Move address geocoding to background jobs
3. **API Rate Limiting**: Implement rate limiting for Google Maps API
4. **Alternative Geocoding**: Add fallback to Nominatim or other services
5. **Unit Tests**: Create comprehensive test suite
6. **Batch Processing**: Optimize for large device lists
