# Email Notification System Documentation

## Overview

A comprehensive email notification system has been implemented for the AskeriPlatform, providing automated email notifications for critical user interactions including welcome emails, password resets, forum replies, blog comments, and like notifications.

---

## 1. Mail Classes

### Location
`app/Mail/`

### Available Mail Classes

#### 1. **WelcomeMail** (`app/Mail/WelcomeMail.php`)
Sent when a new user registers.

**Usage:**
```php
use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;

Mail::to($user->email)->send(new WelcomeMail($user));
```

**Template:** `resources/views/emails/welcome.blade.php`

**Features:**
- 🎉 Welcome greeting
- Feature overview (blog, forum, library, interviews, calculators, AI)
- Dashboard and profile links
- Encourages exploring the platform

---

#### 2. **ForumReplyMail** (`app/Mail/ForumReplyMail.php`)
Sent when a user receives a forum reply or quote.

**Usage:**
```php
use App\Mail\ForumReplyMail;

Mail::to($recipient->email)->send(new ForumReplyMail(
    $recipient,
    $sender,
    $topic,
    $post,
    'reply' // or 'quote'
));
```

**Template:** `resources/views/emails/forum-reply.blade.php`

**Features:**
- Differentiates between replies and quotes
- Shows sender information with avatar
- Displays topic title
- Includes message snippet
- Direct link to the reply

---

#### 3. **ForumLikeMail** (`app/Mail/ForumLikeMail.php`)
Sent when a user's forum post receives a like.

**Usage:**
```php
use App\Mail\ForumLikeMail;

Mail::to($recipient->email)->send(new ForumLikeMail(
    $recipient,
    $liker,
    $post,
    $topic
));
```

**Template:** `resources/views/emails/forum-like.blade.php`

**Features:**
- 👍 Like notification
- Liker information
- Message snippet
- Engagement encouragement

---

#### 4. **BlogCommentMail** (`app/Mail/BlogCommentMail.php`)
Sent when a user's blog post receives a comment or a comment receives a reply.

**Usage:**
```php
use App\Mail\BlogCommentMail;

Mail::to($recipient->email)->send(new BlogCommentMail(
    $recipient,
    $post,
    $comment,
    'new_comment' // or 'reply'
));
```

**Template:** `resources/views/emails/blog-comment.blade.php`

**Features:**
- Differentiates between new comments and replies
- Commenter information
- Blog post title
- Comment content preview
- Direct link to comment

---

#### 5. **PasswordResetMail** (`app/Mail/PasswordResetMail.php`)
Sent when a user requests a password reset.

**Usage:**
```php
use App\Mail\PasswordResetMail;

Mail::to($user->email)->send(new PasswordResetMail(
    $user,
    $resetUrl
));
```

**Template:** `resources/views/emails/password-reset.blade.php`

**Features:**
- 🔐 Security focus
- 60-minute expiration notice
- Warning about unsolicited requests
- Direct reset link
- Fallback URL option

---

#### 6. **EmailVerificationMail** (`app/Mail/EmailVerificationMail.php`)
Sent when a user registers and needs to verify their email.

**Usage:**
```php
use App\Mail\EmailVerificationMail;

Mail::to($user->email)->send(new EmailVerificationMail(
    $user,
    $verifyUrl
));
```

**Template:** `resources/views/emails/email-verification.blade.php`

**Features:**
- ✉️ Email verification
- 60-minute validity window
- Account activation information
- Direct verification link
- Fallback URL option

---

## 2. EmailService

### Location
`app/Services/EmailService.php`

### Purpose
Central service for managing all email communications with error handling, user preference checks, and logging.

### Key Methods

```php
// Send welcome email
$emailService->sendWelcomeEmail($user);

// Send forum reply/quote
$emailService->sendForumReplyEmail($recipient, $sender, $topic, $post, $type);

// Send forum like notification
$emailService->sendForumLikeEmail($recipient, $liker, $post, $topic);

// Send blog comment
$emailService->sendBlogCommentEmail($recipient, $post, $comment, $type);

// Send password reset
$emailService->sendPasswordResetEmail($user, $resetUrl);

// Send email verification
$emailService->sendEmailVerificationEmail($user, $verifyUrl);
```

### Features
- ✅ Automatic error handling with logging
- ✅ User preference checking
- ✅ Active user verification
- ✅ Self-notification prevention
- ✅ Graceful failure (doesn't break app)

---

## 3. Email Templates

### Location
`resources/views/emails/`

### Template Files

| Template | Purpose | Style |
|----------|---------|-------|
| `welcome.blade.php` | New user welcome | Blue gradient header |
| `forum-reply.blade.php` | Forum replies & quotes | Blue header, snippet preview |
| `forum-like.blade.php` | Forum post likes | Orange gradient header |
| `blog-comment.blade.php` | Blog comments & replies | Purple gradient header |
| `password-reset.blade.php` | Password reset requests | Red gradient header |
| `email-verification.blade.php` | Email verification | Green gradient header |
| `layout.blade.php` | Base email layout | Responsive HTML |

### Template Features
- 📱 **Responsive Design**: Works on desktop, tablet, and mobile
- 🎨 **Color-Coded**: Each email type has distinct styling
- 🔗 **Actionable**: Clear CTAs with direct links
- 🌐 **Internationalization-Ready**: Turkish text with structure for translation
- ♿ **Accessible**: Semantic HTML with proper contrast
- 💾 **Fallback URLs**: Copy-paste option for broken links

---

## 4. Integration Guide

### 4.1 Welcome Email (in `RegisteredUserController`)

```php
use App\Services\EmailService;

public function store(Request $request)
{
    // ... create user ...
    
    $user = User::create([/* ... */]);
    
    // Send welcome email
    app(EmailService::class)->sendWelcomeEmail($user);
    
    // ... rest of logic ...
}
```

### 4.2 Forum Notifications (in `ForumController`)

```php
use App\Services\EmailService;
use App\Models\ForumNotification;

// When posting a reply
$post = ForumPost::create([/* ... */]);

// Notify topic owner (database)
ForumNotification::notify($topic->user_id, 'reply', [
    'from_user_id'   => auth()->id(),
    'from_user_name' => auth()->user()->name,
    'post_id'        => $post->id,
    'topic_id'       => $topic->id,
]);

// Send email notification
$emailService = app(EmailService::class);
if ($topic->user && $topic->user_id !== auth()->id()) {
    $emailService->sendForumReplyEmail(
        $topic->user,
        auth()->user(),
        $topic,
        $post,
        'reply'
    );
}
```

### 4.3 Forum Likes (in `ForumController`)

```php
use App\Services\EmailService;

// When liking a post
if ($type === 'like' && $post->user_id !== $userId) {
    $emailService = app(EmailService::class);
    $emailService->sendForumLikeEmail(
        $post->user,
        auth()->user(),
        $post,
        $post->topic
    );
}
```

### 4.4 Blog Comments (in `BlogCommentController`)

```php
use App\Services\EmailService;

// When posting a comment
$comment = $post->comments()->create([/* ... */]);

// Notify post author
if (auth()->check() && $post->user_id !== auth()->id()) {
    app(EmailService::class)->sendBlogCommentEmail(
        $post->user,
        $post,
        $comment,
        'new_comment'
    );
}

// Notify parent comment author (if reply)
if (!empty($validated['parent_id']) && auth()->check()) {
    $parentComment = BlogComment::find($validated['parent_id']);
    if ($parentComment && $parentComment->user_id !== auth()->id()) {
        app(EmailService::class)->sendBlogCommentEmail(
            $parentComment->user,
            $post,
            $comment,
            'reply'
        );
    }
}
```

---

## 5. Configuration

### Environment Variables (.env)
```env
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="noreply@askeribilgiler.com"
MAIL_FROM_NAME="AskeriPlatform"

# Optional: Enable/disable email notifications
MAIL_ENABLED=true
```

### Config (config/mail.php)
Already configured by Laravel. Update if needed:
```php
'enabled' => env('MAIL_ENABLED', true),
```

---

## 6. Email Testing

### Local Development (Mailtrap)
1. Create free account at https://mailtrap.io
2. Get SMTP credentials
3. Update `.env` with credentials
4. Test emails appear in Mailtrap inbox

### Testing in Code
```php
use App\Services\EmailService;
use App\Models\User;

$user = User::first();
$emailService = app(EmailService::class);

// Test welcome email
$emailService->sendWelcomeEmail($user);

// Check logs for errors
tail -f storage/logs/laravel.log
```

### Queue Testing (Optional)
If using queues for email:
```php
// In config/queue.php
'default' => env('QUEUE_CONNECTION', 'database'),

// Run queue worker
php artisan queue:work
```

---

## 7. Email Customization

### Changing Email Content

#### Edit Template
```html
<!-- resources/views/emails/welcome.blade.php -->
<p>Customize your message here...</p>
```

#### Change Colors
Search for color values in templates:
- Blue: `#2563eb`
- Purple: `#8b5cf6`
- Orange: `#f59e0b`
- Red: `#ef4444`
- Green: `#10b981`

#### Modify Mail Class Subject
```php
// app/Mail/WelcomeMail.php
public function envelope(): Envelope
{
    return new Envelope(
        subject: 'Custom Subject Here',
    );
}
```

---

## 8. Troubleshooting

### Emails Not Sending

**Problem:** Emails not arriving
```
Solution:
1. Check MAIL_MAILER setting in .env
2. Verify SMTP credentials
3. Check logs: tail -f storage/logs/laravel.log
4. Test SMTP connection manually
5. Check EmailService::shouldSendEmail() logic
```

**Problem:** User not active
```
Solution:
Check if user.status = 'active'
Update: User::find($id)->update(['status' => 'active']);
```

**Problem:** SMTP connection error
```
Solution:
1. Verify MAIL_HOST, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD
2. For Gmail: Use app-specific passwords (not regular password)
3. For Mailtrap: Use correct port (usually 2525)
4. Disable SSL if using TLS
```

---

## 9. Best Practices

### ✅ DO
- Use EmailService for all emails (centralized)
- Log all email failures
- Always include unsubscribe links (future feature)
- Test emails in development
- Use descriptive subjects
- Include action links in emails
- Check user preferences before sending

### ❌ DON'T
- Send spam (respect user preferences)
- Include sensitive information in emails
- Send to unverified addresses
- Use plain text only (use HTML for better design)
- Forget error handling
- Send without proper SMTP configuration

---

## 10. Future Enhancements

### Planned Features
1. **Email Preferences Panel** — Let users opt-in/out of specific email types
2. **Email Templates Admin** — Customize templates via admin panel
3. **Email Logging** — Track all sent emails in database
4. **Batch Email Sending** — Newsletters and announcements
5. **Email Scheduling** — Digest emails, scheduled notifications
6. **Mobile App Integration** — Push notifications as alternative to email
7. **Unsubscribe Link** — Legal requirement for marketing emails
8. **Email Analytics** — Track opens, clicks, bounce rates
9. **A/B Testing** — Test different subject lines
10. **Dark Mode Support** — Email templates for dark mode

---

## 11. File Structure

```
app/
├── Mail/
│   ├── WelcomeMail.php
│   ├── ForumReplyMail.php
│   ├── ForumLikeMail.php
│   ├── BlogCommentMail.php
│   ├── PasswordResetMail.php
│   └── EmailVerificationMail.php
└── Services/
    └── EmailService.php

resources/views/
└── emails/
    ├── layout.blade.php
    ├── welcome.blade.php
    ├── forum-reply.blade.php
    ├── forum-like.blade.php
    ├── blog-comment.blade.php
    ├── password-reset.blade.php
    └── email-verification.blade.php
```

---

## 12. Implementation Checklist

- [x] 6 Mail classes created
- [x] 6 Email templates designed
- [x] EmailService with error handling
- [x] Responsive HTML emails
- [x] Color-coded email types
- [x] Turkish language support
- [x] Security best practices
- [x] Logging integration
- [x] User preference checks
- [x] Self-notification prevention
- [ ] Integration with ForumController (ready, needs activation)
- [ ] Integration with BlogCommentController (ready, needs activation)
- [ ] Integration with RegisteredUserController (ready, needs activation)
- [ ] SMTP configuration (manual setup)
- [ ] Testing in production

---

## 13. Quick Start

### 1. Setup SMTP
```bash
# Edit .env
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_FROM_ADDRESS="noreply@askeribilgiler.com"
```

### 2. Send Test Email
```php
use App\Services\EmailService;
use App\Models\User;

$user = User::first();
app(EmailService::class)->sendWelcomeEmail($user);
```

### 3. Check in Mailtrap
Visit https://mailtrap.io → check inbox

### 4. Integrate into Controllers
Add EmailService calls to:
- RegisteredUserController@store
- ForumController@storeReply
- ForumController@toggleLike
- BlogCommentController@store

---

## Summary

✅ **Complete Email System**
- 6 mail classes for different scenarios
- 6 beautifully designed HTML templates
- Centralized EmailService with error handling
- Turkish language support
- Responsive design for all devices
- Security-focused best practices
- Ready for SMTP configuration
- Extensible architecture for future features

Ready to deploy! 🚀
