# Messaging System Documentation

## Overview
The Flat Line messaging system allows administrators to send notifications to users via SMS (BulkSMSGhana) or Email. Messages are stored in the database and displayed in the user dashboard.

## Features

### 1. Admin Message Sending
- **Individual Messages**: Send SMS or Email to a specific user
- **Broadcast Messages**: Send SMS or Email to all users at once
- **Message Templates**: Pre-defined templates for common messages
- **Message History**: View recent order-related messages

### 2. User Notifications
- **Dashboard Display**: Unread notifications appear prominently on user dashboard
- **Notification Badge**: Shows count of unread messages
- **Mark as Read**: Users can mark individual or all notifications as read
- **Message Types**: Displays whether message was sent via SMS or Email

## Configuration

### BulkSMS Ghana Setup

1. **Get API Credentials**
   - Visit [https://bulksmsghana.com/](https://bulksmsghana.com/)
   - Sign up for an account
   - Get your API Key from the dashboard

2. **Configure in Admin Dashboard**
   - Login as admin
   - Navigate to Settings section
   - Enter your BulkSMS API Key
   - Set your Sender ID (max 11 characters, default: "FlatLine")
   - Click "Save Settings"

3. **Environment Variables** (Optional)
   ```env
   BULKSMS_API_KEY=your_api_key_here
   BULKSMS_SENDER_ID=FlatLine
   ```

### Email Configuration

Configure your email settings in `.env`:

```env
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="noreply@flatline.com"
MAIL_FROM_NAME="Flat Line"
```

## Usage

### Sending Individual Messages

1. Navigate to Messages section in admin dashboard
2. Select "Individual" tab
3. Choose a member from the dropdown
4. Select message type (SMS or Email)
5. If Email, enter a subject line
6. Type your message or use a template
7. Click "Send"

### Sending Broadcast Messages

1. Navigate to Messages section in admin dashboard
2. Select "Broadcast" tab
3. Select message type (SMS or Email)
4. If Email, enter a subject line
5. Type your message or use a template
6. Click "Send to All"
7. Confirm the action

### Message Templates

Available templates:
- **✓ Payment**: Payment received confirmation
- **⟳ Processing**: Order is being processed
- **🎉 Done**: Order completed
- **? Info**: Request additional information
- **⏱ Delay**: Notify about delays

Templates use placeholders:
- `[N]` - Customer first name
- `[A]` - Amount
- `[I]` - Order ID

## Database Schema

### Notifications Table
```sql
CREATE TABLE notifications (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    user_id BIGINT NOT NULL,
    type VARCHAR(255) NOT NULL, -- 'sms' or 'email'
    subject VARCHAR(255) NULL,
    message TEXT NOT NULL,
    status VARCHAR(255) DEFAULT 'sent', -- 'sent', 'failed', 'pending'
    is_read BOOLEAN DEFAULT FALSE,
    read_at TIMESTAMP NULL,
    created_at TIMESTAMP,
    updated_at TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
```

## API Endpoints

### Admin Routes
```php
POST /admin/messages/send          // Send individual message
POST /admin/messages/broadcast     // Send broadcast message
```

### User Routes
```php
POST /notifications/{id}/read      // Mark notification as read
POST /notifications/read-all       // Mark all notifications as read
```

## API Request Examples

### Send Individual Message
```javascript
fetch('/admin/messages/send', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': csrfToken
  },
  body: JSON.stringify({
    user_id: 1,
    message: 'Your order has been completed!',
    type: 'sms', // or 'email'
    subject: 'Order Completed' // required for email
  })
});
```

### Send Broadcast
```javascript
fetch('/admin/messages/broadcast', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': csrfToken
  },
  body: JSON.stringify({
    message: 'System maintenance scheduled for tonight',
    type: 'email',
    subject: 'Maintenance Notice'
  })
});
```

## BulkSMS Ghana API

### Phone Number Format
The system automatically formats phone numbers:
- Removes spaces, dashes, and special characters
- Adds Ghana country code (+233) if missing
- Converts local format (0XX) to international (+233XX)

### API Response
```json
{
  "status": "success",
  "message": "Message sent successfully",
  "message_id": "12345"
}
```

### Error Handling
- Invalid API key: Returns error message
- Insufficient balance: Returns balance error
- Invalid phone number: Returns validation error
- All errors are logged and stored in notification status

## User Dashboard

### Notification Display
- Appears at top of dashboard when unread messages exist
- Shows notification count badge
- Displays message preview (120 characters)
- Shows message type (SMS/Email) and time
- Blue dot indicator for unread messages

### Interaction
- Click notification to mark as read
- Click "Mark all read" to clear all notifications
- Notifications fade out when marked as read
- Page refreshes when all notifications are cleared

## Best Practices

1. **SMS Messages**
   - Keep messages under 160 characters for single SMS
   - Use clear, concise language
   - Include order numbers for reference
   - Test with your own number first

2. **Email Messages**
   - Use descriptive subject lines
   - Format messages for readability
   - Include contact information
   - Test email delivery before broadcasting

3. **Broadcast Messages**
   - Use sparingly to avoid spam
   - Send during business hours
   - Provide opt-out information if required
   - Test with a small group first

4. **Message Templates**
   - Customize templates for your business
   - Keep placeholders consistent
   - Update templates based on user feedback
   - Test all templates before use

## Troubleshooting

### SMS Not Sending
1. Check API key is correct in settings
2. Verify BulkSMS account has sufficient balance
3. Check phone number format
4. Review error logs in `storage/logs/laravel.log`

### Email Not Sending
1. Verify SMTP credentials in `.env`
2. Check email service is running
3. Test with `php artisan tinker` and `Mail::raw()`
4. Review mail logs

### Notifications Not Appearing
1. Check database for notification records
2. Verify user relationship is correct
3. Clear browser cache
4. Check JavaScript console for errors

## Security Considerations

1. **API Keys**: Store securely in database, never expose in frontend
2. **Rate Limiting**: Consider implementing rate limits for message sending
3. **User Privacy**: Comply with data protection regulations
4. **Opt-out**: Provide mechanism for users to opt out of messages
5. **Audit Trail**: All messages are logged in database with timestamps

## Future Enhancements

- [ ] WhatsApp integration
- [ ] Push notifications
- [ ] Message scheduling
- [ ] User message preferences
- [ ] Message analytics and reporting
- [ ] A/B testing for message templates
- [ ] Multi-language support
- [ ] Rich media messages (images, links)
