# Telegram Webhook Integration

Complete webhook support for Telegram Bot API with framework integration.

## Features

- ✅ Framework `WebhookRequestHandler` integration
- ✅ Signature verification with `TelegramSignatureProvider`
- ✅ Automatic callback routing with `CallbackRouter`
- ✅ Event-driven architecture via `WebhookReceived` events
- ✅ Idempotency checking
- ✅ Example handlers included

## Architecture

```
Telegram API → /webhooks/telegram → WebhookRequestHandler
                                              ↓
                                    WebhookReceived Event
                                              ↓
                             TelegramWebhookEventHandler
                                              ↓
                                      CallbackRouter
                                              ↓
                               ApproveOrderHandler / Custom Handlers
```

## Quick Start

### 1. Setup Webhook

```bash
php tests/debug/setup-telegram-webhook.php
```

This will:
- Generate a random secret token
- Configure Telegram webhook URL
- Display setup instructions

### 2. Add Secret to Environment

Add to `.env`:
```env
TELEGRAM_WEBHOOK_SECRET=your_generated_secret_token
```

### 3. Create Custom Handler

```php
use App\Framework\Notification\Channels\Telegram\Webhook\{CallbackHandler, CallbackResponse, TelegramCallbackQuery};

final readonly class MyCustomHandler implements CallbackHandler
{
    public function getCommand(): string
    {
        return 'my_action'; // Callback data: my_action_123
    }

    public function handle(TelegramCallbackQuery $callbackQuery): CallbackResponse
    {
        $parameter = $callbackQuery->getParameter(); // "123"

        // Your business logic here

        return CallbackResponse::notification('Action completed!');
    }
}
```

### 4. Register Handler

In `TelegramNotificationInitializer.php`:

```php
$router->register(new MyCustomHandler());
```

## Components

### Value Objects

- **`TelegramUpdate`** - Incoming webhook update
- **`TelegramMessage`** - Message data
- **`TelegramCallbackQuery`** - Callback button click
- **`CallbackResponse`** - Response to send back

### Interfaces

- **`CallbackHandler`** - Implement for custom handlers

### Classes

- **`CallbackRouter`** - Routes callbacks to handlers
- **`TelegramWebhookController`** - Webhook endpoint
- **`TelegramWebhookEventHandler`** - Event processor
- **`TelegramSignatureProvider`** - Security verification
- **`TelegramWebhookProvider`** - Provider factory

## Callback Data Format

Telegram callback buttons use `data` field (max 64 bytes).

**Recommended format**: `{command}_{parameter}`

Examples:
- `approve_order_123` → command: `approve_order`, parameter: `123`
- `delete_user_456` → command: `delete_user`, parameter: `456`
- `toggle_setting_notifications` → command: `toggle_setting`, parameter: `notifications`

## Response Types

```php
// Simple notification (toast message)
CallbackResponse::notification('Action completed!');

// Alert popup
CallbackResponse::alert('Are you sure?');

// Notification + edit message
CallbackResponse::withEdit(
    text: 'Order approved!',
    newMessage: 'Order #123\nStatus: ✅ Approved'
);
```

## Testing

### Send Test Message with Buttons

```bash
php tests/debug/test-telegram-webhook-buttons.php
```

### Monitor Webhook Requests

Check logs for:
- `Telegram webhook received`
- `Processing callback query`
- `Callback query processed successfully`

## Security

- **Secret Token**: Random token sent in `X-Telegram-Bot-Api-Secret-Token` header
- **HTTPS Required**: Telegram requires HTTPS for webhooks
- **Signature Verification**: Automatic via `TelegramSignatureProvider`
- **Idempotency**: Duplicate requests are detected and ignored

## Troubleshooting

### Webhook not receiving updates

1. Check webhook is configured:
   ```bash
   curl https://api.telegram.org/bot{BOT_TOKEN}/getWebhookInfo
   ```

2. Verify URL is publicly accessible via HTTPS

3. Check `TELEGRAM_WEBHOOK_SECRET` is set in `.env`

### Callback buttons not working

1. Ensure webhook is set (not using getUpdates polling)
2. Check callback handler is registered in `CallbackRouter`
3. Verify callback data format matches handler command
4. Check logs for error messages

### "No handler registered for command"

The callback command from button doesn't match any registered handler.

Example:
- Button: `approve_order_123`
- Extracted command: `approve_order`
- Needs handler with `getCommand() === 'approve_order'`

## Examples

See `Examples/` directory:
- `ApproveOrderHandler.php` - Order approval with message edit
- `RejectOrderHandler.php` - Order rejection with alert

## Framework Integration

This implementation uses:
- **Framework Webhook Module** - `App\Framework\Webhook\*`
- **Event System** - `WebhookReceived` events
- **DI Container** - Automatic registration
- **HttpClient** - API communication
- **Logger** - Webhook event logging

## Next Steps

- Implement rich media support (photos, documents)
- Add message editing capabilities
- Extend with more callback handlers
- Add webhook retry logic
