# Email Tracking Testing Guide - Complete Reference

## Quick Start

### 1. Access Test Dashboard
```
http://localhost:8888/PowercozmoLaravel-2023/test-email-tracking
```

This will:
- ✅ Create a test email with real workflow
- ✅ Generate tracking links
- ✅ Provide comprehensive testing interface

---

## Testing Routes Available

### Main Test Routes

| Route | Purpose | Method |
|-------|---------|--------|
| `/test-email-tracking` | Main test dashboard | GET |
| `/test-email-preview/{id}` | Preview blade template email | GET |
| `/test-tracking/{type}/{id}` | Test specific tracking type | GET |
| `/test-email-tracking/stats/{id}` | View tracking statistics | GET |

### Tracking Routes (Production)

| Route | Purpose | Returns |
|-------|---------|---------|
| `/track/logo/{id}` | Logo image tracking | logo.png with tracking |
| `/track/footer/{id}` | Footer image tracking | footer-logo.png with tracking |
| `/track/open/{id}` | Hidden pixel tracking | 1x1 pixel.png with tracking |
| `/track/click/{id}` | Click tracking & redirect | Redirects to quotation page |
| `/track/download/{id}` | Download tracking & redirect | Redirects to download page |

---

## Test Workflow

### Step 1: Create Test Email

```bash
# Access test dashboard
http://localhost:8888/PowercozmoLaravel-2023/test-email-tracking
```

**What happens:**
1. Fetches first workflow from database
2. Creates test email record in `auto_quote_emails`
3. Generates tracking ID
4. Displays comprehensive test dashboard

### Step 2: Preview Email

Click **"Preview Email (Blade Template)"** to see:
- ✅ Professional email layout with logo
- ✅ Gradient header design
- ✅ Footer with tracking
- ✅ Company contact information
- ✅ Hidden tracking pixel
- ✅ Responsive design

### Step 3: Test Individual Tracking

Click each button to test:

**Logo Tracking:**
- URL: `/track/logo/{id}`
- Tracks: Opens via logo image
- Returns: Actual logo.png
- Source: `logo`

**Footer Tracking:**
- URL: `/track/footer/{id}`
- Tracks: Opens via footer image
- Returns: footer-logo.png or logo.png
- Source: `footer`

**Pixel Tracking:**
- URL: `/track/open/{id}`
- Tracks: Opens via hidden pixel
- Returns: 1x1 transparent pixel.png
- Source: `pixel`

**Click Tracking:**
- URL: `/track/click/{id}`
- Tracks: Link clicks
- Returns: Redirects to quotation page
- Logs: Click event in database

**Download Tracking:**
- URL: `/track/download/{id}`
- Tracks: Download attempts
- Returns: Redirects to download page
- Logs: Download event in database

### Step 4: View Statistics

Click **"View Tracking Statistics Dashboard"** to see:
- 📊 Aggregate counts (opens, clicks, downloads)
- 📈 Event breakdown by type
- 📜 Complete event history with timestamps
- 📋 Activity logs (if workflow exists)
- 🔄 Refresh and test again options

---

## Database Verification

### Check Email Record

```sql
SELECT * FROM auto_quote_emails WHERE id = {emailId};
```

**Expected Fields:**
- `id` - Email tracking ID
- `auto_quote_workflow_id` - Should NOT be null
- `quotation_number` - TEST-XXXXXX format
- `recipient_email` - test@example.com
- `open_count` - Increments with each open
- `click_count` - Increments with each click
- `download_count` - Increments with each download
- `first_opened_at` - Timestamp of first open
- `last_opened_at` - Timestamp of last open
- `sent_at` - Creation timestamp

### Check Tracking Events

```sql
SELECT * FROM auto_quote_email_events 
WHERE auto_quote_email_id = {emailId}
ORDER BY created_at DESC;
```

**Expected Fields:**
- `event_type` - 'open', 'click', or 'download'
- `ip_address` - Client IP (::1 for localhost)
- `user_agent` - Browser user agent string
- `referrer` - HTTP referrer (if available)
- `created_at` - Event timestamp

### Check Activity Logs

```sql
SELECT * FROM auto_quote_activities 
WHERE auto_quote_email_id = {emailId}
ORDER BY created_at DESC;
```

**Expected Fields:**
- `seller_id` - From workflow
- `module` - 'email'
- `operation` - 'opened', 'clicked', or 'downloaded'
- `performed_by` - 'buyer'
- `message` - Descriptive message
- `ip_address` - Client IP
- `user_agent` - Browser user agent

### Event Count by Type

```sql
SELECT event_type, COUNT(*) as count 
FROM auto_quote_email_events 
WHERE auto_quote_email_id = {emailId}
GROUP BY event_type;
```

---

## Testing Scenarios

### Scenario 1: Basic Tracking

**Objective:** Verify single tracking event

**Steps:**
1. Create test email
2. Click "Test Logo Tracking"
3. View statistics
4. Verify: open_count = 1, events table has 1 record

**Expected Result:**
```
✅ Open event recorded
✅ Aggregate count updated
✅ Activity log created
```

### Scenario 2: Multiple Tracking Points

**Objective:** Verify multiple tracking methods

**Steps:**
1. Create test email
2. Click "Test Logo Tracking"
3. Click "Test Footer Tracking"
4. Click "Test Pixel Tracking"
5. View statistics

**Expected Result:**
```
✅ open_count = 3
✅ 3 events in auto_quote_email_events
✅ 3 activities in auto_quote_activities
✅ All have different source metadata
```

### Scenario 3: Click and Download Tracking

**Objective:** Verify action tracking

**Steps:**
1. Create test email
2. Click "Test Click Tracking"
3. Click "Test Download Tracking"
4. View statistics

**Expected Result:**
```
✅ click_count = 1
✅ download_count = 1
✅ Events recorded with correct type
✅ Redirects work (may show 404 if quotation doesn't exist)
```

### Scenario 4: Blade Template Rendering

**Objective:** Verify email layout

**Steps:**
1. Create test email
2. Click "Preview Email (Blade Template)"
3. Check browser

**Expected Result:**
```
✅ Logo loads from /track/logo/{id}
✅ Footer logo loads from /track/footer/{id}
✅ Hidden pixel present: <img src="/track/open/{id}" width="1" height="1">
✅ Professional layout with gradient header
✅ Company contact information displayed
✅ Email body content rendered
```

### Scenario 5: Error Handling

**Objective:** Verify graceful error handling

**Steps:**
1. Access invalid email ID: `/track/open/99999`
2. Check logs: `storage/logs/laravel.log`

**Expected Result:**
```
✅ Returns pixel.png (doesn't break)
✅ Error logged but doesn't crash
✅ No 500 errors
```

---

## Tracking URL Examples

### For Email ID: 12

**Logo Tracking:**
```
http://localhost:8888/PowercozmoLaravel-2023/track/logo/12
```

**Footer Tracking:**
```
http://localhost:8888/PowercozmoLaravel-2023/track/footer/12
```

**Pixel Tracking:**
```
http://localhost:8888/PowercozmoLaravel-2023/track/open/12
```

**Click Tracking:**
```
http://localhost:8888/PowercozmoLaravel-2023/track/click/12
```

**Download Tracking:**
```
http://localhost:8888/PowercozmoLaravel-2023/track/download/12
```

---

## Blade Template Testing

### Preview Test Email

```
http://localhost:8888/PowercozmoLaravel-2023/test-email-preview/12
```

### Manual Blade Test

Create a test route:

```php
Route::get('/test-blade-manual', function () {
    return view('emails.auto_quotation_email', [
        'emailBody' => '<h1>Test</h1><p>This is a test email body with <a href="{{quotation_url}}" class="button">View Quote</a></p>',
        'subject' => 'Test Subject',
        'trackingId' => 12,
        'recipientEmail' => 'test@example.com',
        'companyAddress' => '123 Test St, City, State',
        'companyPhone' => '+1 555-1234',
        'companyEmail' => 'test@company.com',
    ]);
});
```

---

## Troubleshooting

### Issue: Logo/Footer Not Loading

**Problem:** Images showing broken in email preview

**Solutions:**
1. Check file exists:
   ```bash
   ls -la public/frontend/images/logo.png
   ls -la public/frontend/images/footer-logo.png
   ```

2. Create test images if missing:
   ```bash
   # Copy existing logo or create placeholder
   cp public/frontend/images/existing-logo.png public/frontend/images/logo.png
   cp public/frontend/images/logo.png public/frontend/images/footer-logo.png
   ```

3. Verify URL accessible:
   ```
   http://localhost:8888/PowercozmoLaravel-2023/track/logo/1
   ```

### Issue: Tracking Not Recording

**Problem:** Events not appearing in database

**Solutions:**
1. Check database connection:
   ```php
   php artisan tinker
   >>> \DB::connection('crm')->getPdo();
   ```

2. Verify EmailTrackingService namespace:
   ```
   app/Service/AutoQuote/EmailTrackingService.php
   namespace: App\Service\AutoQuote
   ```

3. Check logs:
   ```bash
   tail -f storage/logs/laravel.log
   ```

4. Test direct method call:
   ```php
   app(\App\Service\AutoQuote\EmailTrackingService::class)->trackOpen(12);
   ```

### Issue: Workflow Not Found

**Problem:** "No workflow found in database"

**Solutions:**
1. Create a workflow:
   ```sql
   INSERT INTO auto_quote_workflows (seller_id, name, status, created_at, updated_at)
   VALUES (1, 'Test Workflow', 'active', NOW(), NOW());
   ```

2. Or use console:
   ```bash
   php artisan auto-quote:process --seller=1
   ```

### Issue: Blade Template Errors

**Problem:** Email not rendering correctly

**Solutions:**
1. Clear blade cache:
   ```bash
   php artisan view:clear
   ```

2. Check blade syntax:
   ```bash
   php artisan view:cache
   # Look for errors
   ```

3. Verify template exists:
   ```bash
   ls -la resources/views/emails/auto_quotation_email.blade.php
   ls -la resources/views/emails/layouts/auto_quotation.blade.php
   ```

---

## Advanced Testing

### Test with Actual Email

**Send test email via command line:**

```php
php artisan tinker

>>> use Illuminate\Support\Facades\Mail;
>>> Mail::send('emails.auto_quotation_email', [
...     'emailBody' => '<h1>Test</h1>',
...     'trackingId' => 12,
...     'recipientEmail' => 'your@email.com',
...     'subject' => 'Test',
...     'companyAddress' => 'Test Address',
... ], function ($message) {
...     $message->to('your@email.com')->subject('Test Email Tracking');
... });
```

**Then check:**
1. Email received
2. Images load correctly
3. Tracking URLs work
4. Database records created

### Load Testing

**Test multiple tracking events:**

```php
php artisan tinker

>>> $service = app(\App\Service\AutoQuote\EmailTrackingService::class);
>>> for ($i = 0; $i < 10; $i++) {
...     $service->trackOpen(12, ['source' => 'load_test_' . $i]);
... }
>>> 
>>> // Check results
>>> \DB::connection('crm')->table('auto_quote_email_events')
...     ->where('auto_quote_email_id', 12)->count();
```

---

## Production Checklist

Before deploying to production:

- [ ] **Remove test routes:**
  - `/test-email-tracking`
  - `/test-email-preview/{id}`
  - `/test-tracking/{type}/{id}`
  - `/test-email-tracking/stats/{id}`

- [ ] **Upload real images:**
  - `public/frontend/images/logo.png`
  - `public/frontend/images/footer-logo.png`

- [ ] **Configure email settings:**
  - Company address
  - Company phone
  - Company email

- [ ] **Test with real email addresses:**
  - Send to Gmail, Outlook, Yahoo
  - Verify images load
  - Check tracking works

- [ ] **Monitor logs:**
  - Check for tracking errors
  - Verify no 500 errors
  - Review activity logs

- [ ] **Database indexes:**
  ```sql
  CREATE INDEX idx_email_events_email_id 
  ON auto_quote_email_events(auto_quote_email_id);
  
  CREATE INDEX idx_email_events_type 
  ON auto_quote_email_events(event_type);
  ```

---

## Summary

### Test Dashboard Features

✅ **Comprehensive Testing Interface**
- Professional UI with color-coded sections
- One-click testing for all tracking methods
- Real-time statistics dashboard
- Database query examples

✅ **Blade Template Preview**
- See actual email layout
- Verify tracking embedded correctly
- Check responsive design

✅ **Individual Tracking Tests**
- Logo tracking (primary)
- Footer tracking (secondary)
- Pixel tracking (fallback)
- Click tracking (actions)
- Download tracking (actions)

✅ **Statistics Dashboard**
- Aggregate counts display
- Event history table
- Activity logs (if workflow exists)
- Event breakdown by type
- Timestamp tracking

✅ **Error Handling**
- Graceful fallbacks
- Comprehensive logging
- User-friendly error messages

### Access URLs

**Main Dashboard:**
```
http://localhost:8888/PowercozmoLaravel-2023/test-email-tracking
```

**Direct Stats (after creating test):**
```
http://localhost:8888/PowercozmoLaravel-2023/test-email-tracking/stats/{emailId}
```

**Email Preview:**
```
http://localhost:8888/PowercozmoLaravel-2023/test-email-preview/{emailId}
```

This testing system provides everything needed to verify email tracking works correctly before production deployment!
