# Email & Notifications Setup Guide

## Overview

ChatBud supports multiple email providers for sending transactional and notification emails.

## Supported Email Services

1. **SMTP** (Built-in PHP mail or external SMTP server)
2. **SendGrid** (Third-party API)
3. **Mailgun** (Third-party API)
4. **Postmark** (Third-party API)

## Configuration

### Environment Variables

Add to `.env` file:

```env
# Email Driver: 'smtp', 'sendgrid', 'mailgun', 'postmark'
MAIL_DRIVER=smtp

# SMTP Configuration
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=465
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_FROM_ADDRESS=noreply@chatbud.com
MAIL_FROM_NAME=ChatBud

# SendGrid (if using SendGrid)
SENDGRID_API_KEY=your_sendgrid_api_key

# Mailgun (if using Mailgun)
MAILGUN_API_KEY=your_mailgun_api_key
MAILGUN_DOMAIN=mail.chatbud.com

# Postmark (if using Postmark)
POSTMARK_API_KEY=your_postmark_api_key

# App URL for email links
APP_URL=https://chatbud.com
```

## SMTP Setup

### Using Mailtrap (Development)

1. Sign up at https://mailtrap.io
2. Create inbox
3. Copy credentials from "Integrations" tab
4. Add to `.env`:

```env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=465
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_FROM_ADDRESS=noreply@chatbud.com
```

### Using Gmail SMTP

1. Enable 2-factor authentication
2. Generate App Password
3. Configure:

```env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_app_password
MAIL_FROM_ADDRESS=noreply@chatbud.com
```

### Using Custom SMTP Server

```env
MAIL_DRIVER=smtp
MAIL_HOST=your.mail.server
MAIL_PORT=587
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_FROM_ADDRESS=noreply@chatbud.com
```

## SendGrid Setup

### 1. Create Account

- Sign up at https://sendgrid.com
- Verify sender email domain

### 2. Get API Key

1. Go to Settings → API Keys
2. Create new API key
3. Copy the key

### 3. Configure

```env
MAIL_DRIVER=sendgrid
SENDGRID_API_KEY=SG.your_api_key_here
MAIL_FROM_ADDRESS=noreply@chatbud.com
```

### 4. Install SendGrid Library (Optional)

```bash
composer require sendgrid/sendgrid
```

## Mailgun Setup

### 1. Create Account

- Sign up at https://mailgun.com
- Add domain
- Verify domain

### 2. Get API Key

1. Go to API tab
2. Copy Private API Key
3. Note your domain

### 3. Configure

```env
MAIL_DRIVER=mailgun
MAILGUN_API_KEY=key-xxxxxxxxxxxx
MAILGUN_DOMAIN=mg.chatbud.com
MAIL_FROM_ADDRESS=noreply@chatbud.com
```

### 4. Install Mailgun Library (Optional)

```bash
composer require mailgun/mailgun-php
```

## Email Types & Templates

### 1. Verification Email

Sent when user registers:
- Purpose: Verify email address
- Delay: Immediately
- Link expires: 24 hours

### 2. Password Reset Email

Sent when user requests password reset:
- Purpose: Reset forgotten password
- Delay: Immediately
- Link expires: 1 hour

### 3. Notification Emails

Sent for user interactions:
- **Follow**: Someone follows user
- **Like**: Someone likes user's post
- **Comment**: Someone comments on user's post
- **Mention**: User is mentioned in a post

### 4. Welcome Email

Sent after email verification:
- Purpose: Welcome new user
- Delay: After verification
- Can be customized

## Email Templates

Templates are stored in `src/templates/emails/`

### Creating Custom Template

Create `src/templates/emails/custom.php`:

```php
<?php
$email = $email ?? 'user@example.com';
$username = $username ?? 'User';
$link = $link ?? '#';
$content = $content ?? '';
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <style>
        body { font-family: Arial, sans-serif; }
        .container { max-width: 600px; margin: 0 auto; }
        .button { 
            display: inline-block;
            padding: 12px 24px;
            background: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Welcome to ChatBud, <?php echo e($username); ?>!</h1>
        <p><?php echo e($content); ?></p>
        <a href="<?php echo e($link); ?>" class="button">Action Button</a>
    </div>
</body>
</html>
```

### Using Template in Code

```php
$emailService = new EmailService();
$emailService->sendTemplate($email, 'Subject', 'custom', [
    'email' => $email,
    'username' => $username,
    'link' => $link,
    'content' => 'Custom content'
]);
```

## Notification Preferences

Users can control notification preferences (future feature):

```php
// Save user notification preferences
$userNotificationPrefs = [
    'follow' => true,
    'like' => true,
    'comment' => true,
    'mention' => true,
    'direct_message' => true,
    'digest' => 'daily' // or 'weekly', 'never'
];
```

## Testing Emails

### Test Email Service

Create `test_email.php`:

```php
<?php
require_once 'src/lib/config.php';

$emailService = new EmailService();

try {
    $result = $emailService->send(
        'test@example.com',
        'Test Email from ChatBud',
        'This is a test email to verify email service is working.'
    );
    
    if ($result) {
        echo "✓ Email sent successfully!";
    } else {
        echo "✗ Email failed to send";
    }
} catch (Exception $e) {
    echo "✗ Error: " . $e->getMessage();
}
?>
```

Run:
```bash
php test_email.php
```

### Check Email Logs

Emails are logged in system error log:
```bash
tail -f /var/log/php-errors.log | grep EMAIL
```

## Troubleshooting

### Emails Not Being Sent

1. Check mail driver configuration
2. Verify credentials
3. Check firewall/port settings
4. Review error logs
5. Test with `php test_email.php`

### Emails Going to Spam

1. Set up SPF record:
   ```
   v=spf1 include:sendgrid.net ~all
   ```

2. Set up DKIM:
   - Configure in email provider

3. Set up DMARC:
   ```
   v=DMARC1; p=quarantine; rua=mailto:admin@chatbud.com
   ```

### SMTP Connection Timeout

1. Check firewall allows outbound connections
2. Verify correct port (usually 465 for SSL, 587 for TLS)
3. Try different SMTP provider
4. Check server logs for errors

### Invalid Credentials

1. Double-check username and password
2. Verify API key format
3. Check if credentials have expired
4. Regenerate credentials in provider dashboard

## Production Checklist

- [ ] Email driver configured
- [ ] Credentials secured in environment variables
- [ ] SPF/DKIM/DMARC records configured
- [ ] Email templates customized
- [ ] Sender email domain verified
- [ ] Rate limiting configured
- [ ] Bounce handling implemented
- [ ] Email logs monitored
- [ ] Unsubscribe mechanism implemented
- [ ] GDPR compliance for email preferences

## Advanced Configuration

### Rate Limiting

Prevent email flooding:

```php
// Allow 5 emails per minute per user
$maxEmails = 5;
$timeWindow = 60; // seconds

// Check and send
if ($emailService->canSend($userId, $maxEmails, $timeWindow)) {
    $emailService->send($email, $subject, $message);
}
```

### Bounce Handling

Handle email bounces from providers:

```php
// Listen for webhook from email provider
$bounce = json_decode($_POST['bounce'] ?? '{}', true);

if ($bounce['type'] === 'permanent') {
    // Mark email as invalid
    $userModel->update($userId, ['email' => null, 'is_active' => false]);
}
```

### Email Queue

For high volume, queue emails for async sending:

```php
// Queue email instead of sending immediately
$emailQueue->queue($email, $subject, $message);

// Process queue via cron job
// /scripts/process_email_queue.php
```

## Support

For email issues, contact: support@chatbud.com
