# Email Notifications Setup Guide

## Overview

This guide explains how to configure email notifications for ticket actions in MVNexus.

## Quick Summary

**Issue**: Ticket action emails were not being sent to real email addresses.

**Root Cause**: 
1. Missing Mailgun Symfony mailer package
2. Missing Mailgun mailer configuration in Laravel's mail config

**Solution**: 
1. Installed required Mailgun packages via Composer
2. Added Mailgun mailer configuration 
3. Updated environment settings

---

## Installation Requirements

### Required Composer Packages

To use Mailgun for email notifications, you must install the Symfony Mailgun mailer:

```bash
composer require symfony/mailgun-mailer symfony/http-client
```

These packages are required for Laravel to communicate with the Mailgun API.

---

## Configuration Files Changed

### 1. `/config/mail.php`
Added Mailgun mailer to the `mailers` array:

```php
'mailgun' => [
    'transport' => 'mailgun',
],
```

### 2. `/config/services.php`
Added Mailgun service configuration:

```php
'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
    'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
    'scheme' => 'https',
],
```

### 3. `.env`
Updated environment variables:

```env
# Mail Configuration
MAIL_MAILER=mailgun  # Changed from 'log'

# Mailgun Credentials (already present)
MAILGUN_DOMAIN=mountainviewegypt.com
MAILGUN_SECRET=your-secret-key
MAILGUN_ENDPOINT=api.mailgun.net

# Notification Settings
NOTIFICATIONS_EMAIL_ENABLED=true
NOTIFICATIONS_DEDUPE_ENABLED=true
```

---

## How It Works

### Development vs Production

**Development Mode (`MAIL_MAILER=log`)**:
- Emails are written to `storage/logs/laravel.log`
- No actual emails are sent
- Useful for local testing without consuming Mailgun quota

**Production Mode (`MAIL_MAILER=mailgun`)**:
- Emails are sent via Mailgun to real email addresses
- Requires valid Mailgun credentials
- Emails appear in Mailgun dashboard

### Notification Flow

1. **Event Triggered**: A ticket action occurs (create, assign, status change, etc.)
2. **Event Listener**: Corresponding listener (e.g., `NotifyOnTicketCreated`) is invoked
3. **Notification Service**: `NotificationService` processes the notification
4. **Channel Check**: Checks if email channel is enabled for the user
5. **Template Rendering**: Retrieves and renders the notification template
6. **Email Job**: `SendNotificationEmailJob` is dispatched (queued or sync)
7. **Mailgun**: Email is sent via Mailgun API

### Supported Notification Types

All ticket actions trigger both in-app and email notifications (if enabled):

- ✅ Ticket Created
- ✅ Ticket Assigned
- ✅ Ticket Unassigned
- ✅ Ticket Status Changed
- ✅ Ticket Resolved
- ✅ Ticket Closed
- ✅ Priority Changed
- ✅ New Reply
- ✅ New Note (internal - agents only)
- ✅ User Mentioned
- ✅ SLA Warning
- ✅ SLA Breached

---

## Testing

### Test via Tinker

```bash
php artisan tinker
```

```php
use App\Modules\Notifications\DTOs\SendNotificationDTO;
use App\Modules\Notifications\Enums\NotificationType;
use App\Modules\Notifications\Services\NotificationService;
use App\Modules\Identity\Models\User;
use App\Modules\Ticketing\Models\Ticket;

$user = User::first();
$ticket = Ticket::first();

$service = app(NotificationService::class);

$dto = new SendNotificationDTO(
    type: NotificationType::TICKET_ASSIGNED,
    recipientIds: [$user->id],
    title: 'Test Notification',
    message: 'This is a test notification',
    data: [
        'ticket_number' => $ticket->ticket_number,
        'ticket_subject' => $ticket->subject,
        'action_url' => config('app.url') . '/tickets/' . $ticket->id,
        'action_text' => 'View Ticket',
    ],
    relatedType: $ticket::class,
    relatedId: $ticket->id,
    departmentId: $ticket->department_id,
);

$service->send($dto);
// Check Mailgun dashboard for delivery
```

### Test via PHPUnit

Run all notification tests:

```bash
php artisan test tests/Feature/Notifications/ tests/Unit/Modules/Notifications/
```

### Verify in Mailgun Dashboard

1. Log in to https://app.mailgun.com/
2. Navigate to **Sending** → **Logs**
3. Filter by domain: `mountainviewegypt.com`
4. Check for recent email deliveries

---

## Troubleshooting

### Emails not appearing in Mailgun

**Check 1: Verify mail driver**
```bash
php artisan tinker --execute="echo config('mail.default');"
```
Should output: `mailgun`

**Check 2: Clear config cache**
```bash
php artisan config:clear
```

**Check 3: Check Mailgun credentials**
```bash
php artisan tinker --execute="
echo 'Domain: ' . config('services.mailgun.domain') . PHP_EOL;
echo 'Secret: ' . (config('services.mailgun.secret') ? 'SET' : 'NOT SET') . PHP_EOL;
"
```

**Check 4: Check Laravel logs**
```bash
tail -f storage/logs/laravel.log
```
Look for errors related to email sending.

### Emails going to spam

- Ensure your Mailgun domain is verified
- Set up SPF and DKIM records in your DNS
- Check Mailgun domain reputation

### User not receiving emails

**Check 1: User preferences**
```php
$pref = App\Modules\Notifications\Models\NotificationPreference
    ::where('user_id', $userId)
    ->where('notification_type', 'ticket_created')
    ->first();
    
if ($pref) {
    echo $pref->email_enabled ? 'Enabled' : 'Disabled';
}
```

**Check 2: Global email channel enabled**
```bash
php artisan tinker --execute="
echo config('notifications.channels.email.enabled') ? 'ENABLED' : 'DISABLED';
"
```

**Check 3: User has email address**
```php
$user = App\Modules\Identity\Models\User::find($userId);
echo $user->email ?? 'NO EMAIL';
```

---

## Queue Configuration

### Synchronous (Development)

```env
QUEUE_CONNECTION=sync
```
- Jobs run immediately in the same process
- No queue worker needed
- Slower response times for API requests

### Asynchronous (Production - Recommended)

```env
QUEUE_CONNECTION=database
```

**Start queue worker:**
```bash
php artisan queue:work --sleep=3 --tries=3 --timeout=90
```

**Or use a process manager (Supervisor):**
```ini
[program:mvhelpdesk-queue]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/mvhelpdesk/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/path/to/mvhelpdesk/storage/logs/queue.log
stopwaitsecs=3600
```

---

## Common Issues

### "Mailer [mailgun] is not defined"

**Cause**: Missing mailgun configuration in `config/mail.php` OR missing Symfony Mailgun package

**Fix**: 
1. Install required package:
   ```bash
   composer require symfony/mailgun-mailer symfony/http-client
   ```
2. Ensure `mailgun` mailer is defined in the `mailers` array (see Configuration Files section above)

### "Class 'Symfony\Component\Mailer\Bridge\Mailgun\Transport\MailgunTransportFactory' not found"

**Cause**: Symfony Mailgun mailer package not installed

**Fix**:
```bash
composer require symfony/mailgun-mailer symfony/http-client
php artisan config:clear
```

### "User has no email address"

**Cause**: User model doesn't have an email set

**Fix**: Ensure users have valid email addresses in the `users` table

### "No template found"

**Cause**: Notification template not seeded

**Fix**: 
```bash
php artisan db:seed --class=NotificationTemplateSeeder
```

Or the system will auto-seed missing templates via `NotificationTemplateBootstrapService`.

---

## Best Practices

1. **Development**: Use `MAIL_MAILER=log` to avoid sending test emails
2. **Production**: Use `MAIL_MAILER=mailgun` with queue workers
3. **Always clear config cache** after changing `.env`:
   ```bash
   php artisan config:clear
   ```
4. **Monitor Mailgun quota** to avoid sending limits
5. **Set up proper DNS records** (SPF, DKIM) for better deliverability
6. **Test notifications** after deployment using Tinker

---

## Related Files

- `app/Modules/Notifications/Services/NotificationService.php` - Main notification orchestrator
- `app/Modules/Notifications/Services/Channels/EmailNotificationChannel.php` - Email channel handler
- `app/Modules/Notifications/Jobs/SendNotificationEmailJob.php` - Queued email job
- `app/Modules/Notifications/Mail/NotificationEmail.php` - Email mailable
- `app/Modules/Notifications/Listeners/` - Event listeners for each notification type
- `database/seeders/NotificationTemplateSeeder.php` - Default templates
- `tests/Feature/Notifications/AllTicketNotificationTypesTest.php` - Comprehensive test suite

---

## Support

For issues or questions:
1. Check `storage/logs/laravel.log` for errors
2. Run the test suite: `php artisan test tests/Feature/Notifications/`
3. Verify Mailgun dashboard for delivery status
4. Check notification preferences in the database
