# Email-to-Task Integration

## Overview

The Email-to-Task system allows users to create tasks by sending emails to `tasks@firmly.webiton.pt`. This provides seamless integration with Outlook and other email clients.

## Features

- ✅ **IMAP Email Processing** - Automatically checks emails from tasks@firmly.webiton.pt
- ✅ **Smart Email Parsing** - Extracts task details from email content
- ✅ **Automatic Task Creation** - Creates tasks in the CRM system
- ✅ **Email Confirmations** - Sends confirmation back to the sender
- ✅ **Metadata Extraction** - Parses priority, due dates, matter references, etc.

## Setup

### 1. Email Account Configuration

Set up the email account `tasks@firmly.webiton.pt` with your email provider.

### 2. Environment Variables

Add these to your `.env` file:

```env
# Email-to-Task Configuration
TASK_EMAIL_HOST=imap.gmail.com
TASK_EMAIL_PORT=993
TASK_EMAIL_ENCRYPTION=ssl
TASK_EMAIL_USERNAME=tasks@firmly.webiton.pt
TASK_EMAIL_PASSWORD=your_email_app_password
TASK_EMAIL_VALIDATE_CERT=true
```

### 3. Gmail Setup (if using Gmail)

1. **Enable 2-Factor Authentication** on the Gmail account
2. **Generate App Password**:
   - Go to Google Account Settings
   - Security → 2-Step Verification → App passwords
   - Generate password for "Mail"
   - Use this password in `TASK_EMAIL_PASSWORD`

### 4. Run Database Migration

```bash
php artisan migrate
```

### 5. Test the Setup

```bash
# Test configuration (dry run)
php artisan email:process-tasks --dry-run

# Process emails for real
php artisan email:process-tasks
```

## Usage Examples

### Basic Task Creation

**Email:**
```
To: tasks@firmly.webiton.pt
Subject: Review client contract
Body: Need to review the new client contract for Johnson & Associates
```

**Result:** Creates a task with title "Review client contract"

### Advanced Task with Metadata

**Email:**
```
To: tasks@firmly.webiton.pt
Subject: [HIGH] Prepare court documents - Due: 2025-08-10
Body: 
Prepare all court documents for the Johnson case.

Priority: high
Due: 2025-08-10
Matter: 123
Hours: 4
Assign: lawyer@ccsllegal.com

Details:
- Gather evidence files
- Draft motion
- Review with senior partner
```

**Result:** Creates a high-priority task with due date, assigned to specific lawyer

### Email Format Options

#### Priority Indicators
- `[URGENT]` or `Priority: urgent` → urgent priority
- `[HIGH]` or `Priority: high` → high priority  
- `[LOW]` or `Priority: low` → low priority
- Default → medium priority

#### Due Dates
- `Due: 2025-08-10`
- `Deadline: 2025-08-10`
- `By: 2025-08-10`
- `- Due: 2025-08-10` (in subject)

#### Matter References
- `Matter: 123`
- `#matter123`
- `Matter #123`

#### Assignment
- `Assign: user@domain.com`

#### Estimated Hours
- `Hours: 4`
- `Hour: 2`

#### Start Date
- `Start: 2025-08-05`

## Automation

### Scheduled Processing

Add to your cron jobs to process emails every 5 minutes:

```bash
# In your crontab or Laravel scheduler
*/5 * * * * cd /path/to/your/app && php artisan email:process-tasks
```

### Laravel Scheduler

Add to `app/Console/Kernel.php`:

```php
protected function schedule(Schedule $schedule)
{
    $schedule->command('email:process-tasks')
             ->everyFiveMinutes()
             ->withoutOverlapping();
}
```

## Email Templates

### Confirmation Email

When a task is created, the user receives a confirmation email:

```
Hi [User Name],

Your task has been created successfully!

Task Details:
- Title: Review client contract
- Priority: High
- Due Date: 2025-08-10
- Matter: Johnson Case

View/Edit Task: https://firmly.webiton.pt/tasks/[task-uuid]/edit

Best regards,
Firmly CRM System
```

## Outlook Integration

### Method 1: Direct Email

Users can simply email `tasks@firmly.webiton.pt` from Outlook with task details.

### Method 2: Outlook Quick Steps

Create Outlook Quick Steps for common task types:

1. **High Priority Task**
   - Template: `[HIGH] [Task Title] - Due: [Date]`
   - To: `tasks@firmly.webiton.pt`

2. **Client Work Task**
   - Template: `[Client Work] [Task Title]`
   - Body includes: `Category: client-work`

### Method 3: Outlook Rules

Set up Outlook rules to automatically forward certain emails to `tasks@firmly.webiton.pt`.

## Security Considerations

1. **Email Authentication**: Only emails from registered users create tasks
2. **IMAP Security**: Use SSL/TLS encryption
3. **App Passwords**: Use app-specific passwords, not account passwords
4. **Access Control**: Users can only create tasks they have permission for

## Troubleshooting

### Common Issues

1. **"IMAP client not available"**
   - Check email configuration
   - Verify IMAP credentials
   - Ensure IMAP is enabled on email account

2. **"User not found"**
   - Email sender must be a registered user in the CRM
   - Check email address matches exactly

3. **Authentication failed**
   - Use app-specific password for Gmail
   - Check IMAP settings
   - Verify SSL/TLS configuration

### Debug Commands

```bash
# Test email processing
php artisan email:process-tasks --dry-run

# Check logs
tail -f storage/logs/laravel.log | grep -i "email\|task"

# Test IMAP connection
php artisan tinker
>>> $service = new \App\Services\EmailToTaskService();
>>> $service->processTaskEmails();
```

## Advanced Features

### Email Parsing Rules

The system intelligently parses email content:

- **Subject Cleaning**: Removes RE:, FW:, and other prefixes
- **Priority Detection**: Recognizes priority indicators
- **Date Extraction**: Finds due dates in various formats
- **Metadata Removal**: Cleans email signatures and footers
- **Smart Assignment**: Recognizes user email addresses for task assignment

### Integration with Existing Features

- **Matter Association**: Links tasks to specific matters
- **User Permissions**: Respects existing user permissions
- **Task Categories**: Automatically categorizes tasks when possible
- **Notifications**: Integrates with existing notification system

## Future Enhancements

1. **Microsoft Graph Integration**: Direct integration with Outlook via API
2. **Email Templates**: Predefined email templates for common task types
3. **Attachment Processing**: Handle email attachments as task attachments
4. **Reply Processing**: Update tasks via email replies
5. **Bulk Operations**: Process multiple tasks from a single email

## Support

For issues or questions:

1. Check the logs: `storage/logs/laravel.log`
2. Verify email configuration
3. Test with simple email first
4. Ensure user exists in the system
