# Email Notification System Guide

## Overview

The Chitti Finserv email notification system provides automated email notifications for various user actions and loan application status updates. The system uses beautiful HTML templates and integrates with your existing SMTP configuration.

## Features

- **Welcome Emails**: Sent to new users upon registration
- **Loan Application Confirmations**: Sent when users submit loan applications
- **Status Update Notifications**: Sent when admin updates loan application status
- **Beautiful HTML Templates**: Responsive, modern email designs
- **Logo Integration**: Uses logo from configuration/splash object
- **SMTP Configuration**: Uses environment variables for SMTP settings
- **Admin Testing Tools**: Routes for testing and manual email sending

## Email Templates

### 1. Welcome Email (`welcome.html`)
- **Trigger**: User registration
- **Content**: Welcome message, account features, account details
- **Template Variables**:
  - `{{userName}}` - User's name
  - `{{userEmail}}` - User's email
  - `{{userPhone}}` - User's phone number
  - `{{createdDate}}` - Account creation date
  - `{{logoUrl}}` - Logo URL from configuration
  - `{{buttonText}}` - CTA button text
  - `{{buttonUrl}}` - CTA button URL

### 2. Loan Application Email (`loan-application.html`)
- **Trigger**: Loan application submission
- **Content**: Application confirmation, details, next steps
- **Template Variables**:
  - `{{userName}}` - User's name
  - `{{applicationId}}` - Loan application ID
  - `{{loanType}}` - Type of loan
  - `{{amount}}` - Loan amount (formatted)
  - `{{applicationDate}}` - Application submission date
  - `{{status}}` - Current application status
  - `{{logoUrl}}` - Logo URL from configuration
  - `{{buttonText}}` - CTA button text
  - `{{buttonUrl}}` - CTA button URL

### 3. Status Update Email (`status-update.html`)
- **Trigger**: Admin status update
- **Content**: Status change notification, application details, admin notes
- **Template Variables**:
  - `{{userName}}` - User's name
  - `{{statusIcon}}` - Status-specific emoji icon
  - `{{newStatus}}` - New status (uppercase)
  - `{{statusMessage}}` - Status-specific message
  - `{{applicationId}}` - Loan application ID
  - `{{loanType}}` - Type of loan
  - `{{amount}}` - Loan amount (formatted)
  - `{{oldStatus}}` - Previous status (uppercase)
  - `{{updatedDate}}` - Status update date
  - `{{adminNotes}}` - Admin notes (optional)
  - `{{statusSpecificTitle}}` - Status-specific title (optional)
  - `{{statusSpecificMessage}}` - Status-specific message (optional)
  - `{{logoUrl}}` - Logo URL from configuration
  - `{{buttonText}}` - CTA button text
  - `{{buttonUrl}}` - CTA button URL

### 4. Test Email (`test.html`)
- **Trigger**: Manual testing
- **Content**: Email service verification
- **Template Variables**:
  - `{{logoUrl}}` - Logo URL from configuration

## SMTP Configuration

The email service uses the following environment variables:

```env
SMTP_HOST=your-smtp-host.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=your-email@domain.com
SMTP_PASS=your-email-password
APP_URL=https://your-domain.com
```

### Supported SMTP Providers

- **Gmail**: Use Gmail SMTP settings
- **Outlook/Hotmail**: Use Outlook SMTP settings
- **Custom SMTP**: Any SMTP server with proper credentials
- **SendGrid**: Use SendGrid SMTP settings
- **Mailgun**: Use Mailgun SMTP settings

## API Endpoints

### Email Testing and Management

#### 1. Test Email Service
```http
POST /api/email/test
Authorization: Bearer <admin-token>
Content-Type: application/json

{
  "email": "test@example.com"
}
```

#### 2. Send Welcome Email
```http
POST /api/email/welcome/:userId
Authorization: Bearer <admin-token>
```

#### 3. Send Loan Application Email
```http
POST /api/email/loan-application/:applicationId
Authorization: Bearer <admin-token>
```

#### 4. Send Status Update Email
```http
POST /api/email/status-update/:applicationId
Authorization: Bearer <admin-token>
Content-Type: application/json

{
  "oldStatus": "pending",
  "newStatus": "approved",
  "adminNotes": "Application approved after document verification"
}
```

## Automatic Email Triggers

### 1. User Registration
- **Route**: `POST /api/auth/register`
- **Email**: Welcome email sent automatically
- **Error Handling**: Email failure doesn't affect registration

### 2. Loan Application Submission
- **Route**: `POST /api/loan-applications`
- **Email**: Loan application confirmation sent automatically
- **Error Handling**: Email failure doesn't affect application submission

### 3. Status Updates
- **Route**: `PUT /api/loan-applications/:id/status`
- **Email**: Status update notification sent automatically
- **Error Handling**: Email failure doesn't affect status update

## Logo Integration

The email system automatically fetches the logo from your configuration:

1. **Configuration Source**: `Configuration.findOne({ isActive: true })`
2. **Logo Path**: `config.splash.logo`
3. **URL Handling**: 
   - Full URLs are used as-is
   - Relative paths are prefixed with `APP_URL`
   - Fallback to default logo if not found

## Status-Specific Features

### Status Icons
- `pending`: ⏳
- `approved`: 🎉
- `rejected`: ❌
- `processing`: ⚙️
- `disbursed`: 💰

### Status Messages
Each status has specific messaging and styling:
- **Approved**: Green styling with congratulations message
- **Rejected**: Red styling with explanation message
- **Disbursed**: Green styling with fund transfer confirmation

## Error Handling

The email system includes comprehensive error handling:

1. **Template Loading**: Falls back to inline template if file not found
2. **SMTP Errors**: Logged but don't affect main functionality
3. **Logo Loading**: Falls back to default logo if configuration fails
4. **Email Sending**: Non-blocking - main operations continue even if email fails

## Testing

### 1. Test SMTP Configuration
```bash
curl -X POST http://localhost:5000/api/email/test \
  -H "Authorization: Bearer <admin-token>" \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com"}'
```

### 2. Test Welcome Email
```bash
curl -X POST http://localhost:5000/api/email/welcome/<user-id> \
  -H "Authorization: Bearer <admin-token>"
```

### 3. Test Loan Application Email
```bash
curl -X POST http://localhost:5000/api/email/loan-application/<application-id> \
  -H "Authorization: Bearer <admin-token>"
```

## Customization

### Adding New Email Types

1. **Create Template**: Add new HTML template in `templates/emails/`
2. **Add Service Method**: Add method in `services/emailService.js`
3. **Add Route**: Add route in `routes/email.js` (if needed)
4. **Integrate**: Call the service method where needed

### Modifying Templates

1. **Edit HTML**: Modify template files in `templates/emails/`
2. **Update Variables**: Ensure template variables match service data
3. **Test**: Use test endpoints to verify changes

### Styling

All templates use inline CSS for maximum email client compatibility:
- Responsive design
- Modern gradients and shadows
- Status-specific color schemes
- Mobile-friendly layouts

## Troubleshooting

### Common Issues

1. **SMTP Connection Failed**
   - Check SMTP credentials in `.env`
   - Verify SMTP host and port
   - Check firewall settings

2. **Logo Not Displaying**
   - Verify logo path in configuration
   - Check if logo file exists
   - Ensure `APP_URL` is set correctly

3. **Emails Not Sending**
   - Check server logs for SMTP errors
   - Verify email service is imported correctly
   - Test with `/api/email/test` endpoint

4. **Template Variables Not Replaced**
   - Check template variable names match service data
   - Verify template file exists
   - Check template loading in email service

### Debug Logging

The email service includes detailed logging:
- Template loading attempts
- SMTP connection status
- Email sending results
- Error details with stack traces

## Security Considerations

1. **Admin-Only Access**: Email testing routes require admin authentication
2. **Rate Limiting**: Email endpoints are subject to rate limiting
3. **Input Validation**: All email addresses are validated
4. **Error Handling**: Sensitive information is not exposed in error messages

## Performance

1. **Async Operations**: All email sending is asynchronous
2. **Non-Blocking**: Email failures don't affect main operations
3. **Template Caching**: Templates are loaded on-demand
4. **Connection Pooling**: SMTP connections are managed efficiently

## Future Enhancements

1. **Email Queue**: Implement queue system for high-volume sending
2. **Template Editor**: Admin interface for template editing
3. **Email Analytics**: Track email open rates and click-through rates
4. **SMS Integration**: Combine with SMS notifications
5. **Multi-language Support**: Support for multiple languages
6. **Email Preferences**: User-configurable email preferences 