# ConverseDriver Update Summary

## What Was Done

The `ConverseDriver` has been updated to work as a **standalone BotMan driver** that communicates with your main WhatsApp application via HTTP API calls.

## Key Changes

### 1. **Removed Direct Service Dependencies**
- ✅ Removed `WhatsappService` dependency
- ✅ Removed `Contact` and `Organization` model dependencies
- ✅ Changed from direct database access to HTTP API calls

### 2. **HTTP-Based Communication**
- ✅ Uses Laravel `Http` facade for API calls
- ✅ Sends messages via POST to main app's `/api/send` endpoint
- ✅ Sends media via POST to main app's `/api/send/media` endpoint
- ✅ Fetches media URLs via GET from `/api/getMedia/{id}` endpoint

### 3. **Configuration**
- ✅ Requires `url` and `token` in config
- ✅ No database connection needed (except Redis for duplicate detection)
- ✅ Simple setup in separate application

## Architecture

```
┌─────────────────┐
│  WhatsApp API   │
└────────┬────────┘
         │
         ▼
┌─────────────────────────┐
│   Main Application      │
│  - Webhook Handler      │
│  - WhatsappService      │
│  - Database             │
│  - API Endpoints:       │
│    * POST /api/send     │
│    * POST /api/send/    │
│      media              │
│    * GET /api/getMedia/ │
│      {id}               │
└──────────┬──────────────┘
           │
           │ HTTP API
           │ (Bearer Token)
           │
           ▼
┌─────────────────────────┐
│  BotMan Application     │
│  - ConverseDriver       │
│  - Bot Logic            │
│  - Conversations        │
│  - Redis (duplicates)   │
└─────────────────────────┘
```

## File Changes

### Modified Files
1. **`app/Drivers/ConverseDriver.php`**
   - Changed to use HTTP API calls instead of direct service calls
   - Simplified configuration requirements
   - Improved error handling and logging

### New Documentation Files
1. **`CONVERSE_DRIVER_SETUP.md`**
   - Complete setup guide for separate BotMan application
   - Example configurations and code
   - Troubleshooting tips

2. **`botman-app.env.example`**
   - Environment variable template for BotMan app

3. **`CONVERSE_DRIVER_SUMMARY.md`**
   - This file - overview of changes

## Configuration Required

### In BotMan App

```php
// config/botman/converse.php
return [
    'converse' => [
        'url' => env('CONVERSE_API_URL', 'https://your-main-app.com'),
        'token' => env('CONVERSE_API_TOKEN', 'your-token'),
    ],
];
```

### In Main App

```php
// Add to WebhookController to forward messages
Http::post(config('services.botman.url') . '/botman/webhook', $payload);
```

## API Endpoints Used

### Main App Must Provide:

1. **POST `/api/send`**
   ```json
   {
     "phone": "+1234567890",
     "message": "Hello",
     "type": "text"
   }
   ```

2. **POST `/api/send/media`**
   ```json
   {
     "phone": "+1234567890",
     "media_type": "image",
     "media_url": "https://example.com/image.jpg",
     "file_name": "image.jpg",
     "caption": "Caption here"
   }
   ```

3. **GET `/api/getMedia/{mediaId}`**
   - Returns: `{"statusCode": 200, "url": "https://..."}`

All endpoints require Bearer token authentication.

## Benefits of This Approach

1. **Separation of Concerns**
   - Main app handles WhatsApp integration
   - BotMan app handles conversation logic

2. **Scalability**
   - Can deploy bot logic separately
   - Can scale each service independently

3. **Maintainability**
   - Bot logic isolated from main app
   - Easier to update bot conversations
   - No need to redeploy main app for bot changes

4. **Flexibility**
   - Multiple bot apps can connect to same main app
   - Different bots for different use cases
   - Easy A/B testing

## Quick Start

### 1. Copy Driver to BotMan App
```bash
cp app/Drivers/ConverseDriver.php /path/to/botman-app/app/Drivers/WhatsApp/
```

### 2. Configure BotMan App
```bash
# In BotMan app
cp .env.example .env
# Edit .env and set:
# CONVERSE_API_URL=https://your-main-app.com
# CONVERSE_API_TOKEN=your-token
```

### 3. Register Driver
```php
// app/Providers/AppServiceProvider.php
DriverManager::loadDriver(\App\Drivers\WhatsApp\ConverseDriver::class);
```

### 4. Create Bot Logic
```php
// app/Http/Controllers/BotManController.php
$botman->hears('hello', function (BotMan $bot) {
    $bot->reply('Hi there!');
});
```

### 5. Setup Webhook Forwarding in Main App
```php
// In WebhookController
Http::post(env('BOTMAN_URL') . '/botman/webhook', $payload);
```

## Testing

### Test API Connection
```bash
curl -X POST https://main-app.com/api/send \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"phone":"+1234567890","message":"Test"}'
```

### Test Webhook
```bash
curl -X POST http://botman-app.com/botman/webhook \
  -H "Content-Type: application/json" \
  -d @test-payload.json
```

## Production Checklist

- [ ] Set secure API tokens
- [ ] Configure HTTPS for both apps
- [ ] Setup Redis for duplicate detection
- [ ] Configure proper logging
- [ ] Set up monitoring and alerts
- [ ] Test all message types
- [ ] Configure rate limiting
- [ ] Setup backup/failover
- [ ] Document bot commands
- [ ] Train support team

## Troubleshooting

### Issue: Messages not forwarding
- ✅ Check WebhookController is forwarding to BotMan
- ✅ Verify BOTMAN_URL in main app .env
- ✅ Check network connectivity

### Issue: Bot not responding
- ✅ Check bot logic is registered
- ✅ Verify driver is loaded
- ✅ Check logs in storage/logs/laravel.log

### Issue: API calls failing
- ✅ Verify API token is correct
- ✅ Check endpoints are accessible
- ✅ Verify Bearer token format
- ✅ Check API rate limits

## Next Steps

1. **Read**: `CONVERSE_DRIVER_SETUP.md` for detailed setup instructions
2. **Copy**: Driver file to your BotMan application
3. **Configure**: Set environment variables
4. **Test**: Start with simple text messages
5. **Deploy**: Follow production checklist
6. **Monitor**: Watch logs and metrics

## Support

For questions or issues:
1. Check application logs
2. Verify API connectivity
3. Test with curl commands
4. Review configuration settings
5. Consult setup documentation

## Version Information

- **Driver Version**: 2.0 (HTTP API based)
- **Laravel Version**: 9.x/10.x compatible
- **BotMan Version**: 2.x compatible
- **PHP Version**: 8.0+

## Credits

Updated for HTTP API communication to support separate BotMan application deployment.


