# Email Configuration Module - Installation Guide

## Overview

This document provides all necessary information for integrating the Email Configuration Module into your existing SSHIA Laravel application. Follow these steps to ensure proper installation and configuration.

---

## Requirements

### PHP Extensions Required

The following PHP extensions are required for the Email Configuration Module:

| Extension | Purpose | Installation |
|-----------|---------|--------------|
| **openssl** | SSL/TLS encryption for SMTP/IMAP | Usually enabled by default |
| **imap** | IMAP email receiving functionality | `apt-get install php-imap` |
| **mbstring** | Multi-byte string handling | Usually enabled by default |

### Laravel Requirements

- Laravel 12+
- PHP 8.2 or 8.3
- MySQL 5.7+

---

## Installation Steps

### Step 1: Copy Module Files

Copy the following directories to your Laravel application:

```
email-configuration-module/
├── app/
│   ├── Http/
│   │   ├── Controllers/
│   │   │   └── EmailConfigurationController.php    → app/Http/Controllers/
│   │   └── Requests/
│   │       └── EmailConfigurationRequest.php       → app/Http/Requests/
│   ├── Models/
│   │   ├── EmailConfiguration.php                  → app/Models/
│   │   └── EmailLog.php                            → app/Models/
│   └── Services/
│       ├── ConfigurationService.php                → app/Services/
│       ├── EmailProvider.php                       → app/Services/
│       └── EmailService.php                        → app/Services/
├── database/
│   ├── migrations/
│   │   ├── *_create_email_configurations_table.php → database/migrations/
│   │   └── *_create_email_logs_table.php           → database/migrations/
│   └── seeders/
│       └── EmailConfigurationPermissionSeeder.php  → database/seeders/
├── routes/
│   └── email.php                                   → routes/email.php
└── resources/views/config/email/
    ├── index.blade.php                             → resources/views/config/email/
    ├── form.blade.php                              → resources/views/config/email/
    ├── logs.blade.php                              → resources/views/config/email/
    └── documentation.blade.php                     → resources/views/config/email/
```

### Step 2: Register Routes

Add the email routes to your main routes file (usually `routes/web.php`):

```php
// Include email configuration routes
require __DIR__ . '/email.php';
```

Or add the route group directly:

```php
Route::middleware(['auth', 'role:Super Manager'])
    ->prefix('config/email')
    ->name('config.email.')
    ->group(function () {
        // Include all email configuration routes
    });
```

### Step 3: Register Service Provider (Optional)

If you want to register the EmailService as a singleton, add to `app/Providers/AppServiceProvider.php`:

```php
use App\Services\EmailService;
use App\Services\ConfigurationService;
use App\Services\EmailProvider;

public function register(): void
{
    $this->app->singleton(ConfigurationService::class);
    $this->app->singleton(EmailProvider::class);
    $this->app->singleton(EmailService::class);
}
```

### Step 4: Run Migrations

Run the database migrations to create the required tables:

```bash
php artisan migrate
```

### Step 5: Seed Permissions

Run the permission seeder to create required permissions:

```bash
php artisan db:seed --class=EmailConfigurationPermissionSeeder
```

### Step 6: Clear Cache

Clear all caches after installation:

```bash
php artisan optimize:clear
```

---

## Environment Variables

Add the following variables to your `.env` file (optional - for default configuration):

```env
# SMTP Configuration
MAIL_SMTP_HOST=
MAIL_SMTP_PORT=587
MAIL_SMTP_USERNAME=
MAIL_SMTP_PASSWORD=
MAIL_SMTP_ENCRYPTION=tls

# IMAP Configuration
MAIL_IMAP_HOST=
MAIL_IMAP_PORT=993
MAIL_IMAP_USERNAME=
MAIL_IMAP_PASSWORD=
MAIL_IMAP_ENCRYPTION=ssl

# Sender Information
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME="${APP_NAME}"
```

Update `.env.example` with the same variables for documentation.

---

## Navigation Integration

Add the email configuration link to your navigation menu (`resources/views/layouts/navigation.blade.php`):

```blade
@can('manage email configuration')
    <x-nav-link :href="route('config.email.index')" :active="request()->routeIs('config.email.*')">
        <i class="fas fa-envelope mr-2"></i>
        {{ __('Email Configuration') }}
    </x-nav-link>
@endcan
```

For the sidebar, add under a Configuration section:

```blade
@can('manage email configuration')
    <x-sidebar-link :href="route('config.email.index')" :active="request()->routeIs('config.email.*')">
        <i class="fas fa-envelope mr-3"></i>
        {{ __('Email Configuration') }}
    </x-sidebar-link>
@endcan
```

---

## PHP IMAP Extension

If the IMAP extension is not installed, install it:

### Ubuntu/Debian
```bash
sudo apt-get update
sudo apt-get install php8.2-imap  # or php8.3-imap
sudo service apache2 restart      # or nginx restart
```

### CentOS/RHEL
```bash
sudo yum install php-imap
sudo service httpd restart
```

### macOS (Homebrew)
```bash
brew install php@8.2
```

### Verify Installation
```bash
php -m | grep imap
```

---

## Troubleshooting

### Common Issues

#### 1. "Class 'IMAP' not found" Error
- **Cause**: PHP IMAP extension not installed
- **Solution**: Install the PHP IMAP extension as described above

#### 2. Permission Denied (403)
- **Cause**: User doesn't have required permissions
- **Solution**: Run the permission seeder and ensure user has 'manage email configuration' permission

#### 3. "No active email configuration" Error
- **Cause**: Email configuration not set up
- **Solution**: Access `/config/email/create` to create a configuration

#### 4. SMTP Connection Failed
- **Cause**: Incorrect host/port/credentials
- **Solution**: Verify SMTP settings with your email provider

#### 5. Gmail SMTP Not Working
- **Cause**: Gmail requires App Password for SMTP
- **Solution**: 
  1. Enable 2-Factor Authentication on Gmail
  2. Generate an App Password at https://myaccount.google.com/apppasswords
  3. Use the App Password instead of your regular password

---

## Testing

After installation, test the module:

1. Log in as Super Manager
2. Navigate to `/config/email`
3. Create a new configuration
4. Test SMTP connection
5. Send a test email
6. View email logs

---

## Dependencies

This module requires the following packages (already included in SSHIA Laravel):

| Package | Version | Purpose |
|---------|---------|---------|
| Laravel Framework | 12.x | Core framework |
| spatie/laravel-permission | 6.24+ | Role and permission management |
| illuminate/support | 12.x | Laravel support helpers |

No additional composer packages are required.

---

## Security Considerations

1. **Credential Encryption**: All usernames and passwords are encrypted using Laravel's encryption
2. **Role-Based Access**: Only Super Manager role can access email configuration
3. **Password Masking**: Passwords are never exposed in API responses or views
4. **CSRF Protection**: All forms include CSRF tokens
5. **XSS Prevention**: Input sanitization on all text fields

---

## Support

For issues or questions regarding this module:

1. Review the documentation at `/config/email/documentation`
2. Check the email logs at `/config/email/logs`
3. Review the source code in `app/Services/` directory

---

## Version History

| Version | Date | Changes |
|---------|------|---------|
| 1.0.0 | 2024-01-01 | Initial release |

---

## License

This module is part of the SSHIA Laravel System and follows the same license terms.
