# Twilio SMS Integration Guide

## Overview

This application now has full Twilio SMS integration for notifying clients and users. The system includes:

- ✅ Admin panel for configuring Twilio settings
- ✅ SMS template management
- ✅ Notification logging
- ✅ Automatic SMS sending for events
- ✅ WhatsApp support (optional)

## Database Tables

### 1. `sms_settings`
Stores Twilio configuration:
- `provider` - SMS provider (default: twilio)
- `twilio_sid` - Twilio Account SID
- `twilio_token` - Twilio Auth Token
- `twilio_phone_number` - Twilio phone number for SMS
- `twilio_whatsapp_number` - Twilio WhatsApp number (optional)
- `status` - Enable/disable SMS
- `use_whatsapp` - Use WhatsApp instead of SMS

### 2. `sms_templates`
Pre-configured SMS templates:
- `booking-confirmation` - Sent when booking is created
- `booking-reminder` - Sent before appointment (trigger manually)
- `booking-cancelled` - Sent when booking is cancelled
- `employee-welcome` - Sent when new employee is added
- `otp-verification` - Sent for OTP verification
- `password-reset` - Sent for password reset

### 3. `notification_logs`
Tracks all sent SMS:
- `user_id` - User who received the SMS
- `type` - sms, whatsapp, or email
- `template_slug` - Template used
- `recipient` - Phone number or email
- `message` - Message content
- `status` - pending, sent, or failed
- `error_message` - Error if failed

## Admin Panel Endpoints

All endpoints are at: `https://yourdomain.com/admin/sms-settings/{endpoint}`

### Get SMS Settings
```
GET /admin/sms-settings
```
Returns current SMS configuration.

### Update SMS Settings
```
POST /admin/sms-settings
```
**Request Body:**
```json
{
  "provider": "twilio",
  "twilio_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "twilio_token": "your_auth_token_here",
  "twilio_phone_number": "+1234567890",
  "twilio_whatsapp_number": "+14155238886",
  "status": true,
  "use_whatsapp": false
}
```

### Test Twilio Connection
```
POST /admin/sms-settings/test
```
**Request Body:**
```json
{
  "to": "+1234567890"
}
```
Sends a test SMS to verify configuration.

### Get SMS Templates
```
GET /admin/sms-settings/templates
```
Returns all SMS templates.

### Update SMS Template
```
PUT /admin/sms-settings/templates/{id}
```
**Request Body:**
```json
{
  "name": "Booking Confirmation",
  "content": "Hi {customer_name}, your booking is confirmed!",
  "status": true
}
```

### Get Notification Logs
```
GET /admin/sms-settings/logs?type=sms&status=sent
```
**Query Parameters:**
- `type` - Filter by type (sms, whatsapp, email)
- `status` - Filter by status (sent, failed, pending)
- `search` - Search by recipient
- `page` - Page number

### Get SMS Statistics
```
GET /admin/sms-settings/statistics
```
Returns SMS usage statistics.

## How to Use Twilio

### 1. Get Twilio Credentials

1. Sign up at https://www.twilio.com/
2. Go to Console → Settings → General Settings
3. Copy:
   - **Account SID**
   - **Auth Token**
4. Buy a phone number from Phone Numbers → Buy a Number
5. Copy the **Phone Number**

### 2. Configure in Admin Panel

Go to: `https://yourdomain.com/admin/sms-settings`

Update settings with your Twilio credentials:
```
Provider: twilio
Twilio SID: ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Twilio Token: your_auth_token_here
Phone Number: +1234567890
Status: Enabled
```

### 3. Test Configuration

Click "Test Connection" button and enter your phone number to receive a test SMS.

## SMS Templates

### Template Variables

Templates use `{variable}` syntax. Available variables:

**Booking Confirmation:**
- `{customer_name}` - Customer's name
- `{service_name}` - Service name
- `{booking_date}` - Booking date
- `{booking_time}` - Booking time
- `{company_name}` - Company name

**Booking Reminder:**
- `{customer_name}` - Customer's name
- `{service_name}` - Service name
- `{booking_date}` - Booking date
- `{booking_time}` - Booking time
- `{company_name}` - Company name

**Employee Welcome:**
- `{employee_name}` - Employee's name
- `{company_name}` - Company name
- `{job_title}` - Job title
- `{login_link}` - Login URL

**OTP Verification:**
- `{otp}` - One-time password
- `{expiry_minutes}` - OTP expiry in minutes

### Customizing Templates

1. Go to `/admin/sms-settings/templates`
2. Find the template you want to edit
3. Click "Edit"
4. Modify the content while keeping the `{variable}` placeholders
5. Save changes

## Programmatic Usage

### Send Custom SMS

```php
use App\Helpers\NotificationHelper;

$notificationHelper = new NotificationHelper();
$notificationHelper->sendCustomSms(
    '+1234567890',
    'Your custom message here',
    $userId // optional
);
```

### Send Booking Confirmation

```php
use App\Helpers\NotificationHelper;
use App\Models\Booking;

$booking = Booking::find(1);
$notificationHelper = new NotificationHelper();
$notificationHelper->sendBookingConfirmation($booking);
```

### Send Booking Reminder

```php
$notificationHelper->sendBookingReminder($booking);
```

### Send Employee Welcome

```php
use App\Models\User;

$employee = User::find(1);
$notificationHelper->sendEmployeeWelcome(
    $employee,
    'My Company',
    'Hair Stylist'
);
```

### Send OTP

```php
$user = auth()->user();
$otp = '123456';
$notificationHelper->sendOtp($user, $otp, 15);
```

## Integration Points

### 1. Booking Creation

In `BookingController@store`, after creating booking:
```php
use App\Helpers\NotificationHelper;

$notificationHelper = new NotificationHelper();
if ($notificationHelper->isSmsEnabled()) {
    $notificationHelper->sendBookingConfirmation($booking);
}
```

### 2. Booking Cancellation

In `BookingController@cancel`:
```php
$notificationHelper->sendBookingCancellation($booking);
```

### 3. Employee Creation

In `EmployeeController@store`:
```php
$notificationHelper->sendEmployeeWelcome(
    $user,
    auth()->user()->company->name,
    $request->job_title
);
```

### 4. OTP Generation

In `AuthenticationController@generateOtp`:
```php
$notificationHelper->sendOtp($user, $otp);
```

## WhatsApp Setup (Optional)

To use WhatsApp instead of SMS:

1. Get WhatsApp Sender ID from Twilio
2. Configure in admin settings:
   - Set `use_whatsapp` = true
   - Add your WhatsApp number to `twilio_whatsapp_number`
3. Template format changes to `whatsapp:{phone_number}`

## Cost Optimization

### Tips to Reduce SMS Costs:

1. **Use WhatsApp** - Cheaper than SMS in most countries
2. **Bundle Reminders** - Send daily summary instead of individual reminders
3. **Smart Timing** - Send reminders only for high-value bookings
4. **Opt-out Option** - Allow users to disable SMS notifications

### Monitoring Costs:

Go to `/admin/sms-settings/statistics` to see:
- Total SMS sent
- Total failed
- Today's count
- This month's count

## Troubleshooting

### SMS Not Sending

1. Check `/admin/sms-settings/logs` for errors
2. Verify Twilio credentials in admin panel
3. Check phone number format (include country code: +1234567890)
4. Ensure SMS is enabled in settings
5. Check Twilio account balance

### Common Errors:

**"Authentication Error - Invalid username or password"**
→ Wrong Twilio SID or Token

**"The 'To' phone number: +1234567890 is not currently reachable"**
→ Invalid or unreachable phone number

**"Insufficient funds"**
→ Add credits to your Twilio account

**"From" number is not verified"**
→ Verify your Twilio phone number in Twilio console

## Security Notes

1. **Never expose Twilio Token** in frontend code
2. **Use Environment Variables** for sensitive credentials
3. **Restrict Admin Access** - Only admins should access SMS settings
4. **Rate Limiting** - Implement rate limiting to prevent abuse
5. **Log Access** - All SMS actions are logged

## Environment Variables (Optional)

For production, you can use `.env`:

```
TWILIO_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+1234567890
TWILIO_WHATSAPP_NUMBER=+14155238886
```

Then update migration to read from env.

## Future Enhancements

- [ ] Scheduled reminders (1 day before, 1 hour before)
- [ ] SMS drip campaigns
- [ ] Multi-language templates
- [ ] SMS analytics dashboard
- [ ] A/B testing for templates
- [ ] Bulk SMS for marketing
- [ ] MMS support (images/videos)

## Support

For issues:
1. Check `/admin/sms-settings/logs` for error details
2. Review Twilio console: https://console.twilio.com/
3. Check Laravel logs: `storage/logs/laravel.log`
4. Verify database tables are created: `sms_settings`, `sms_templates`, `notification_logs`
