# ConverseDriver - Quick Start Guide

## 🚀 Setup in 5 Minutes

### 1. Copy the Driver
```bash
# Copy to your BotMan application
cp app/Drivers/ConverseDriver.php /your-botman-app/app/Drivers/WhatsApp/
```

### 2. Configure Environment
```bash
# In your BotMan app's .env
CONVERSE_API_URL=https://your-main-app.com
CONVERSE_API_TOKEN=your-bearer-token-here
```

### 3. Create Config File
```bash
# Create config/botman/converse.php
cat > config/botman/converse.php << 'EOF'
<?php
return [
    'converse' => [
        'url' => env('CONVERSE_API_URL'),
        'token' => env('CONVERSE_API_TOKEN'),
    ],
];
EOF
```

### 4. Register Driver
```php
// app/Providers/AppServiceProvider.php
use BotMan\BotMan\Drivers\DriverManager;
use App\Drivers\WhatsApp\ConverseDriver;

public function boot()
{
    DriverManager::loadDriver(ConverseDriver::class);
}
```

### 5. Create Controller
```php
// app/Http/Controllers/BotManController.php
<?php

namespace App\Http\Controllers;

use BotMan\BotMan\BotMan;

class BotManController extends Controller
{
    public function handle()
    {
        $botman = app('botman');

        $botman->hears('hi|hello', function (BotMan $bot) {
            $bot->reply('Hello! How can I help you?');
        });

        $botman->fallback(function (BotMan $bot) {
            $bot->reply("Sorry, I didn't understand that.");
        });

        $botman->listen();
    }
}
```

### 6. Add Route
```php
// routes/web.php or routes/api.php
Route::match(['get', 'post'], '/botman/webhook', 
    [BotManController::class, 'handle']);
```

### 7. Setup Main App Forwarding
```php
// In main app's WebhookController.php
use Illuminate\Support\Facades\Http;

public function handle(Request $request)
{
    // ... existing webhook verification ...
    
    $payload = $request->all();
    $payload['organization_id'] = 1; // Your logic here
    
    // Forward to BotMan
    Http::post(env('BOTMAN_URL') . '/botman/webhook', $payload);
    
    return response('OK', 200);
}
```

### 8. Test It!
```bash
# Send a test webhook
curl -X POST http://your-botman-app.com/botman/webhook \
  -H "Content-Type: application/json" \
  -d '{
    "event": "message.received",
    "data": {
      "value": {
        "contacts": [{"wa_id": "1234567890", "profile": {"name": "Test"}}],
        "messages": [{
          "id": "test123",
          "type": "text",
          "text": {"body": "hello"}
        }],
        "metadata": {"display_phone_number": "1234567890"}
      }
    }
  }'
```

## 📋 Required Main App Endpoints

Your main app must have these API endpoints:

### 1. Send Text Message
```
POST /api/send
Authorization: Bearer {token}
Content-Type: application/json

{
  "phone": "+1234567890",
  "message": "Your message here"
}
```

### 2. Send Media
```
POST /api/send/media
Authorization: Bearer {token}
Content-Type: application/json

{
  "phone": "+1234567890",
  "media_type": "image",
  "media_url": "https://example.com/image.jpg",
  "file_name": "image.jpg",
  "caption": "Optional caption"
}
```

### 3. Get Media URL
```
GET /api/getMedia/{mediaId}
Authorization: Bearer {token}

Response: {"statusCode": 200, "url": "https://..."}
```

## 🎯 Payload Examples

### Text Message
```json
{
  "phone": "+1234567890",
  "message": "Hello!",
  "type": "text"
}
```

### Interactive Buttons
```json
{
  "phone": "+1234567890",
  "message": "Choose:",
  "type": "interactive buttons",
  "buttons": [
    {"id": "opt1", "title": "Option 1"},
    {"id": "opt2", "title": "Option 2"}
  ]
}
```

### Interactive List
```json
{
  "phone": "+1234567890",
  "message": "Select:",
  "type": "interactive list",
  "buttons": [
    {
      "title": "",
      "rows": [
        {"id": "1", "title": "Item 1", "description": ""},
        {"id": "2", "title": "Item 2", "description": ""}
      ]
    }
  ],
  "button_label": "Options"
}
```

## ✅ Checklist

- [ ] Driver copied to BotMan app
- [ ] Environment variables set
- [ ] Config file created
- [ ] Driver registered in AppServiceProvider
- [ ] Controller created with bot logic
- [ ] Route added
- [ ] Main app forwarding webhooks
- [ ] API endpoints accessible
- [ ] Bearer token configured
- [ ] Redis configured for duplicates
- [ ] Test webhook successful

## 🔍 Troubleshooting

### Bot not responding?
```bash
# Check logs
tail -f storage/logs/laravel.log

# Verify driver is loaded
php artisan route:list | grep botman

# Test API connection
curl -H "Authorization: Bearer TOKEN" \
  https://main-app.com/api/send
```

### Messages not forwarding?
- Check main app's BOTMAN_URL in .env
- Verify network connectivity
- Review WebhookController forwarding code

### API errors?
- Verify Bearer token format: "Bearer {token}"
- Check endpoint URLs
- Ensure phone format: "+1234567890"

## 📚 Full Documentation

- **Detailed Setup**: See `CONVERSE_DRIVER_SETUP.md`
- **Summary**: See `CONVERSE_DRIVER_SUMMARY.md`
- **Code**: See `app/Drivers/ConverseDriver.php`

## 🆘 Quick Help

| Issue | Solution |
|-------|----------|
| Driver not loading | Check AppServiceProvider boot method |
| 401 Unauthorized | Verify Bearer token in config |
| 404 Not Found | Check API endpoint URLs |
| Duplicate messages | Verify Redis is running |
| No response | Check bot logic and fallback handler |

## 🎓 Example Bot Logic

```php
$botman->hears('menu|help', function (BotMan $bot) {
    $question = Question::create('What do you need?')
        ->addButton(Button::create('Products')->value('products'))
        ->addButton(Button::create('Support')->value('support'));
    
    $bot->ask($question, function (Answer $answer) use ($bot) {
        $value = $answer->getValue();
        $bot->reply("You selected: $value");
    });
});
```

That's it! You're ready to build your WhatsApp chatbot! 🎉


