# Email Tracking with Blade Templates - Implementation Guide

## Overview

The email tracking system now uses **Blade templates** with **visible tracking images** (logo and footer) instead of hidden tracking pixels. This approach is more reliable because:

1. **Higher delivery rate**: Email clients are more likely to load visible images (logos) than hidden tracking pixels
2. **Better user experience**: Professional email layout with company branding
3. **Multiple tracking points**: Logo (header) + Footer logo + Hidden pixel (fallback)
4. **Easier customization**: Use Blade templates for consistent branding

---

## Architecture

### Files Created/Modified

**Blade Templates:**
- `resources/views/emails/layouts/auto_quotation.blade.php` - Master email layout
- `resources/views/emails/auto_quotation_email.blade.php` - Email content wrapper

**Routes Added:**
- `/track/logo/{id}` - Tracks email open via logo image
- `/track/footer/{id}` - Tracks email open via footer image
- `/track/open/{id}` - Hidden pixel tracking (fallback)

**Service Updates:**
- `app/Services/AutoQuotation/Helpers/EmailTrigger.php` - Uses blade templates, passes tracking ID

---

## How It Works

### 1. Email Layout Structure

```
┌─────────────────────────────────┐
│  HEADER (Gradient Background)   │
│  ┌──────────────────────────┐  │
│  │  LOGO (Tracked Image)    │  │ ← Tracks via /track/logo/{id}
│  └──────────────────────────┘  │
├─────────────────────────────────┤
│                                 │
│  EMAIL BODY CONTENT             │
│  - Dynamic content from DB      │
│  - {{quotation_url}} tracking   │ ← Replaced with /track/click/{id}
│                                 │
├─────────────────────────────────┤
│  FOOTER                         │
│  ┌──────────────────────────┐  │
│  │  Footer Logo (Tracked)   │  │ ← Tracks via /track/footer/{id}
│  └──────────────────────────┘  │
│  Company Info                   │
│  Hidden Pixel (1x1)             │ ← Fallback tracking
└─────────────────────────────────┘
```

### 2. Tracking Flow

```
User Opens Email
    ↓
Email Client Loads Images
    ↓
┌──────────────────────────────┐
│ 1. Logo loads from:          │
│    /track/logo/{emailId}     │ → Logs "open" event (source: logo)
└──────────────────────────────┘
    ↓
┌──────────────────────────────┐
│ 2. Footer logo loads from:   │
│    /track/footer/{emailId}   │ → Logs "open" event (source: footer)
└──────────────────────────────┘
    ↓
┌──────────────────────────────┐
│ 3. Hidden pixel loads:       │
│    /track/open/{emailId}     │ → Logs "open" event (fallback)
└──────────────────────────────┘
```

### 3. Code Flow

```php
EmailTrigger::send()
    ↓
1. Get email template from DB
    ↓
2. Parse template variables ({{buyer_name}}, {{quotation_number}}, etc.)
    ↓
3. logEmailSent() - Save to DB, get email ID
    ↓
4. Store email ID in $this->lastEmailLogId
    ↓
5. Replace {{quotation_url}} with /track/click/{id}
    ↓
6. sendEmail() - Render blade template with:
   - emailBody (parsed content)
   - trackingId (for logo/footer/pixel)
   - recipientEmail
   - company info
    ↓
7. Blade template includes:
   <img src="/track/logo/{trackingId}" />    ← Header logo
   <img src="/track/footer/{trackingId}" />  ← Footer logo
   <img src="/track/open/{trackingId}" />    ← Hidden pixel
```

---

## Implementation Details

### Blade Layout (`auto_quotation.blade.php`)

**Features:**
- Responsive design (max-width: 600px)
- Professional styling with gradient header
- Logo in header (tracked)
- Footer with logo (tracked)
- Company contact information
- Hidden tracking pixel (fallback)

**Variables Passed:**
```php
[
    'emailBody' => $parsedContent,        // From DB template
    'subject' => $emailSubject,
    'trackingId' => $emailLogId,          // For tracking URLs
    'recipientEmail' => $buyer->email,
    'companyAddress' => $settings->company_address,
    'companyPhone' => $settings->company_phone,
    'companyEmail' => $settings->company_email,
]
```

### Tracking Routes

**Logo Tracking:**
```php
Route::get('/track/logo/{id}', function ($id) {
    // Track open event with source metadata
    app(EmailTrackingService::class)->trackOpen($id, ['source' => 'logo']);
    
    // Return actual logo image
    return response()->file(public_path('frontend/images/logo.png'));
});
```

**Footer Tracking:**
```php
Route::get('/track/footer/{id}', function ($id) {
    // Track open event with source metadata
    app(EmailTrackingService::class)->trackOpen($id, ['source' => 'footer']);
    
    // Return footer logo
    return response()->file(public_path('frontend/images/footer-logo.png'));
});
```

**Benefits:**
- Returns real images (logos) that email clients trust
- Tracks which part of email was viewed (logo vs footer)
- Fallback chain: footer-logo.png → logo.png → pixel.png

---

## Database Schema

### Tables Used

**auto_quote_emails:**
```sql
- id (primary key)
- auto_quote_workflow_id (nullable) - FK to workflows
- auto_quote_template_id (nullable) - Legacy, now nullable
- auto_email_setting_id (nullable) - New template system
- quotation_number
- recipient_email
- email_body (stored for reference)
- sent_at
- open_count (aggregated)
- click_count (aggregated)
- download_count (aggregated)
- first_opened_at, last_opened_at
- first_clicked_at, last_clicked_at
- first_downloaded_at, last_downloaded_at
```

**auto_quote_email_events:**
```sql
- id (primary key)
- auto_quote_email_id (FK)
- event_type (open, click, download)
- ip_address
- user_agent
- referrer
- created_at
```

**auto_quote_activities:**
```sql
- id (primary key)
- seller_id
- auto_quote_template_id (nullable) - Made nullable via migration
- auto_quote_email_id (nullable)
- module (email, pricing, workflow)
- operation (opened, clicked, downloaded, sent)
- performed_by (buyer, system, seller)
- message
- ip_address
- user_agent
- meta (JSON)
- created_at, updated_at
```

---

## Configuration

### Required Assets

Place these images in your public directory:

1. **Logo (Header):**
   - Path: `public/frontend/images/logo.png`
   - Recommended: 200px wide, transparent background
   - Used in email header

2. **Footer Logo:**
   - Path: `public/frontend/images/footer-logo.png`
   - Recommended: 150px wide, transparent background
   - Used in email footer

3. **Tracking Pixel (Fallback):**
   - Path: `public/pixel.png`
   - 1x1 transparent PNG (already created)

### Email Template Variables

Templates support these placeholders:

```
{{buyer_name}}          - Buyer's full name
{{buyer_email}}         - Buyer's email
{{seller_name}}         - Seller's name
{{quotation_number}}    - Quote number
{{quotation_date}}      - Quote date
{{quotation_total}}     - Total amount
{{quotation_url}}       - Auto-replaced with tracked click URL
{{product_name}}        - Product/service name
{{company_name}}        - Your company name
```

### Customization

**To customize email layout:**
1. Edit `resources/views/emails/layouts/auto_quotation.blade.php`
2. Modify colors, fonts, styling in `<style>` section
3. Update logo paths if using different images

**To add custom tracking:**
```php
// In blade template
<img src="{{ url('/track/custom/' . $trackingId) }}" />

// In routes/web.php
Route::get('/track/custom/{id}', function ($id) {
    app(EmailTrackingService::class)->trackOpen($id, ['source' => 'custom']);
    return response()->file(public_path('path/to/image.png'));
});
```

---

## Testing

### Test Email Tracking

1. **Generate test email:**
   ```
   http://localhost:8888/PowercozmoLaravel-2023/test-email-tracking
   ```

2. **Click tracking links:**
   - Test Open Tracking (Pixel)
   - Test Click Tracking
   - Test Download Tracking

3. **View statistics:**
   ```
   http://localhost:8888/PowercozmoLaravel-2023/test-email-tracking/stats/{emailId}
   ```

### Verify Tracking

**Database Queries:**
```sql
-- Check email record
SELECT * FROM auto_quote_emails ORDER BY id DESC LIMIT 1;

-- Check tracking events
SELECT * FROM auto_quote_email_events 
WHERE auto_quote_email_id = {emailId}
ORDER BY created_at DESC;

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

**Expected Flow:**
1. Email sent → `auto_quote_emails` record created
2. Buyer opens email → Logo loads → `open` event recorded (source: logo)
3. Buyer scrolls → Footer loads → `open` event recorded (source: footer)
4. Buyer clicks link → `click` event recorded
5. All events → Aggregated counts updated in `auto_quote_emails`
6. All events → Activity log entries in `auto_quote_activities`

---

## Advantages of This Approach

### 1. Higher Tracking Reliability
- **Visible images load more reliably** than hidden pixels
- Email clients often block tracking pixels but show logos
- Multiple tracking points increase accuracy

### 2. Professional Presentation
- Branded email layout with company logo
- Consistent styling across all auto-quotation emails
- Mobile-responsive design

### 3. Better Analytics
- Track which images loaded (logo vs footer)
- Understand email client behavior
- Multiple data points for open tracking

### 4. Maintainability
- Centralized template (one place to update)
- Blade syntax for easy customization
- Separation of content and presentation

### 5. Fallback Strategy
```
Primary:   Logo tracking (/track/logo/{id})
Secondary: Footer tracking (/track/footer/{id})
Fallback:  Hidden pixel (/track/open/{id})
```

---

## Production Checklist

Before deploying to production:

- [ ] Remove test routes from `routes/web.php`:
  - `/test-email-tracking`
  - `/test-email-tracking/stats/{id}`

- [ ] Upload company logo and footer images:
  - `public/frontend/images/logo.png`
  - `public/frontend/images/footer-logo.png`

- [ ] Update email layout with company branding:
  - Colors, fonts in `auto_quotation.blade.php`
  - Company contact information

- [ ] Configure email settings in `auto_email_settings` table:
  - `company_address`
  - `company_phone`
  - `company_email`

- [ ] Test email delivery:
  - Send test email to real email account
  - Verify images load correctly
  - Check tracking works

- [ ] Monitor tracking:
  - Check `auto_quote_email_events` table
  - Verify aggregates update correctly
  - Review activity logs

---

## Troubleshooting

### Images Not Loading

**Issue:** Logo/footer not appearing in emails

**Solutions:**
1. Check file exists: `public/frontend/images/logo.png`
2. Verify URL is accessible: Visit `/track/logo/1` directly
3. Check file permissions: `chmod 644 public/frontend/images/*.png`

### Tracking Not Working

**Issue:** Opens/clicks not recorded

**Solutions:**
1. Check routes are public (no auth middleware)
2. Verify `EmailTrackingService` class path is correct
3. Check database connection (`crm` connection)
4. Review logs: `storage/logs/laravel.log`

### Blade Template Errors

**Issue:** Email not rendering

**Solutions:**
1. Check blade syntax: `php artisan view:clear`
2. Verify template exists: `resources/views/emails/auto_quotation_email.blade.php`
3. Check variables passed to view match blade template

---

## API Documentation

### EmailTrigger::send()

```php
public function send(
    Quotation $quotation,
    AutoQuotingSetting $settings,
    AutoQuoteWorkflow $workflow
): bool
```

**Purpose:** Send auto-quotation email with tracking

**Flow:**
1. Validate auto-email enabled
2. Get buyer information
3. Load email template from `auto_email_settings`
4. Parse template variables
5. Log email to database (get tracking ID)
6. Replace `{{quotation_url}}` with tracked link
7. Send email via blade template with tracking
8. Return success/failure

**Returns:** `true` if email sent successfully, `false` otherwise

### EmailTrackingService::trackOpen()

```php
public function trackOpen(int $emailId, array $meta = []): void
```

**Parameters:**
- `$emailId` - Auto quote email ID
- `$meta` - Optional metadata (e.g., `['source' => 'logo']`)

**Purpose:** Record email open event

**Actions:**
1. Create event record in `auto_quote_email_events`
2. Update aggregate counts in `auto_quote_emails`
3. Log activity in `auto_quote_activities` (if workflow exists)

---

## Summary

The blade template approach provides:

✅ **Professional branded emails** with logo and company info
✅ **Reliable tracking** using visible images instead of hidden pixels
✅ **Multiple tracking points** (logo + footer + pixel)
✅ **Easy customization** via blade templates
✅ **Better deliverability** - email clients trust visible images
✅ **Comprehensive analytics** with source tracking

This implementation replaces the old method of injecting tracking pixels into HTML strings with a clean, maintainable blade template system that provides better tracking reliability and professional presentation.
