# Twilio SMS Module

## Overview
The Twilio module provides SMS functionality for the Seraph3 application using Twilio's SMS API. This module follows the Laravel module pattern and provides a clean, maintainable interface for sending SMS messages.

## Features

- **SMS Sending**: Send SMS messages to phone numbers
- **Task Integration**: Send SMS with task context and logging
- **Completion Notifications**: Automatic SMS notifications for task completion
- **Phone Number Validation**: Validate and format phone numbers
- **Delivery Status**: Check SMS delivery status
- **SMS History**: Retrieve SMS history with filtering
- **Account Management**: Get Twilio account information and available numbers
- **Testing**: Comprehensive testing tools and commands

## Installation

### 1. Environment Configuration

Add the following environment variables to your `.env` file:

```env
# Twilio Configuration
TWILIO_SID=your_twilio_account_sid
TWILIO_TOKEN=your_twilio_auth_token
TWILIO_FROM=+1234567890
TWILIO_BASE_URL=https://api.twilio.com
TWILIO_TIMEOUT=30
TWILIO_LOG_LEVEL=info
TWILIO_CACHE_TTL=3600
TWILIO_COMPLETION_MESSAGE=Thank you for choosing our services!
```

### 2. Database Settings

Configure the following settings in your database:

```sql
-- Enable Twilio integration
UPDATE settings SET value = '1' WHERE name = 'integrations.twilio.enabled';

-- Set Twilio credentials
UPDATE settings SET value = 'your_account_sid' WHERE name = 'integrations.twilio.account_sid';
UPDATE settings SET value = 'your_auth_token' WHERE name = 'integrations.twilio.auth_token';
UPDATE settings SET value = '+1234567890' WHERE name = 'integrations.twilio.from_number';

-- Enable SMS notifications
UPDATE settings SET value = '1' WHERE name = 'notifications.sms_enabled';
```

### 3. Service Provider Registration

The module is automatically registered via the `TwilioServiceProvider`. Ensure it's included in your `config/app.php`:

```php
'providers' => [
    // ... other providers
    'App\Modules\Twilio\TwilioServiceProvider',
],
```

## Usage

### Service Injection

```php
use App\Modules\Twilio\Services\TwilioServiceInterface;

class YourController extends Controller
{
    public function __construct(TwilioServiceInterface $twilioService)
    {
        $this->twilioService = $twilioService;
    }

    public function sendSMS()
    {
        $result = $this->twilioService->sendSMS(
            '+1234567890',
            'Hello from Seraph3!'
        );

        if ($result['success']) {
            // SMS sent successfully
            $messageSid = $result['message_sid'];
        }
    }
}
```

### API Endpoints

#### Send SMS
```http
POST /api/v1/twilio/send
Content-Type: application/json

{
    "to": "+1234567890",
    "message": "Hello from Seraph3!",
    "from": "+0987654321" // optional
}
```

#### Test SMS
```http
POST /api/v1/twilio/test
Content-Type: application/json

{
    "to": "+1234567890",
    "message": "Test message"
}
```

#### Send Task SMS
```http
POST /api/v1/tasks/{taskId}/sms
Content-Type: application/json

{
    "send_to": "+1234567890",
    "message": "Task update"
}
```

#### Get Delivery Status
```http
GET /api/v1/twilio/status/{messageSid}
```

#### Get SMS History
```http
GET /api/v1/twilio/history?from=+1234567890&limit=10
```

#### Validate Phone Number
```http
POST /api/v1/twilio/validate-phone
Content-Type: application/json

{
    "phone_number": "+1234567890"
}
```

### Console Commands

#### Test SMS
```bash
docker-compose exec app php artisan twilio:test-sms +1234567890 "Test message"
```

## Configuration

### SMS Settings

- **Max Length**: 1600 characters per SMS
- **Default From**: Configured via `TWILIO_FROM` environment variable
- **Completion Message**: Customizable completion message template

### Phone Number Formatting

- **Default Country**: GB (United Kingdom)
- **Default Prefix**: +44
- **Automatic Formatting**: Converts UK numbers starting with 0 to +44 format

### Delivery Status

- **Check Interval**: 5 minutes (configurable)
- **Max Retries**: 3 attempts

## Integration with Existing Code

### Task Completion Observer

The module integrates with the existing `TaskCompletionObserver` to send automatic SMS notifications when tasks are completed.

### Customer Notifications

All SMS messages are logged in the `customer_notifications` table with the following fields:
- `type`: 'sms'
- `sent_to`: Phone number
- `message`: SMS content
- `task_id`: Associated task ID
- `message_sid`: Twilio message SID
- `subject`: Notification subject

### Backward Compatibility

The module maintains backward compatibility with existing SMS functionality:
- Legacy route: `POST /api/v1/sms/send`
- Existing task SMS endpoints
- Current notification system

## Error Handling

The module provides comprehensive error handling:

- **Invalid Phone Numbers**: Validation and formatting
- **Twilio API Errors**: Proper error messages and logging
- **Configuration Errors**: Clear feedback for missing credentials
- **Network Issues**: Timeout and retry handling

## Logging

All operations are logged with the `[TWILIO]` prefix:

```php
Log::info("[TWILIO] SMS sent successfully", [
    'message_sid' => 'SM1234567890',
    'to' => '+1234567890'
]);
```

## Testing

### Unit Tests

```bash
docker-compose exec app php artisan test --filter=TwilioTest
```

### Manual Testing

```bash
# Test SMS functionality
docker-compose exec app php artisan twilio:test-sms +1234567890

# Test with custom message
docker-compose exec app php artisan twilio:test-sms +1234567890 "Custom test message"
```

## Troubleshooting

### Common Issues

1. **Invalid Credentials**
   - Check `TWILIO_SID` and `TWILIO_TOKEN` in `.env`
   - Verify credentials in Twilio dashboard

2. **Phone Number Format**
   - Ensure phone numbers are in international format
   - Use the validation endpoint to check formatting

3. **SMS Not Sending**
   - Check Twilio account status
   - Verify from number is approved
   - Check account balance

4. **Module Not Loading**
   - Ensure service provider is registered
   - Clear configuration cache: `php artisan config:clear`

### Debug Mode

Enable debug logging by setting:
```env
TWILIO_LOG_LEVEL=debug
```

## Security

- All credentials are stored securely in environment variables
- Phone numbers are validated and sanitized
- API responses are logged for audit purposes
- No sensitive data is exposed in logs

## Performance

- Singleton service binding for stateless operations
- Caching for account information
- Efficient phone number formatting
- Minimal API calls for status checks

## Contributing

When contributing to the Twilio module:

1. Follow the module pattern template
2. Add comprehensive logging
3. Include proper error handling
4. Write unit tests for new features
5. Update documentation

## License

This module is part of the Seraph3 application and follows the same license terms. 