# Email-to-Chapter Setup Guide

This guide explains how to configure the email processing system for BookDash.

## Overview

Users can create chapters by sending emails to their unique email addresses. The system:
1. Receives emails at `noreply@classiccitylegal.com` (forwarded from user unique emails)
2. Processes emails via IMAP every 5 minutes
3. Creates chapters from email content
4. Deducts credits automatically

## Prerequisites

- PHP IMAP extension enabled
- Access to `mail.classiccitylegal.com` IMAP server
- Email forwarding configured to `noreply@classiccitylegal.com`

## Configuration

### 1. Enable PHP IMAP Extension

**For XAMPP on Windows:**
1. Open `php.ini` (usually in `C:\xampp\php\php.ini`)
2. Find the line `;extension=imap`
3. Remove the semicolon to uncomment: `extension=imap`
4. Restart Apache

**For Linux/Mac:**
```bash
# Ubuntu/Debian
sudo apt-get install php-imap

# CentOS/RHEL
sudo yum install php-imap

# Restart web server
sudo service apache2 restart  # or nginx/php-fpm
```

### 2. Configure Environment Variables

Add these to your `.env` file:

```env
# IMAP Configuration for Inbound Emails
IMAP_HOST=mail.classiccitylegal.com
IMAP_PORT=993
IMAP_USERNAME=noreply@classiccitylegal.com
IMAP_PASSWORD=your_password_here
IMAP_ENCRYPTION=ssl
IMAP_VALIDATE_CERT=true
```

### 3. Test IMAP Connection

Run the email processor manually to test:

```bash
php artisan emails:process-inbound
```

You should see output like:
```
Connecting to email server...
Found 3 new email(s). Processing...
✓ Created chapter 'Chapter One' in book 'My Novel'
Successfully processed 3 email(s).
```

## Email Forwarding Setup

### On Your Email Server (ClassicCityLegal.com)

Create forwarding rules to redirect user unique emails to the processing inbox:

**Option 1: Wildcard Forwarding (Recommended)**
- Forward all `user-*@classiccitylegal.com` → `noreply@classiccitylegal.com`

**Option 2: Individual Forwarding**
- As users generate unique emails, add forwarding rules for each

## Scheduled Processing

The system automatically processes emails every 5 minutes via Laravel's task scheduler.

### Windows (XAMPP)

**Option A: Task Scheduler (Recommended)**
1. Open Windows Task Scheduler
2. Create New Task:
   - **Name:** BookDash Email Processor
   - **Trigger:** Every 5 minutes, indefinitely
   - **Action:** Start a program
   - **Program:** `C:\xampp\php\php.exe`
   - **Arguments:** `artisan schedule:run`
   - **Start in:** `C:\xampp\htdocs\bookdash`

**Option B: Continuous Script**
Create `email-processor.bat` in your project root:
```batch
@echo off
:loop
php artisan emails:process-inbound
timeout /t 300 /nobreak
goto loop
```

Run this script in a persistent command window or as a scheduled task.

### Linux/Mac

Add to crontab:
```bash
crontab -e
```

Add this line:
```
* * * * * cd /path/to/bookdash && php artisan schedule:run >> /dev/null 2>&1
```

This runs Laravel's scheduler every minute, which executes the email processor every 5 minutes.

## How It Works

### User Workflow

1. User clicks "Generate Email" in their dashboard
2. System creates unique email like `user-123-abc@classiccitylegal.com`
3. User sends email to this address with:
   - **Subject:** `Book Title – Chapter Name` (or just `Chapter Name`)
   - **Body:** Chapter content
4. Email forwards to `noreply@classiccitylegal.com`
5. System processes email every 5 minutes
6. Chapter created automatically

### Email Format

**Subject Line:**
- `My Novel – Chapter One` → Creates/finds book "My Novel", creates chapter "Chapter One"
- `Chapter One` → Creates chapter in user's latest book

**Body:**
- Plain text content becomes chapter content
- Email signatures and quoted text are automatically removed

### Processing Logic

1. Connect to IMAP mailbox (`noreply@classiccitylegal.com`)
2. Fetch unread emails
3. For each email:
   - Extract sender, recipient (unique email), subject, body
   - Find user by unique email
   - Check credit balance
   - Parse book/chapter from subject
   - Create or find book
   - Deduct 1 credit
   - Create chapter with email content
   - Mark email as read
   - Log in `email_logs` table

## Troubleshooting

### IMAP Connection Fails

**Error:** "Failed to connect to IMAP server"

**Solutions:**
1. Verify PHP IMAP extension is enabled: `php -m | grep imap`
2. Check credentials in `.env`
3. Test port connectivity: `telnet mail.classiccitylegal.com 993`
4. Try disabling certificate validation: `IMAP_VALIDATE_CERT=false`

### Emails Not Processing

**Check:**
1. Run manually: `php artisan emails:process-inbound`
2. Check Laravel logs: `storage/logs/laravel.log`
3. Verify forwarding is working (check noreply inbox manually)
4. Confirm scheduler is running: `php artisan schedule:list`

### User Not Found

**Error:** "User not found for email: user-123-abc@..."

**Causes:**
- User hasn't generated unique email yet
- Wrong email address
- Database issue

**Fix:**
- Have user generate email via dashboard
- Verify email pattern matches: `user-{id}-{hash}@classiccitylegal.com`

### Insufficient Credits

**Error:** "Insufficient credits"

- User needs to purchase credits before emailing chapters
- Each email chapter costs 1 credit

## Monitoring

### View Email Logs

Check the `email_logs` table:
```sql
SELECT * FROM email_logs ORDER BY created_at DESC LIMIT 10;
```

### Check Scheduler Status

```bash
# View scheduled tasks
php artisan schedule:list

# Test schedule without waiting
php artisan schedule:run
```

### View Laravel Logs

```bash
tail -f storage/logs/laravel.log
```

## Security Considerations

1. **IMAP Credentials:** Store securely in `.env`, never commit to git
2. **Email Validation:** System validates unique email format to prevent abuse
3. **Credit Check:** Users must have credits before chapters are created
4. **Rate Limiting:** 5-minute intervals prevent excessive server load
5. **Email Sanitization:** Signatures and quoted text removed automatically

## Advanced Configuration

### Change Processing Interval

Edit `routes/console.php`:
```php
// Every 10 minutes
Schedule::command('emails:process-inbound')->everyTenMinutes();

// Every hour
Schedule::command('emails:process-inbound')->hourly();

// Every minute (not recommended)
Schedule::command('emails:process-inbound')->everyMinute();
```

### Custom Email Parsing

Edit `app/Console/Commands/ProcessInboundEmails.php`:
- Modify `extractRecipientEmail()` for different forwarding formats
- Update `cleanEmailBody()` for custom signature removal
- Adjust subject parsing in `processEmail()` for different title formats

### Logging Verbosity

Add more logging in the command:
```php
use Illuminate\Support\Facades\Log;

Log::info('Processing email', [
    'from' => $from,
    'to' => $to,
    'subject' => $subject
]);
```

## Testing

### Manual Test

1. Generate unique email for a test user
2. Send test email:
   ```
   To: user-1-abc123@classiccitylegal.com
   Subject: Test Book – Test Chapter
   Body: This is my test chapter content.
   ```
3. Wait for forwarding (or manually forward to noreply)
4. Run: `php artisan emails:process-inbound`
5. Check database for new chapter
6. Verify credit deduction

### Automated Testing

Create a test script:
```php
// tests/Feature/EmailProcessingTest.php
public function test_email_creates_chapter()
{
    // Send test email
    // Run processor
    // Assert chapter created
    // Assert credit deducted
}
```

## Support

For issues:
1. Check `storage/logs/laravel.log`
2. Review `email_logs` table for processing status
3. Test IMAP connection manually
4. Verify email forwarding rules
