# GetAddress.io Autocomplete - Setup Guide

## Quick Start

### 1. Install the Module

```bash
# From your Magento root directory, install via composer
composer require portalpeople/magento-getaddress-autocomplete

# Enable the module
php bin/magento module:enable PortalPeople_GetAddressAutocomplete

# Run setup upgrade
php bin/magento setup:upgrade

# Clear caches
php bin/magento cache:clean
```

### 2. Get Your API Key

1. Visit [https://getaddress.io](https://getaddress.io)
2. Sign up for a free account
3. Confirm your email
4. Generate an API key from your account dashboard
5. Copy the API key

### 3. Configure in Magento

#### Via Admin Panel

1. Log in to your Magento Admin
2. Navigate to: **Stores** → **Configuration** → **Sales** → **Checkout**
3. Look for **Address Autocomplete** section
4. Enable the module
5. Paste your API key
6. Save configuration
7. Clear cache again

#### Via Command Line (if config table exists)

```bash
# First, ensure the configuration section exists in your system
php bin/magento config:set checkout/getaddress_autocomplete/enabled 1
php bin/magento config:set checkout/getaddress_autocomplete/api_key "YOUR_API_KEY_HERE"
php bin/magento cache:clean
```

### 4. Verify Installation

1. Go to checkout page
2. You should see "Find Address" field instead of standard address fields
3. Try searching for a postcode (e.g., "SW1A 2AA")
4. Verify suggestions appear

## Architecture Overview

### Module Structure

```
magento-getaddress-autocomplete/
├── src/
│   ├── Api/                              # Contract interfaces
│   │   └── AddressAutocompleteInterface.php
│   ├── Model/                            # Business logic
│   │   └── AddressAutocompleteManagement.php
│   ├── etc/                              # Configuration
│   │   ├── module.xml
│   │   ├── di.xml
│   │   ├── extension_attributes.xml
│   │   └── frontend/
│   │       └── di.xml
│   ├── registration.php
│   └── view/
│       └── frontend/
│           ├── requirejs-config.js
│           ├── layout/
│           │   └── checkout_index_index.xml
│           └── web/
│               ├── js/
│               │   ├── view/
│               │   │   └── address-autocomplete.js       (Main component)
│               │   └── action/
│               │       └── set-shipping-information-mixin.js
│               ├── template/
│               │   └── address-autocomplete.html         (UI template)
│               └── css/
│                   └── address-autocomplete.css          (Styling)
├── composer.json
├── README.md
├── LICENSE
└── SETUP_GUIDE.md                        (This file)
```

## How It Works

### Frontend Flow

1. **User sees autocomplete field** on checkout page
2. **User types address or postcode** in search field
3. **Component calls API endpoint** `/V1/getaddress/address/search`
4. **API queries getAddress.io service** with the search term
5. **Addresses returned in dropdown** for selection
6. **User selects address** from dropdown
7. **Address fields auto-populate** in quote
8. **Address data saved** via `/V1/getaddress/address/save` endpoint

### Backend Flow

1. **GetAddress.io API Integration** in `AddressAutocompleteManagement.php`
   - Makes HTTP requests to getAddress.io
   - Handles API authentication
   - Parses and returns address data

2. **Quote Management**
   - Saves address to quote shipping address
   - Stores extension attributes (postcode, validation status, etc.)
   - Persists data to database

3. **Error Handling**
   - Validates API response
   - Logs errors for debugging
   - Returns user-friendly error messages

## Configuration Details

### API Endpoints

The module exposes these REST API endpoints:

**Search Addresses**
```
POST /V1/getaddress/address/search
Content-Type: application/json

{
    "search_term": "SW1A 2AA"
}
```

Response:
```json
{
    "success": true,
    "addresses": [
        {
            "address": "10 DOWNING STREET, London",
            "postcode": "SW1A 2AA",
            "Label": "10 DOWNING STREET, LONDON",
            "AddressId": 12345
        }
    ]
}
```

**Get Address Details**
```
GET /V1/getaddress/address/details
Content-Type: application/json

{
    "address_id": "12345"
}
```

**Save Address to Quote**
```
POST /V1/getaddress/address/save
Content-Type: application/json

{
    "postcode": "SW1A 2AA",
    "udprn": 12345,
    "organisation": "Cabinet Office",
    "building": "10 Downing Street",
    "street": "Downing Street",
    "city": "London",
    "county": ""
}
```

## Customization

### Changing the UI

Edit `src/view/frontend/web/template/address-autocomplete.html`:
- Modify form fields
- Change button labels
- Adjust layout structure

### Styling

Edit `src/view/frontend/web/css/address-autocomplete.css`:
- Change colors
- Adjust spacing
- Modify responsive breakpoints

### JavaScript Behavior

Edit `src/view/frontend/web/js/view/address-autocomplete.js`:
- Change search debounce timing
- Modify address selection behavior
- Add custom validation

## Troubleshooting

### Module Not Showing on Checkout

1. **Check module is enabled**
   ```bash
   php bin/magento module:status | grep GetAddress
   ```
   Should show: `PortalPeople_GetAddressAutocomplete`

2. **Clear all caches**
   ```bash
   php bin/magento cache:clean
   ```

3. **Check configuration**
   - Verify API key is set in admin
   - Check "Enabled" is set to "Yes"

4. **Check browser console**
   - Press F12 in browser
   - Look for JavaScript errors
   - Check Network tab for failed requests

### "No addresses found" / API Errors

1. **Verify API key**
   - Log in to getAddress.io account
   - Check API key is active
   - Verify key has quota remaining

2. **Test with postcode**
   - Try searching with UK postcode instead of address
   - Example postcodes: "SW1A 2AA", "B1 1AA", "W1A 1AA"

3. **Check network connectivity**
   - Verify server can reach api.getaddress.io
   - Check firewall rules
   - Test with curl:
   ```bash
   curl -X GET "https://api.getaddress.io/find/SW1A%202AA?api-key=YOUR_API_KEY"
   ```

### JavaScript Not Loading

1. **Run static files generation**
   ```bash
   php bin/magento setup:static-content:deploy
   ```

2. **Check RequireJS config**
   - Frontend layout may need "Flush Magento Static Files"
   - Clear browser cache

3. **Check layout XML**
   - Verify `checkout_index_index.xml` is being loaded
   - Check module dependencies in `module.xml`

### Address Not Populating to Quote

1. **Check quote extension attributes**
   - Verify `extension_attributes.xml` is loaded
   - Check database has proper fields

2. **Check API endpoints response**
   - Monitor Network tab in browser DevTools
   - Look for `/V1/getaddress/` requests
   - Check response status and data

3. **Check logs**
   ```bash
   tail -f var/log/system.log
   ```

## Development

### Enable Debug Mode

Edit `.env` or `app/etc/env.php`:
```php
'MAGE_MODE' => 'developer',
```

### Monitor Logs

```bash
# Watch system log
tail -f var/log/system.log

# Watch for API errors
grep -i getaddress var/log/system.log
```

### Test API Manually

Use Postman or cURL to test endpoints:
```bash
# Test search
curl -X POST "http://your-magento/V1/getaddress/address/search" \
  -H "Content-Type: application/json" \
  -d '{"search_term":"SW1A 2AA"}'
```

## Performance Considerations

- **Debouncing**: Search is triggered on keyup (consider adding debounce)
- **API Limits**: getAddress.io has rate limits on free tier
- **Caching**: Address suggestions are not cached (to ensure accuracy)
- **Database**: Ensure extension attributes table exists before use

## Security Considerations

- **API Key**: Keep your API key secret in environment variables
- **Data Validation**: User input is validated before API calls
- **HTTPS**: Always use HTTPS for API communication
- **Permissions**: API endpoints are accessible to customers only

## Support & Resources

- **Documentation**: See README.md in plugin root
- **GetAddress.io Docs**: https://getaddress.io/documentation
- **Issues**: Contact support@portalpeople.uk

## Next Steps

After installation and configuration:

1. Test on staging environment first
2. Verify address data is saved to orders
3. Test on mobile devices
4. Monitor error logs for issues
5. Customize styling to match your theme
