# SMS Fallback System

## Overview

The SMS fallback system automatically sends email alerts to the admin when SMS notifications fail for critical operations like withdrawals and exchanges. This ensures that important notifications are never missed even if the SMS service is down or misconfigured.

## How It Works

### 1. Enhanced SMS Service

The `SmsService` class now includes a new method `sendWithEmailFallback()` that:
- First attempts to send the SMS using the regular `send()` method
- If SMS fails, automatically sends an email alert to the admin
- Logs all attempts and failures for debugging
- Returns detailed information about both SMS and email attempts

### 2. Email Fallback Process

When an SMS fails:
1. The system logs the failure with full context
2. Retrieves the admin email from settings (`admin_alert_email`)
3. Sends a detailed email notification using the `sms-failure-alert` template
4. Includes all relevant information about the failed SMS and customer context

### 3. Updated Controllers

The following controllers now use the fallback system for critical notifications:

#### DashboardController
- **Withdrawal requests**: User SMS confirmations and admin alerts
- Uses context: user details, amount, reference, Alipay account

#### ExchangeController  
- **Exchange orders**: Admin SMS alerts for new orders
- Uses context: user details, order number, amounts, exchange rate

#### AdminController
- **Withdrawal approvals**: User SMS notifications
- **Withdrawal rejections**: User SMS notifications  
- **Exchange completions**: User SMS notifications
- Uses context: user details, amounts, references, reasons

## Email Template

The system uses a professional email template (`emails.sms-failure-alert`) that includes:

### Alert Header
- Clear warning about SMS failure
- Urgency indicator

### SMS Details Table
- Recipient phone number
- Message type (withdrawal_request, exchange_completed, etc.)
- SMS provider used
- Specific error message
- Timestamp

### Original Message
- Full text of the failed SMS in a code block
- Easy to copy for manual sending

### Context Information
- User details (name, email)
- Transaction details (amounts, references)
- Any additional relevant data

### Action Items
- Check SMS configuration
- Verify provider credentials
- Contact customer directly
- Review provider logs

### Quick Actions
- Direct link to admin settings panel

## Configuration

### Required Settings

Ensure these settings are configured in the admin panel:

```
admin_alert_email    - Email address to receive fallback notifications
sms_provider        - Your SMS provider (bulksmsghana or smsonlinegh)  
bulksms_api_key     - Your SMS API key
bulksms_sender_id   - Your SMS sender ID
```

### Email Settings

The fallback system requires working email configuration:

```
email_provider      - Your email provider (smtp, mailjet, brevo, phpmailer)
email_from_address  - From email address
email_from_name     - From name
[provider_credentials] - Specific credentials for your email provider
```

## Usage Examples

### Basic Usage
```php
$smsService = new \App\Services\SmsService();
$result = $smsService->sendWithEmailFallback(
    $phone, 
    $message, 
    'withdrawal_request',
    ['user_name' => $user->name, 'amount' => $amount]
);
```

### Response Handling
```php
if ($result['success']) {
    // SMS sent successfully
    Log::info('SMS sent successfully');
} else {
    // SMS failed, check if email fallback was sent
    if (isset($result['email_fallback_sent'])) {
        Log::warning('SMS failed but admin notified via email');
    }
}
```

## Message Types

The system recognizes these message types for better categorization:

- `withdrawal_request` - User withdrawal requests
- `withdrawal_approved` - Withdrawal approvals
- `withdrawal_rejected` - Withdrawal rejections
- `exchange_completed` - Completed exchange orders
- `admin_withdrawal_alert` - Admin alerts for withdrawals
- `admin_exchange_alert` - Admin alerts for exchanges

## Logging

All SMS attempts and failures are logged with full context:

```
Log Level: WARNING
Message: "SMS failed, sending email fallback to admin"
Context: phone, message, type, sms_error, context
```

```
Log Level: INFO  
Message: "Email fallback sent successfully"
Context: admin_email, type, phone
```

```
Log Level: ERROR
Message: "Failed to send email fallback" 
Context: error, phone, type
```

## Troubleshooting

### SMS Failures
1. Check SMS provider credentials in admin settings
2. Verify account balance with SMS provider
3. Test SMS configuration using admin panel test feature
4. Review Laravel logs for detailed error messages

### Email Fallback Failures
1. Verify admin email address is configured
2. Check email provider configuration
3. Test email settings using admin panel
4. Ensure email templates exist and are accessible

### Common Issues

**No admin email configured**
- Set `admin_alert_email` in admin settings
- Verify email address is valid

**Email template not found**
- Ensure `resources/views/emails/sms-failure-alert.blade.php` exists
- Check file permissions

**Both SMS and email fail**
- Check internet connectivity
- Verify all provider credentials
- Review Laravel error logs

## Benefits

1. **Zero missed notifications** - Critical alerts always reach admin
2. **Detailed failure information** - Full context for troubleshooting
3. **Professional presentation** - Clean, actionable email format
4. **Automatic fallback** - No manual intervention required
5. **Complete audit trail** - All attempts logged for analysis
6. **Customer context** - Full details for manual follow-up

## Security Considerations

- Email fallback contains sensitive customer information
- Ensure admin email account is secure
- Email templates escape all user input
- Logs contain phone numbers and amounts (review log retention policies)
- Consider encrypting sensitive data in email content

## Future Enhancements

Potential improvements to consider:

1. **Multiple admin emails** - Send to multiple administrators
2. **SMS retry logic** - Attempt SMS multiple times before fallback
3. **Alternative SMS providers** - Automatic failover between providers
4. **Push notifications** - Mobile app notifications for admins
5. **Slack/Discord integration** - Team chat notifications
6. **Dashboard alerts** - In-app notification system