# Lead Capture Troubleshooting Guide


**Last Updated:** 2025-11-20

## Overview

This guide covers common issues, debugging methods, and solutions for the lead capture popup system.

## Common Issues

### Popup Doesn't Appear

**Symptoms:**
- Popup never shows, even after waiting/scrolling
- No JavaScript errors in console

**Possible Causes:**
1. Form was previously submitted (30-day block)
2. Popup already shown on this page
3. Triggers disabled or misconfigured
4. JavaScript not loaded

**Solutions:**

1. **Clear submission flags:**
```javascript
// In browser console
localStorage.removeItem('lead_capture_submitted');
localStorage.removeItem('lead_capture_submitted_expires');
sessionStorage.removeItem('lead_capture_submitted');
sessionStorage.removeItem('lead_capture_permanent');
sessionStorage.removeItem('lead_capture_shown');
```

2. **Check trigger status:**
```javascript
// In browser console
console.log('Has shown:', window.leadCaptureTriggers?.hasShown);
console.log('Triggers:', window.leadCaptureTriggers?.triggers);
console.log('Page priority:', window.leadCaptureTriggers?.getPagePriority());
```

3. **Manually trigger popup:**
```javascript
// In browser console
window.leadCapturePopup?.show('manual');
```

4. **Verify includes:**
```php
// Check both are present
<?php include '../components/lead-capture-popup.php'; ?>
<script src="/v2/js/lead-capture-triggers.js"></script>
```

### Form Submission Fails

**Symptoms:**
- Form submits but shows error
- Network request fails
- No data in HubSpot/Sheets

**Possible Causes:**
1. API endpoint not accessible
2. Validation errors
3. Network timeout
4. Server errors

**Solutions:**

1. **Check network tab:**
   - Open browser DevTools → Network
   - Submit form
   - Check `/v2/api/lead-capture.php` request
   - Look for error status (400, 500, etc.)

2. **Check API response:**
```javascript
// In browser console, check response
fetch('/v2/api/lead-capture.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        step: '1',
        name: 'Test',
        phone: '+49123456789'
    })
}).then(r => r.json()).then(console.log);
```

3. **Check server logs:**
```bash
# Check error logs
tail -f v2/logs/lead-capture.log
tail -f v2/logs/lead-capture-debug.log
```

4. **Test API endpoint:**
```bash
# Test API connectivity
curl -X POST http://localhost:8003/v2/api/lead-capture.php \
  -H "Content-Type: application/json" \
  -d '{"step":"1","name":"Test","phone":"+49123456789"}'
```

### HubSpot Sync Issues

**Symptoms:**
- Form submits successfully
- No contact in HubSpot
- Duplicate contacts created

**Possible Causes:**
1. Invalid API token
2. Invalid form GUID
3. Contact identification issues
4. API rate limits

**Solutions:**

1. **Test HubSpot connectivity:**
```
Visit: /v2/api/lead-capture.php?debug_hubspot=test
```

2. **Check API token:**
```php
// In lead-capture.php, verify token is set
define('HUBSPOT_API_TOKEN_LEAD_CAPTURE', 'pat-eu1-...');
```

3. **Check form GUID:**
```php
// Verify form GUID matches HubSpot form
define('ORDIO_HUBSPOT_LEAD_CAPTURE_FORM_GUID', '9f9d4e35-d8d9-4283-93b6-1a789e0a1281');
```

4. **Check logs for errors:**
```bash
# Look for HubSpot errors
grep -i "hubspot" v2/logs/lead-capture-debug.log | tail -20
```

5. **Verify contact identification:**
   - Check if temporary email pattern matches: `lead-{leadId}@temp.ordio.com`
   - Verify phone normalization works correctly
   - Check if contact exists before creating

### Google Sheets Sync Issues

**Symptoms:**
- Form submits successfully
- No row in Google Sheets
- Rows not updating

**Possible Causes:**
1. Invalid credentials
2. Spreadsheet permissions
3. API errors
4. Network issues

**Solutions:**

1. **Check credentials:**
```php
// Verify credentials file exists
$credentialsPath = __DIR__ . '/../config/google-sheets-credentials.json';
if (!file_exists($credentialsPath)) {
    // Uses embedded credentials as fallback
}
```

2. **Check spreadsheet ID:**
```php
// Verify spreadsheet ID matches
$spreadsheetId = '1gHzf0CcCACPPLo3Xb4aBcO9cguraVa7eeLyYZvqCBAk';
```

3. **Check service account permissions:**
   - Verify service account has edit access to spreadsheet
   - Check Google Cloud Console for service account status

4. **Check logs for errors:**
```bash
# Look for Google Sheets errors
grep -i "sheets" v2/logs/lead-capture-debug.log | tail -20
```

### Copy Doesn't Match Page

**Symptoms:**
- Popup shows default copy
- Copy doesn't match page type
- Copy shows for wrong page

**Possible Causes:**
1. URL pattern doesn't match
2. Pattern not in config
3. Quick lookup missing entry

**Solutions:**

1. **Check URL pattern:**
```php
// In browser console
console.log('Current URL:', window.location.pathname);
console.log('Current file:', '<?php echo basename($_SERVER["SCRIPT_FILENAME"]); ?>');
```

2. **Verify pattern exists:**
```php
// Check v2/data/lead_capture_copy.php
// Verify pattern exists and URLs match
```

3. **Add pattern if missing:**
   - See [Copy Management Guide](./COPY_MANAGEMENT.md)

4. **Add to quick lookup:**
   - See [Copy Management Guide](./COPY_MANAGEMENT.md)

### UTM Tracking Issues

**Symptoms:**
- UTM parameters not captured
- Lead source shows "Direct Traffic"
- HubSpot missing UTM data

**Possible Causes:**
1. UTM tracker not loaded
2. UTM data not passed to API
3. UTM validation failing

**Solutions:**

1. **Check UTM tracker:**
```javascript
// In browser console
console.log('UTM Tracker:', window.utmTracker);
console.log('UTM Data:', window.utmTracker?.getAllUTMData());
```

2. **Check UTM data in form submission:**
```javascript
// Monitor form submission
const originalFetch = window.fetch;
window.fetch = function(...args) {
    if (args[0].includes('lead-capture.php')) {
        console.log('Lead capture request:', args);
    }
    return originalFetch.apply(this, args);
};
```

3. **Verify UTM data in API:**
```bash
# Check logs for UTM data
grep -i "utm" v2/logs/lead-capture-debug.log | tail -20
```

4. **Test with UTM parameters:**
```
Visit: /page?utm_source=test&utm_medium=test&utm_campaign=test
```

### Session Management Issues

**Symptoms:**
- Popup shows multiple times
- Form can be submitted multiple times
- Session not persisting

**Possible Causes:**
1. Session storage cleared
2. Expiration logic not working
3. Page refresh detection failing

**Solutions:**

1. **Check session storage:**
```javascript
// In browser console
console.log('Session storage:', {
    shown: sessionStorage.getItem('lead_capture_shown'),
    submitted: sessionStorage.getItem('lead_capture_submitted'),
    page: sessionStorage.getItem('lead_capture_page')
});

console.log('Local storage:', {
    submitted: localStorage.getItem('lead_capture_submitted'),
    expires: localStorage.getItem('lead_capture_submitted_expires')
});
```

2. **Check expiration date:**
```javascript
// In browser console
const expires = localStorage.getItem('lead_capture_submitted_expires');
if (expires) {
    const now = new Date();
    const expiresDate = new Date(expires);
    console.log('Expires:', expiresDate);
    console.log('Now:', now);
    console.log('Expired:', now > expiresDate);
}
```

3. **Reset session:**
```javascript
// In browser console
window.resetLeadCapture();
```

## Debugging Methods

### Browser Console Helpers

```javascript
// Check popup status
window.leadCapturePopup?.isOpen();

// Check trigger status
window.leadCaptureTriggers?.hasShown;

// Manually show popup
window.leadCapturePopup?.show('manual');

// Reset all state
window.resetLeadCapture();

// Check copy detection
// (if debug function available)
debugLeadCaptureCopy();
```

### Server-Side Debugging

1. **Enable debug logging:**
```php
// Already enabled in lead-capture.php
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/lead-capture-debug.log');
```

2. **Check logs:**
```bash
# Real-time log monitoring
tail -f v2/logs/lead-capture-debug.log

# Search for specific errors
grep -i "error" v2/logs/lead-capture-debug.log

# Search for specific lead ID
grep "LC1234567890" v2/logs/lead-capture-debug.log
```

3. **Test API endpoint:**
```bash
# Test HubSpot connectivity
curl "http://localhost:8003/v2/api/lead-capture.php?debug_hubspot=test"
```

### Network Debugging

1. **Monitor network requests:**
   - Open DevTools → Network
   - Filter by "lead-capture"
   - Check request/response details

2. **Check request payload:**
```javascript
// In browser console
const originalFetch = window.fetch;
window.fetch = function(...args) {
    if (args[0].includes('lead-capture.php')) {
        console.log('Request URL:', args[0]);
        console.log('Request options:', args[1]);
        if (args[1]?.body) {
            console.log('Request body:', JSON.parse(args[1].body));
        }
    }
    return originalFetch.apply(this, args).then(response => {
        if (args[0].includes('lead-capture.php')) {
            response.clone().json().then(data => {
                console.log('Response:', data);
            });
        }
        return response;
    });
};
```

## Error Codes

### HTTP Status Codes

- **200:** Success
- **400:** Bad request (validation error)
- **500:** Server error

### API Response Codes

```json
{
    "success": true|false,
    "message": "User-friendly message",
    "error": "Error details (if success: false)",
    "data": {
        "lead_id": "LC1234567890",
        "hubspot_contact_id": "12345678",
        "sheets_updated": true,
        "hubspot_updated": true
    }
}
```

## Testing Methods

### Manual Testing

1. **Test form submission:**
   - Fill Step 1 (name, phone)
   - Submit and verify Step 2 appears
   - Fill Step 2 (email, notes, preference)
   - Submit and verify success state

2. **Test triggers:**
   - Wait for time trigger (30-60s)
   - Scroll for scroll trigger (25-40%)
   - Move mouse to top for exit intent

3. **Test error scenarios:**
   - Submit with invalid phone
   - Submit with invalid email
   - Disable network and submit

### Automated Testing

```javascript
// Test popup functionality
describe('Lead Capture Popup', () => {
    it('should show popup on trigger', () => {
        window.leadCapturePopup.show('manual');
        expect(window.leadCapturePopup.isOpen()).toBe(true);
    });
    
    it('should validate phone number', () => {
        const popup = new LeadCapturePopup();
        expect(popup.isValidPhoneNumber('+49123456789')).toBe(true);
        expect(popup.isValidPhoneNumber('invalid')).toBe(false);
    });
});
```

## Performance Debugging

### Check Load Times

```javascript
// In browser console
performance.getEntriesByType('resource')
    .filter(r => r.name.includes('lead-capture'))
    .forEach(r => console.log(r.name, r.duration + 'ms'));
```

### Check Memory Usage

```javascript
// In browser console
console.log('Memory:', performance.memory);
```

## Related Documentation

- [Architecture Overview](./ARCHITECTURE.md) - System architecture
- [Integration Guide](./INTEGRATION_GUIDE.md) - Adding popup to pages
- [Trigger Configuration](./TRIGGER_CONFIGURATION.md) - Trigger setup
- [Copy Management](./COPY_MANAGEMENT.md) - Copy configuration
- [Testing Checklist](./TESTING_CHECKLIST.md) - Testing procedures

