# GDPR Implementation Guide for HandL UTM Grabber Plugin

This documentation provides developers with the necessary information to implement GDPR compliance for the HandL UTM Grabber plugin.

## Overview

The HandL UTM Grabber plugin provides two main functions for GDPR compliance:
- `RunHandL()` - Starts tracking when consent is given
- `RemoveHandLCookies()` - Removes tracking cookies when consent is denied

## Core Functions

### RunHandL()
Initiates UTM tracking and cookie setting when user consent is obtained.

```javascript
function RunHandL() {
    // Sets up UTM tracking, cookies, and form field population
    // Only call this when user has given consent
}
```

### RemoveHandLCookies()
Removes all HandL tracking cookies when consent is denied.

```javascript
function RemoveHandLCookies() {
    console.log('Removing HandL cookies');
    handl_utm_all_params.forEach(param => {
        Cookies.remove(param, { path: '/', domain: getDomainName() });
    });
}
```

## Consent Detection Methods

The plugin supports multiple consent management platforms and methods:

### 1. Google Tag Manager (GTM) Consent Mode

```javascript
function getConsentStatus() {
    if (!window.dataLayer) {
        console.warn('dataLayer is not defined.');
        return null;
    }
    let consent = null;
    // Iterate through dataLayer in reverse to find the latest consent event
    for (let i = window.dataLayer.length - 1; i >= 0; i--) {
        if (window.dataLayer[i][0] === 'consent' && window.dataLayer[i][1] === 'update') {
            consent = window.dataLayer[i][2];
            break;
        } else if (typeof window.dataLayer[i] === 'object' && window.dataLayer[i].value && window.dataLayer[i].value.event && window.dataLayer[i].value.event.includes('consent')) {
            consent = window.dataLayer[i].value;
            break;
        }
    }
    return consent;
}

function isConsentDenied() {
    const consentStatus = getConsentStatus();
    return consentStatus && (consentStatus.ad_user_data === 'denied' && (consentStatus.analytics_storage === 'denied' || !consentStatus.analytics_storage));
}

function handleConsentStatus() {
    if (isConsentDenied()) {
        RemoveHandLCookies();
    } else {
        RunHandL();
    }
}
```

### 2. Borlabs Cookie

```javascript
// Check Borlabs cookie on page load
const borlabsCookie = Cookies.get('borlabs-cookie');
if (borlabsCookie) {
    try {
        const cookieData = JSON.parse(borlabsCookie);
        if (cookieData.consents.marketing.includes('handl-utm-grabber')) {
            console.log("handl-utm-grabber checked by Borlabs.. RunHandL...");
            RunHandL();
        } else {
            console.log("handl-utm-grabber not checked by Borlabs");
        }
    } catch (e) {
        console.error('Error parsing JSON:', e);
    }
}

// Listen for Borlabs consent changes
window.addEventListener('borlabs-cookie-consent-saved', () => {
    if (window.BorlabsCookie.Consents.hasConsent('handl-utm-grabber')) {
        RunHandL();
    }
});
```

### 3. Cookiebot

```javascript
window.addEventListener('CookiebotOnAccept', function (e) {
    if (Cookiebot.consent.marketing) {
        RunHandL();
    }
}, false);
```

### 4. Complianz

```javascript
document.addEventListener("cmplz_enable_category", function(consentData) {
    var category = consentData.detail.category;
    if (category === 'marketing') {
        RunHandL();
    }
});
```

### 5. Custom GDPR Implementation

For custom consent implementations, you can use the built-in GDPR notice:

```javascript
// Set consent cookie
Cookies.set("gdprConsent", 1); // 1 for accept, 0 for deny

// The plugin will automatically check this cookie and call appropriate functions
```

## Implementation Examples

### Basic Implementation

```javascript
// Check if consent is required
if (typeof handl_ajax.require_third_party_consent !== 'undefined' && handl_ajax.require_third_party_consent) {
    // Monitor dataLayer for consent changes
    if (!window.dataLayer) {
        window.dataLayer = [];
    }

    const originalPush = window.dataLayer.push;
    window.dataLayer.push = function(...args) {
        args.forEach(entry => {
            if (
                (Array.isArray(entry) && entry[0] === 'consent' && entry[1] === 'update')
                || (entry.event && entry.event.includes('consent'))
                || (entry.value && entry.value.event && entry.value.event.includes('consent'))
            ) {
                handleConsentStatus();
            }
        });
        return originalPush.apply(this, args);
    };
}
```

### Custom Consent Manager Integration

```javascript
// Example for a custom consent manager
function checkCustomConsent() {
    // Your consent checking logic here
    const hasConsent = yourConsentManager.hasMarketingConsent();
    
    if (hasConsent) {
        RunHandL();
    } else {
        RemoveHandLCookies();
    }
}

// Call on page load
checkCustomConsent();

// Listen for consent changes
yourConsentManager.onConsentChange(function(consent) {
    if (consent.marketing) {
        RunHandL();
    } else {
        RemoveHandLCookies();
    }
});
```

## Server-Side PHP Integration

The plugin also provides server-side consent checking:

```php
// Check if consent is given
function HandLCookieConsented() {
    $good2go = apply_filters('is_ok_to_capture_utms', array('good2go' => 1));
    return $good2go["good2go"];
}

// Use in your code
if (HandLCookieConsented()) {
    // User has given consent, proceed with tracking
    // Your tracking code here
}
```

## Configuration Options

### WordPress Admin Settings

1. **Enable GDPR**: Shows HandL's built-in consent notice
2. **Require Third-Party Consent**: Requires consent from third-party services (e.g., GTM) before tracking

### JavaScript Variables

- `handl_ajax.require_third_party_consent`: Boolean indicating if third-party consent is required
- `handl_utm_all_params`: Array of all UTM parameters that will be tracked
- `handl_utm_cookie_duration`: Cookie expiration settings

## Best Practices

1. **Always check consent before calling `RunHandL()`**
2. **Call `RemoveHandLCookies()` when consent is denied**
3. **Listen for consent changes and update accordingly**
4. **Test with different consent management platforms**
5. **Ensure your implementation works with the plugin's built-in GDPR features**

## Testing

To test your GDPR implementation:

1. Clear all cookies
2. Load the page without consent
3. Verify that `RunHandL()` is not called
4. Give consent through your consent manager
5. Verify that `RunHandL()` is called and cookies are set
6. Revoke consent
7. Verify that `RemoveHandLCookies()` is called and cookies are removed

## Troubleshooting

### Common Issues

1. **Consent not detected**: Ensure your consent manager is properly integrated and firing the correct events
2. **Cookies not removed**: Check that `getDomainName()` returns the correct domain
3. **Multiple consent managers**: Ensure only one consent manager is active to avoid conflicts

### Debug Mode

Enable console logging to debug consent issues:

```javascript
console.log('Consent status:', getConsentStatus());
console.log('Is consent denied:', isConsentDenied());
console.log('HandL cookies:', handl_utm_all_params);
```

## Support

For additional support or questions about GDPR implementation, refer to the plugin documentation or contact the development team.