# Email Provider Configuration

## Overview
The application now supports two email delivery methods:
1. **SMTP** - Laravel Mail configuration (fallback option)
2. **Email API** - Multi-provider email gateway with automatic failover (default)

## Environment Variables

Add the following variables to your `.env` file:

```env
# Email Provider Configuration
# Options: 'api' (default) or 'smtp'
EMAIL_PROVIDER=api

# Email API Configuration
# Base URL for email service (private domain - AWS internal only)
EMAIL_API_BASE_URL=http://utility-api.drjob.services/api

# Optional: API timeout in seconds (default: 30)
EMAIL_API_TIMEOUT=30

# Admin email for notifications (optional)
ADMIN_EMAIL=admin@drjobs.com
```

## Configuration File

The email configuration is managed in `config/mail.php`:

```php
// Email provider: 'api' (default) or 'smtp'
'provider' => env('EMAIL_PROVIDER', 'api'),

// Email API settings
'api' => [
    'base_url' => env('EMAIL_API_BASE_URL', 'http://utility-api.drjob.services/api'),
    'timeout' => env('EMAIL_API_TIMEOUT', 30),
],

// Admin email for notifications
'admin_email' => env('ADMIN_EMAIL'),
```

## Email Provider Options

### API (Default)
- Routes emails through multi-provider email service
- Supports automatic failover between providers (Mailgun, Brevo, Mailwizz)
- Requires network access to `http://utility-api.drjob.services`
- **Note**: API is only accessible from inside DrJob AWS servers (private domain)
- Provides better email deliverability and tracking

### SMTP (Fallback)
- Uses Laravel's built-in Mail facade
- Configured via standard mail environment variables
- Use when API is not available or for local development

## Email Routes

The API supports different email routes for different use cases:

| Route | Primary Provider | Fallback | Use Case |
|-------|-----------------|----------|----------|
| `transactional:high` | Mailgun | Mailwizz | High-priority (OTP, password reset, verification) |
| `transactional:low` | Brevo | Mailwizz | Low-priority notifications (welcome, interview, etc.) |
| `marketing` | Brevo | None | Newsletters, campaigns |
| `default` | Mailwizz | Mailgun | General emails |

### Route Constants
```php
Helper::EMAIL_ROUTE_TRANSACTIONAL_HIGH  // 'transactional:high'
Helper::EMAIL_ROUTE_TRANSACTIONAL_LOW   // 'transactional:low'
Helper::EMAIL_ROUTE_MARKETING           // 'marketing'
Helper::EMAIL_ROUTE_DEFAULT             // 'default'
```

### Helper Method
```php
// Automatically determine route based on email type
$route = Helper::getEmailRoute('2fa_otp');  // Returns 'transactional:high'
$route = Helper::getEmailRoute('welcome');  // Returns 'transactional:low'
```

## Usage

The email provider switch is handled automatically in the Helper class. No code changes are required in controllers.

### Sending Simple Emails
```php
// Without email route (uses default)
Helper::sendHtmlMail(
    $to,
    $subject,
    $view,
    $data,
    $fromEmail,
    $fromName
);

// With email route (recommended for API mode)
Helper::sendHtmlMail(
    $to,
    $subject,
    $view,
    $data,
    $fromEmail,
    $fromName,
    Helper::EMAIL_ROUTE_TRANSACTIONAL_HIGH  // For high-priority emails
);
```

### Sending Emails with Attachments
```php
Helper::sendHtmlMailWithAttachments(
    $to,
    $subject,
    $view,
    $data,
    $attachments,
    $fromEmail,
    $fromName,
    Helper::EMAIL_ROUTE_TRANSACTIONAL_LOW  // Optional email route
);
```

### Checking Email Status (API only)
```php
// Without route (uses default)
$status = Helper::checkEmailStatus($messageId);

// With route (recommended)
$status = Helper::checkEmailStatus($messageId, Helper::EMAIL_ROUTE_TRANSACTIONAL_HIGH);
```

## Pre-configured Email Routes

The following Helper methods automatically use appropriate email routes:

| Method | Email Route | Priority |
|--------|-------------|----------|
| `send2FAOTP()` | `transactional:high` | High |
| `sendVerificationEmail()` | `transactional:high` | High |
| `sendPasswordResetEmail()` | `transactional:high` | High |
| `sendWelcomeEmail()` | `transactional:low` | Low |
| `sendMemberWelcomeEmail()` | `transactional:low` | Low |
| `sendMemberInvitationEmail()` | `transactional:low` | Low |
| `sendMemberDeletionEmail()` | `transactional:low` | Low |
| `sendAdminNotification()` | `transactional:low` | Low |

## Email API Endpoints

### 1. Send Email (without attachments)
- **Endpoint**: `POST /api/v1/email/send`
- **Used by**: `Helper::sendHtmlMail()`

### 2. Send Email with Attachments
- **Endpoint**: `POST /api/v1/email/send-attachment`
- **Used by**: `Helper::sendHtmlMailWithAttachments()`

### 3. Check Email Status
- **Endpoint**: `GET /api/v1/email/status/{id}?email_route={route}`
- **Used by**: `Helper::checkEmailStatus()`

### 4. List Routes (informational)
- **Endpoint**: `GET /api/v1/email/routes`

### 5. Get Provider Health (informational)
- **Endpoint**: `GET /api/v1/email/providers`

## API Request/Response Format

### Send Email Request
```json
{
  "to_email": "user@example.com",
  "subject": "Welcome",
  "body": "<p>Welcome to DrJobs</p>",
  "email_route": "transactional:high"
}
```

**Note**: `from_email` and `from_name` are handled by the API based on the email route configuration.

### Send Email with Attachments Request
```json
{
  "to_email": "user@example.com",
  "subject": "Your Invoice",
  "body": "<p>Invoice attached</p>",
  "email_route": "transactional:low",
  "attachments": [
    {
      "name": "invoice.pdf",
      "type": "application/pdf",
      "content": "JVBERi0xLjQ..."
    }
  ]
}
```

### Success Response
```json
{
  "status": "success",
  "data": {
    "message_id": "abc123",
    "status": "sent",
    "email_route": "transactional:high"
  }
}
```

### Status Check Response
```json
{
  "status": "success",
  "data": {
    "message_id": "abc123",
    "status": "delivered",
    "email_route": "transactional:high"
  }
}
```

**Status Values**: `pending`, `sent`, `delivered`, `opened`, `clicked`, `bounced`, `failed`, `unknown`

## Migration Guide

### Breaking Changes from Previous Version

| Old Field | New Field | Notes |
|-----------|-----------|-------|
| `route_type` | `email_route` | Request/response field |
| `attachments[].data` | `attachments[].content` | Base64 content |
| `attachments[].mime_type` | `attachments[].type` | MIME type |
| `MAILWIZZ_API_URL` | `EMAIL_API_BASE_URL` | Environment variable |

### Step 1: Update Environment Variables
Update your `.env` file with the new configuration:
```env
# Email provider (default is now 'api')
EMAIL_PROVIDER=api

# Email API base URL (includes /api path)
EMAIL_API_BASE_URL=http://utility-api.drjob.services/api

# Optional: API timeout
EMAIL_API_TIMEOUT=30
```

### Step 2: Clear Config Cache
After updating environment variables:
```bash
php artisan config:clear
php artisan config:cache
```

### Step 3: Verify API Access
Ensure your server can reach `http://utility-api.drjob.services` (AWS internal network only).

### Step 4: Test Email Sending
Test email functionality to ensure everything works correctly.

## Troubleshooting

### Emails not sending via API
1. Check if `EMAIL_PROVIDER=api` in `.env`
2. Verify `EMAIL_API_BASE_URL` is set correctly
3. Clear config cache: `php artisan config:clear`
4. Verify network access to Email API URL
5. Check application logs for error details:
   - `storage/logs/laravel.log`
   - Search for "Email API" entries

### Reverting to SMTP
Change the environment variable:
```env
EMAIL_PROVIDER=smtp
```
Then clear config cache: `php artisan config:clear`

## Logging

All email operations are logged with appropriate detail:
- Success: `Log::info()` with message ID and email_route (for API)
- Errors: `Log::error()` with error details
- Check logs at: `storage/logs/laravel.log`

## Notes

- API is now the default email provider
- SMTP is available as a fallback option
- API mode requires deployment inside DrJob AWS infrastructure
- Attachments are automatically base64 encoded for API transmission
- View templates are rendered to HTML before sending via API
- Both methods use the same Helper functions - switching is transparent to application code
- Email routes are only used when `EMAIL_PROVIDER=api`; SMTP mode ignores the route parameter
- Configuration is managed via `config/mail.php` using Laravel's config system
