# Business Finder Widget

A reusable autocomplete widget that integrates with Google Places API to help users find their business listings.

## Features

- 🔍 Real-time business search via Google Places API
- 📍 Location-aware suggestions (city/state filtering)
- ⭐ Displays business ratings and review counts
- 🎨 Fully customizable and styled
- 📱 Mobile responsive
- ⚡ Debounced API calls for performance
- 🔒 Secure API key handling via backend endpoint
- 🚫 Automatically disables browser autocomplete to prevent conflicts
- 🆔 Captures Google Place ID for downstream processing

## Installation

### 1. Copy Files to Your Project

```
/api/find_business.php          # Backend API endpoint
/js/business-finder-widget.js   # JavaScript widget
/css/business-finder-widget.css # Widget styles
```

### 2. Add Google Places API Key

In your `config/config.php`, add:

```php
define('GOOGLE_PLACES_API_KEY', 'your-api-key-here');
```

### 3. Include Files in Your HTML

```html
<!-- In <head> -->
<link href="css/business-finder-widget.css" rel="stylesheet">

<!-- Before </body> -->
<script src="js/business-finder-widget.js"></script>
```

## Basic Usage

### HTML

```html
<form id="myForm">
    <div class="form-group">
        <label for="business_name">Business Name *</label>
        <input type="text" id="business_name" name="business_name" required>
    </div>
    
    <div class="form-group">
        <label for="city">City</label>
        <input type="text" id="city" name="city">
    </div>
    
    <div class="form-group">
        <label for="state">State</label>
        <input type="text" id="state" name="state" maxlength="2">
    </div>
</form>
```

### JavaScript

```javascript
const businessFinder = new BusinessFinder({
    inputId: 'business_name',
    apiEndpoint: 'api/find_business.php',
    cityFieldId: 'city',
    stateFieldId: 'state',
    serviceType: 'hvac',  // Optional: pre-filter by service type
    onSelect: function(business) {
        console.log('Selected:', business);
    }
});
```

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `inputId` | string | 'business_name' | ID of the input field |
| `apiEndpoint` | string | '/api/find_business.php' | Backend API endpoint |
| `cityFieldId` | string | null | ID of city field (optional) |
| `stateFieldId` | string | null | ID of state field (optional) |
| `serviceType` | string | '' | Service type filter (e.g., 'hvac', 'plumbing') |
| `minChars` | number | 2 | Minimum characters before search |
| `debounceDelay` | number | 300 | Delay in ms before API call |
| `onSelect` | function | null | Callback when business is selected |
| `placeholder` | string | 'Start typing...' | Input placeholder text |
| `showHelper` | boolean | true | Show helper text above input |

## Advanced Usage

### Custom Callback

```javascript
const finder = new BusinessFinder({
    inputId: 'business_name',
    apiEndpoint: 'api/find_business.php',
    onSelect: function(business) {
        // Store place_id for later use (most important)
        document.getElementById('place_id').value = business.place_id;
        
        // Access other business data if needed
        console.log('Business:', business.name);
        console.log('Rating:', business.rating);
        console.log('Reviews:', business.user_ratings_total);
        
        // Show success message
        showNotification('Business verified!');
    }
});
```

### Get Selected Business

```javascript
const selectedBusiness = businessFinder.getSelectedBusiness();

if (selectedBusiness) {
    console.log('Name:', selectedBusiness.name);
    console.log('Place ID:', selectedBusiness.place_id);
    console.log('Rating:', selectedBusiness.rating);
}
```

### Reset Widget

```javascript
businessFinder.reset();
```

## Business Object Structure

When a business is selected, the callback receives an object with:

```javascript
{
    name: "Smith's HVAC",
    address: "123 Main St, Charlotte, NC 28202, USA",
    place_id: "ChIJ...",
    city: "Charlotte",
    state: "NC",
    rating: 4.8,
    user_ratings_total: 127
}
```

**Note:** City and state parsing from Google Places API addresses is unreliable due to varying formats. The widget does NOT auto-fill these fields. Instead, focus on capturing the `place_id` which can be used with Google Places API to retrieve accurate, structured address data when needed.

## API Endpoint

The backend endpoint (`api/find_business.php`) accepts these GET parameters:

- `query` (required): Search query
- `city` (optional): Filter by city
- `state` (optional): Filter by state
- `service_type` (optional): Service type filter

Example request:
```
/api/find_business.php?query=Smith+HVAC&city=Charlotte&state=NC&service_type=hvac
```

## Styling

The widget includes pre-built styles but can be customized via CSS:

```css
/* Customize dropdown */
.bf-dropdown {
    border-radius: 15px;
    box-shadow: 0 5px 20px rgba(0,0,0,0.15);
}

/* Customize items */
.bf-item:hover {
    background: #f0f9ff;
}

/* Customize colors */
.bf-helper {
    background: #your-color;
    border-left-color: #your-color;
}
```

## Use Cases

### 1. Lead Capture Forms
Help prospects find their exact business name from Google.

### 2. Onboarding Flows
Speed up signup by auto-filling business details.

### 3. Directory Listings
Allow businesses to claim their listings with verified data.

### 4. Marketing Campaigns
Personalize campaigns using accurate business information.

## Browser Support

- Chrome/Edge (latest)
- Firefox (latest)
- Safari (latest)
- Mobile browsers

## Security Notes

- API key is stored server-side only
- CORS headers can be restricted in production
- Input is sanitized on both client and server
- Rate limiting should be implemented for production use

## Troubleshooting

### Dropdown not showing
1. Check console for JavaScript errors
2. Verify CSS file is loaded
3. Ensure parent `.form-group` exists

### No results returned
1. Verify Google Places API key is valid
2. Check API key has Places API enabled
3. Ensure billing is set up in Google Cloud Console

### Location not auto-filling
1. Verify `cityFieldId` and `stateFieldId` are correct
2. Check that city/state fields exist in form
3. Ensure address parsing logic matches your needs

## License

Proprietary - Loyal Fan Loop

## Support

For issues or questions, contact your development team.
