=== Form Attribution Tracking ===

Contributors: ryhowa, samsonovteamwork
Tags: attribution, tracking, referral, forms
Requires at least: 6.0
Tested up to: 6.8.3
Requires PHP: 8.0
Stable tag: 1.0.2
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

A WordPress plugin that automatically adds permanent hidden fields for referral source tracking to forms from Formidable Forms and Fluent Forms.

## Features

- **Automatic Referral Source Detection**: Intelligently detects visitor sources including:
  - UTM parameters (utm_source, utm_medium, utm_campaign)
  - Social media platforms (Facebook, Twitter, LinkedIn, etc.)
  - Search engines (Google, Bing, Yahoo, etc.)
  - Direct traffic
  - Custom referrers

- **Multiple Form Plugin Support**: 
  - Formidable Forms integration
  - Fluent Forms integration
  - Modular architecture for easy extension to other form plugins

- **Smart Persistence**: Uses cookies to maintain original referral source across multiple page visits

- **Auto-Integration**: Automatically adds referral source fields to new forms

- **Flexible Configuration**: Customizable field names, cookie duration, and debug options

## Installation

1. Upload the plugin files to `/wp-content/plugins/form-attribution-tracking/`
2. Run `composer install --no-dev` in the plugin directory
3. Activate the plugin through the WordPress admin panel
4. Configure settings at **Settings > Form Referral Source**

## Requirements

- WordPress 6.0 or higher
- PHP 8.0 or higher
- At least one supported form plugin:
  - Formidable Forms
  - Fluent Forms

## Usage

### Automatic Setup
The plugin automatically adds referral source fields to new forms when enabled in settings.

### Manual Setup
1. Go to **Settings > Form Referral Source**
2. Use the "Integrations" tab to add referral source fields to all existing forms
3. Use the "Forms" tab to check which forms have referral source fields

### JavaScript API
The plugin exposes a JavaScript API for advanced usage:

```javascript
// Get the current referral source
const source = getReferralSource();

// Manually populate form fields
populateFormFields();

// Access the full API
const api = window.FormAttributionTracking;
api.getReferralSource();
api.populateFormFields();
```

## Configuration

### Settings Options

- **Auto-add to new forms**: Automatically add referral source fields to newly created forms
- **Field Name**: Customize the name used for referral source fields
- **Cookie Duration**: How long to store referral source in visitor cookies (1-365 days)
- **Debug Mode**: Enable debug logging in browser console

### Source Detection Logic

1. **UTM Parameters** (highest priority): utm_source, utm_medium, utm_campaign
2. **Stored Cookie**: Previously detected referral source
3. **HTTP Referrer**: Parsed and categorized external referrers
4. **Direct Traffic**: When no referrer is available

### Known Source Categories

The plugin automatically categorizes referrers from popular platforms:

- **google**: Google search engines
- **facebook**: Facebook and Facebook Messenger
- **twitter**: Twitter/X
- **linkedin**: LinkedIn
- **youtube**: YouTube
- **instagram**: Instagram
- **reddit**: Reddit
- And many more...

## Development

### Architecture

The plugin uses a modular architecture with:

- **Contracts**: Interfaces defining integration requirements
- **Abstracts**: Base classes with common functionality
- **Integrations**: Specific implementations for each form plugin
- **Plugin**: Main orchestration class

### Adding New Form Plugin Support

1. Create a new integration class extending `AbstractFormIntegration`
2. Implement the required interface methods
3. Register the integration in the main Plugin class

Example:

```php
<?php

namespace FormAttributionTracking\Integrations;

use FormAttributionTracking\Abstracts\AbstractFormIntegration;

class CustomFormIntegration extends AbstractFormIntegration
{
    public function isAvailable(): bool {
        return class_exists('CustomFormPlugin');
    }
    
    public function getName(): string {
        return 'Custom Form Plugin';
    }
    
    // Implement other required methods...
}
```

### Hooks and Filters

The plugin provides several hooks for customization:

```php
// Modify available integrations
add_filter('attribution_tracking_integrations', function($integrations) {
    $integrations['Custom'] = new CustomFormIntegration();
    return $integrations;
});

// React to integration initialization
add_action('attribution_tracking_integration_initialized', function($integration_name) {
    // Custom logic when integration is initialized
});
```

## JavaScript Events

The plugin triggers custom events for integration with other scripts:

```javascript
// Listen for referral source population
window.addEventListener('referralSourcePopulated', function(event) {
    console.log('Referral source populated:', event.detail.source);
    console.log('Fields populated:', event.detail.fieldsCount);
});
```

## Troubleshooting

### Enable Debug Mode
1. Go to **Settings > Form Referral Source**
2. Enable "Debug Mode"
3. Check browser console for detailed logging

### Common Issues

**Referral source not being captured:**
- Check that JavaScript is enabled
- Verify the field name matches plugin settings
- Ensure cookies are allowed

**Fields not being populated:**
- Check form HTML for correct field selectors
- Verify timing of form rendering vs. script execution
- Enable debug mode for detailed logging

**Integration not working:**
- Ensure the form plugin is active and compatible
- Check WordPress error logs for PHP errors
- Verify plugin dependencies are met

## Support

For support, feature requests, or bug reports, please create an issue in the plugin repository or contact the plugin author.

## License

This plugin is licensed under the GPL v2 or later.

## Changelog

### 1.0.2
- Verified compatibility with the latest WordPress core release.
- Updated plugin metadata (`Tested up to`) to reflect successful testing on the newest WordPress version.
- Minor internal improvements to maintain stability with future WordPress updates.

### 1.0.1
- Fixed a fatal error occurring on Fluent Forms submissions when fallback attribution data was processed as a string instead of an array.
- Improved validation and safety checks for referral source population.
- Enhanced compatibility with Fluent Forms to prevent incorrect data handling.


### 1.0.0
- Initial release
- Formidable Forms integration
- Fluent Forms integration
- Modern PHP 8+ architecture
- Comprehensive admin interface
- Enhanced JavaScript tracking
