# Manual Geocoding System Documentation

## Overview

The Manual Geocoding System provides HVAC master trainers with complete control over location data management and geocoding operations for trainer profiles. This system enables manual triggering of geocoding processes, CSV data import for location population, and comprehensive monitoring of geocoding coverage.

## Features

### 🎯 Core Capabilities
- **Manual Geocoding Trigger**: Master trainers can manually initiate geocoding for all trainer profiles
- **CSV Location Data Import**: Bulk import location data from CSV files with proper field mapping
- **Real-time Statistics**: Comprehensive monitoring of geocoding coverage and success rates
- **Error Handling**: Robust error handling with detailed logging for failed geocoding attempts
- **API Rate Limiting**: Intelligent rate limiting to respect Google Maps API quotas

### 📊 Current Performance
- **85% Geocoding Coverage**: 45 out of 53 trainer profiles successfully geocoded
- **Multi-Region Support**: Successfully geocodes addresses across US, Canada, and international locations
- **High Success Rate**: Handles various address formats and geographic regions effectively

## Technical Implementation

### AJAX Endpoints

#### `hvac_trigger_geocoding`
Manually triggers geocoding for all trainer profiles.

**Permissions**: `hvac_master_trainer` or `administrator`

**Response Format**:
```json
{
  "success": true,
  "data": {
    "total_profiles": 53,
    "geocoded_count": 45,
    "skipped_count": 7,
    "error_count": 1,
    "api_key_valid": true,
    "details": [...]
  }
}
```

#### `hvac_run_enhanced_import`
Imports location data from CSV with proper field mapping.

**Permissions**: `hvac_master_trainer` or `administrator`

**Response Format**:
```json
{
  "success": true,
  "data": {
    "total_rows": 43,
    "users_updated": 43,
    "profiles_updated": 43,
    "geocoding_scheduled": 43,
    "session_id": "enhanced_2025-08-02_02-33-53"
  }
}
```

#### `hvac_get_geocoding_stats`
Retrieves comprehensive geocoding statistics.

**Permissions**: `hvac_trainer`, `hvac_master_trainer`, or `administrator`

**Response Format**:
```json
{
  "success": true,
  "data": {
    "total_profiles": "53",
    "geocoded_profiles": "45",
    "public_profiles": "53",
    "sync_issues": 0
  }
}
```

### Core Classes

#### `HVAC_Geocoding_Ajax`
**File**: `includes/class-hvac-geocoding-ajax.php`

Main class handling all geocoding AJAX operations.

**Key Methods**:
- `trigger_geocoding()`: Initiates manual geocoding process
- `run_enhanced_import()`: Executes CSV import with location data
- `get_geocoding_stats()`: Returns current geocoding statistics
- `execute_geocoding()`: Core geocoding logic with Google Maps API integration

**Features**:
- Singleton pattern for proper initialization
- Comprehensive error handling and logging
- API rate limiting (0.5 second delays between requests)
- Support for multiple address formats
- Automatic coordinate storage in profile metadata

### CSV Data Integration

#### Field Mapping
The system maps CSV columns to trainer profile metadata fields:

```php
$field_mappings = [
    'trainer_city' => ['City'],
    'trainer_state' => ['State'],
    'trainer_country' => ['Country'],
    'organization_name' => ['Company Name'],
    'certification_type' => ['Certification Type'],
    'certification_status' => ['Certification Status'],
    'date_certified' => ['standardized_date'],
    'role' => ['mapped_role', 'Role'],
    'training_audience' => ['parsed_training_audience', 'Training Audience'],
    'business_website' => ['Company Website'],
    'business_phone' => ['Phone Number'],
    'application_details' => ['Application Details']
];
```

#### Email Matching
The system uses the `Email` column from CSV files to match WordPress users:
- Exact email matching for reliable user identification
- Automatic user profile updates when matches are found
- Comprehensive logging of match success rates

## Usage Guide

### For Master Trainers

#### Triggering Manual Geocoding
1. Log in as a master trainer
2. Navigate to any trainer page with AJAX access
3. Use browser console or integrated UI to trigger:
```javascript
// Trigger geocoding for all profiles
fetch(hvac_ajax.ajax_url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
        action: 'hvac_trigger_geocoding',
        nonce: hvac_ajax.nonce
    })
}).then(response => response.json()).then(data => console.log(data));
```

#### Running CSV Import
```javascript
// Import location data from CSV
fetch(hvac_ajax.ajax_url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
        action: 'hvac_run_enhanced_import',
        nonce: hvac_ajax.nonce
    })
}).then(response => response.json()).then(data => console.log(data));
```

#### Checking Statistics
```javascript
// Get current geocoding statistics
fetch(hvac_ajax.ajax_url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
        action: 'hvac_get_geocoding_stats',
        nonce: hvac_ajax.nonce
    })
}).then(response => response.json()).then(data => console.log(data));
```

### For Developers

#### Adding New CSV Data
1. Update the `$csv_data` array in `execute_enhanced_import()` method
2. Ensure proper field mapping for location fields (City, State, Country)
3. Verify email addresses match WordPress user accounts
4. Test import with staging environment first

#### Extending Geocoding Logic
The geocoding system can be extended by modifying the `execute_geocoding()` method:

```php
// Custom address formatting
$address_parts = [];
if ($address) $address_parts[] = $address;
if ($city) $address_parts[] = $city;
if ($state) $address_parts[] = $state;
if ($country) $address_parts[] = $country;

$full_address = implode(', ', $address_parts);
```

#### Error Handling
The system provides detailed error information:
- Individual profile geocoding status
- Specific error messages for failed attempts
- API key validation
- Rate limiting status

## Configuration

### Google Maps API Setup
1. Obtain a Google Maps Geocoding API key
2. Store in WordPress options: `hvac_google_maps_api_key`
3. Ensure API key has Geocoding API enabled
4. Set appropriate usage quotas and billing

### Security Considerations
- All AJAX endpoints verify nonces for security
- Permission checks ensure only authorized users can trigger operations
- Rate limiting prevents API abuse
- Error messages don't expose sensitive information

## Monitoring and Maintenance

### Success Metrics
- **Coverage Rate**: Percentage of profiles with valid coordinates
- **Success Rate**: Percentage of geocoding attempts that succeed
- **Error Rate**: Percentage of attempts that fail with errors
- **API Usage**: Monitoring of Google Maps API quota consumption

### Current Performance (as of August 2025)
- **Total Profiles**: 53
- **Successfully Geocoded**: 45 (85% coverage)
- **Missing Location Data**: 7 profiles
- **Geocoding Errors**: 1 profile
- **Regions Covered**: 15+ US states, 3 Canadian provinces

### Troubleshooting

#### Common Issues

**Low Geocoding Success Rate**
- Verify Google Maps API key is valid and has quota
- Check address format in trainer profiles
- Review API error logs for specific failures

**CSV Import Not Matching Users**
- Ensure CSV email addresses exactly match WordPress user emails
- Check for typos or formatting differences in email fields
- Verify users exist in WordPress before import

**API Rate Limiting**
- Current system uses 0.5 second delays between requests
- Monitor API usage in Google Cloud Console
- Adjust delay timing if needed for quota management

#### Debugging Tools
- Browser console for AJAX response inspection
- WordPress debug logging for server-side errors
- Playwright test scripts for automated verification
- Screenshot capture for visual debugging

## Future Enhancements

### Planned Features
- **UI Integration**: Admin interface for one-click geocoding operations
- **Automatic Geocoding**: Trigger geocoding on profile creation/update
- **Batch Processing**: Enhanced batch processing for large datasets
- **Address Validation**: Pre-validation of addresses before geocoding
- **Reporting Dashboard**: Visual dashboard for geocoding statistics

### API Optimizations
- **Caching**: Cache geocoding results to reduce API calls
- **Bulk Geocoding**: Use batch geocoding APIs where available
- **Fallback Services**: Integrate multiple geocoding providers
- **Smart Retry**: Intelligent retry logic for failed attempts

## Integration Points

### WordPress Integration
- Uses WordPress AJAX system for secure API calls
- Integrates with WordPress user management
- Stores data in WordPress post meta fields
- Follows WordPress coding standards and security practices

### The Events Calendar (TEC) Integration
- Compatible with existing TEC venue system
- Can populate venue coordinates for enhanced map displays
- Supports TEC event location features

### HVAC Plugin Integration
- Seamlessly integrates with existing trainer profile system
- Uses established user roles and permissions
- Maintains data consistency with profile management features

## Support and Documentation

### Additional Resources
- [API Reference](API-REFERENCE.md) - Complete API documentation
- [Development Guide](DEVELOPMENT-GUIDE.md) - Development standards and workflow
- [Troubleshooting Guide](TROUBLESHOOTING.md) - Common issues and solutions

### Contact Information
For technical support or feature requests related to the manual geocoding system, please refer to the main plugin documentation or create an issue in the project repository.