# API Documentation

This document provides comprehensive API documentation for all modules and services in the LarBot Template framework.

## Table of Contents

1. [Core Services](#core-services)
2. [Module APIs](#module-apis)
3. [Telegram Integration](#telegram-integration)
4. [Admin Panel APIs](#admin-panel-apis)
5. [Webhook Endpoints](#webhook-endpoints)
6. [Authentication](#authentication)
7. [Error Handling](#error-handling)

## Core Services

### ModuleManager

Central service for managing telegram bot modules.

#### Class: `App\Services\Core\ModuleManager`

```php
interface ModuleManagerInterface
{
    public function registerModule(TelegramModuleInterface $module): void;
    public function getModule(string $name): ?TelegramModuleInterface;
    public function getAllModules(): array;
    public function getEnabledModules(): array;
    public function handleMessage(TelegramMessage $message): ?TelegramResponse;
    public function handleCallback(TelegramCallback $callback): ?TelegramResponse;
}
```

#### Methods

##### `registerModule(TelegramModuleInterface $module): void`
Registers a new module with the manager.

**Parameters:**
- `$module` (TelegramModuleInterface): Module instance to register

**Example:**
```php
$moduleManager = app(ModuleManager::class);
$moduleManager->registerModule(new PaymentModule());
```

##### `handleMessage(TelegramMessage $message): ?TelegramResponse`
Processes incoming Telegram messages through all registered modules.

**Parameters:**
- `$message` (TelegramMessage): Parsed telegram message

**Returns:**
- `TelegramResponse|null`: Response from first module that handles the message

**Example:**
```php
$response = $moduleManager->handleMessage($telegramMessage);
if ($response) {
    // Send response back to user
    $telegramBot->sendMessage($response);
}
```

### EventBus

Event-driven communication system for inter-module messaging.

#### Class: `App\Services\Analytics\EventBus`

#### Static Methods

##### `emit(string $event, array $data = []): void`
Emits an event to all registered listeners.

**Parameters:**
- `$event` (string): Event name
- `data` (array): Event payload

**Example:**
```php
EventBus::emit('user.registered', [
    'user' => $user,
    'timestamp' => now(),
    'source' => 'telegram'
]);
```

##### `listen(string $event, callable $listener): void`
Registers an event listener.

**Parameters:**
- `$event` (string): Event name to listen for
- `$listener` (callable): Callback function

**Example:**
```php
EventBus::listen('payment.completed', function($data) {
    $user = $data['user'];
    $amount = $data['amount'];
    // Handle payment completion
});
```

##### `track(int|string $telegramUserId, string $type, array $props = []): void`
Tracks user analytics events.

**Parameters:**
- `$telegramUserId` (int|string): Telegram user ID
- `$type` (string): Event type
- `$props` (array): Event properties

**Example:**
```php
EventBus::track($telegramUserId, 'button_click', [
    'button' => 'payment_start',
    'amount' => 50000,
    'currency' => 'IRR'
]);
```

### ConfigurationManager

Manages layered configuration with runtime updates.

#### Class: `App\Services\Core\ConfigurationManager`

#### Methods

##### `get(string $key, mixed $default = null): mixed`
Retrieves configuration value.

**Parameters:**
- `$key` (string): Configuration key (dot notation supported)
- `$default` (mixed): Default value if key not found

**Example:**
```php
$configManager = app(ConfigurationManager::class);
$botToken = $configManager->get('telegram.bot_token');
$timeout = $configManager->get('api.timeout', 30);
```

##### `set(string $key, mixed $value): void`
Sets configuration value at runtime.

**Parameters:**
- `$key` (string): Configuration key
- `$value` (mixed): Value to set

**Example:**
```php
$configManager->set('payment.zarinpal.sandbox_mode', false);
```

## Module APIs

### Persian Localization Module

Provides Persian language support and localization features.

#### Class: `App\Modules\Persian\PersianModule`

#### Commands
- `/language` - Change language preferences
- `/calendar` - Show Persian calendar
- `/convert` - Convert numbers/dates to Persian

#### Methods

##### `convertToPersian(string $text): string`
Converts Latin numbers to Persian.

**Example:**
```php
$persianModule = app(PersianModule::class);
$persianText = $persianModule->convertToPersian('Price: 123,456 IRR');
// Output: 'Price: ۱۲۳,۴۵۶ IRR'
```

##### `formatPersianDate(Carbon $date, string $format = 'Y/m/d'): string`
Formats date in Persian calendar.

**Example:**
```php
$persianDate = $persianModule->formatPersianDate(now());
// Output: '۱۴۰۳/۰۱/۱۵'
```

### Payment Module

Handles payment processing via Zarinpal gateway.

#### Class: `App\Modules\Payment\PaymentModule`

#### Commands
- `/payment` - Start payment process
- `/subscription` - Manage subscriptions
- `/invoice` - View invoice history

#### Configuration
```php
'payment' => [
    'zarinpal' => [
        'merchant_id' => env('ZARINPAL_MERCHANT_ID'),
        'sandbox_mode' => env('ZARINPAL_SANDBOX', true),
        'callback_url' => env('ZARINPAL_CALLBACK_URL'),
    ],
    'currencies' => [
        'default' => 'IRR',
        'supported' => ['IRR', 'USD']
    ]
]
```

#### Service Methods

##### `createPayment(int $amount, User $user, array $metadata = []): ?string`
Creates a new payment request.

**Parameters:**
- `$amount` (int): Payment amount in Rials
- `$user` (User): User making payment
- `$metadata` (array): Additional payment data

**Returns:**
- `string|null`: Payment URL or null on failure

**Example:**
```php
$paymentService = app(PaymentService::class);
$paymentUrl = $paymentService->createPayment(50000, $user, [
    'product' => 'premium_subscription',
    'duration' => '1_month'
]);

if ($paymentUrl) {
    // Redirect user to payment gateway
    return TelegramResponse::withKeyboard(
        'برای پرداخت روی لینک زیر کلیک کنید',
        [[['text' => 'پرداخت', 'url' => $paymentUrl]]]
    );
}
```

##### `verifyPayment(string $authority, int $amount): array`
Verifies payment completion.

**Parameters:**
- `$authority` (string): Payment authority from callback
- `$amount` (int): Expected payment amount

**Returns:**
- `array`: Verification result with status and reference ID

### Notification Module

Manages broadcast messaging and user notifications.

#### Class: `App\Modules\Notification\NotificationModule`

#### Commands
- `/notifications` - Manage notification preferences
- `/subscribe` - Subscribe to notifications
- `/unsubscribe` - Unsubscribe from notifications

#### Service Methods

##### `createCampaign(array $data): BroadcastCampaign`
Creates a new broadcast campaign.

**Parameters:**
- `$data` (array): Campaign configuration

**Example:**
```php
$notificationService = app(NotificationService::class);
$campaign = $notificationService->createCampaign([
    'name' => 'Weekly Newsletter',
    'message' => 'سلام {{name}}! اخبار هفته را مشاهده کنید.',
    'target_filters' => [
        'active_since' => now()->subDays(7),
        'exclude_recent_broadcast' => 24
    ],
    'scheduled_at' => now()->addHour(),
    'created_by' => auth()->id()
]);
```

##### `sendTemplate(string $templateKey, array $recipients, array $variables = []): array`
Sends templated message to multiple recipients.

**Parameters:**
- `$templateKey` (string): Template identifier
- `$recipients` (array): User IDs or User objects
- `$variables` (array): Template variables

**Example:**
```php
$results = $notificationService->sendTemplate(
    'welcome_message',
    [$user1->id, $user2->id],
    [
        'app_name' => 'MyBot',
        'support_url' => 'https://example.com/support'
    ]
);
```

### Analytics Module

Tracks user behavior and provides insights.

#### Class: `App\Modules\Analytics\AnalyticsModule`

#### Commands
- `/analytics` - View personal analytics (admin only)

#### Service Methods

##### `trackEvent(User $user, string $eventType, array $data = []): void`
Records user interaction event.

**Parameters:**
- `$user` (User): User performing action
- `$eventType` (string): Type of event
- `$data` (array): Event metadata

**Example:**
```php
$analyticsService = app(AnalyticsService::class);
$analyticsService->trackEvent($user, 'menu_view', [
    'menu' => 'main_menu',
    'timestamp' => now(),
    'user_agent' => request()->userAgent()
]);
```

##### `getDashboardStats(array $filters = []): array`
Retrieves analytics dashboard data.

**Parameters:**
- `$filters` (array): Date range and other filters

**Returns:**
- `array`: Dashboard statistics

**Example:**
```php
$stats = $analyticsService->getDashboardStats([
    'date_from' => now()->subDays(30),
    'date_to' => now()
]);

// Returns:
// [
//     'total_users' => 1250,
//     'active_users' => 890,
//     'total_messages' => 15420,
//     'top_commands' => [...],
//     'user_growth' => [...]
// ]
```

### Content Module

Manages dynamic content and menus.

#### Class: `App\Modules\Content\ContentModule`

#### Commands
- `/content` - Browse content pages
- `/menu` - Show dynamic menu
- `/help` - Help content

#### Service Methods

##### `getPage(string $slug): ?ContentPage`
Retrieves content page by slug.

**Example:**
```php
$contentService = app(ContentService::class);
$page = $contentService->getPage('privacy-policy');

if ($page && $page->is_published) {
    return TelegramResponse::text($page->content);
}
```

##### `buildMenu(string $menuType, User $user): array`
Builds dynamic menu for user.

**Parameters:**
- `$menuType` (string): Menu type identifier
- `$user` (User): User for personalization

**Returns:**
- `array`: Telegram keyboard array

## Telegram Integration

### TelegramMessage DTO

Data transfer object for incoming messages.

#### Properties
- `chatId` (int): Chat ID
- `userId` (int): User ID
- `text` (string): Message text
- `message` (array): Full message object
- `contact` (array|null): Contact information
- `location` (array|null): Location data

#### Methods

##### `isCommand(): bool`
Checks if message is a command.

##### `getCommand(): ?string`
Extracts command name from message.

##### `getCommandArgs(): array`
Gets command arguments.

**Example:**
```php
if ($message->isCommand()) {
    $command = $message->getCommand(); // 'start'
    $args = $message->getCommandArgs(); // ['param1', 'param2']
}
```

### TelegramResponse DTO

Response object for outgoing messages.

#### Constructor
```php
public function __construct(
    public readonly string $text,
    public readonly ?array $keyboard = null,
    public readonly ?string $parseMode = null,
    public readonly bool $disablePreview = false,
    public readonly bool $handled = true
)
```

#### Static Methods

##### `text(string $text, string $parseMode = null): self`
Creates simple text response.

##### `withKeyboard(string $text, array $keyboard, string $parseMode = null): self`
Creates response with inline keyboard.

**Example:**
```php
return TelegramResponse::withKeyboard(
    'لطفا یکی از گزینه‌های زیر را انتخاب کنید:',
    [
        [
            ['text' => '💳 پرداخت', 'callback_data' => 'payment_start'],
            ['text' => '📊 آمار', 'callback_data' => 'analytics_view']
        ],
        [
            ['text' => '⚙️ تنظیمات', 'callback_data' => 'settings_menu']
        ]
    ]
);
```

## Admin Panel APIs

### Filament Resources

All admin resources follow Filament v3 conventions and provide full CRUD operations.

#### User Resource
**Endpoint:** `/admin/users`
- List users with filtering and search
- Create/edit user profiles
- Manage user permissions
- View user analytics

#### Broadcast Campaign Resource
**Endpoint:** `/admin/broadcast-campaigns`
- Create and manage campaigns
- Schedule message delivery
- Monitor campaign performance
- Target user segments

#### Notification Template Resource
**Endpoint:** `/admin/notification-templates`
- Manage reusable message templates
- Template variable system
- Preview and testing tools

#### Analytics Dashboard
**Endpoint:** `/admin/analytics`
- Real-time user metrics
- Message statistics
- Performance indicators
- Export capabilities

### Health Check API

#### Endpoint: `GET /admin/health`

Returns system health status.

**Response:**
```json
{
    "status": "healthy",
    "checks": {
        "database": {
            "status": "ok",
            "response_time": 12.5
        },
        "cache": {
            "status": "ok",
            "response_time": 2.1
        },
        "telegram_api": {
            "status": "ok",
            "response_time": 156.3
        },
        "storage": {
            "status": "ok",
            "disk_usage": "45%"
        }
    },
    "timestamp": "2024-01-15T10:30:00Z"
}
```

## Webhook Endpoints

### Telegram Webhook
**Endpoint:** `POST /api/telegram/webhook`

Receives updates from Telegram Bot API.

**Headers:**
- `Content-Type: application/json`
- `X-Telegram-Bot-Api-Secret-Token: {webhook_secret}`

**Request Body:**
```json
{
    "update_id": 123456789,
    "message": {
        "message_id": 1234,
        "from": {
            "id": 123456789,
            "is_bot": false,
            "first_name": "John",
            "username": "john_doe"
        },
        "chat": {
            "id": 123456789,
            "first_name": "John",
            "username": "john_doe",
            "type": "private"
        },
        "date": 1640995200,
        "text": "/start"
    }
}
```

### Payment Callback
**Endpoint:** `POST /api/payment/zarinpal/callback`

Handles Zarinpal payment gateway callbacks.

**Parameters:**
- `Authority` (string): Payment authority
- `Status` (string): Payment status (OK/NOK)

## Authentication

### Admin Panel Authentication

Uses Laravel's built-in authentication with custom guards.

#### Login
**Endpoint:** `POST /admin/login`

**Request:**
```json
{
    "email": "admin@example.com",
    "password": "password"
}
```

#### User Context
Admin panel automatically determines user context based on:
1. Authenticated admin user
2. Session data
3. Telegram user mapping

### API Authentication

For API endpoints that require authentication:

#### Headers
```
Authorization: Bearer {token}
X-Telegram-User-ID: {telegram_user_id}
```

## Error Handling

### HTTP Status Codes

- `200` - Success
- `400` - Bad Request (validation error)
- `401` - Unauthorized
- `403` - Forbidden
- `404` - Not Found
- `422` - Unprocessable Entity (validation failed)
- `429` - Too Many Requests (rate limited)
- `500` - Internal Server Error

### Error Response Format

```json
{
    "error": {
        "code": "VALIDATION_FAILED",
        "message": "The given data was invalid.",
        "details": {
            "email": ["The email field is required."]
        }
    },
    "timestamp": "2024-01-15T10:30:00Z",
    "request_id": "req_123456789"
}
```

### Common Error Codes

#### Telegram Integration
- `TELEGRAM_API_ERROR` - Telegram API returned error
- `WEBHOOK_VERIFICATION_FAILED` - Invalid webhook signature
- `BOT_BLOCKED` - User blocked the bot
- `MESSAGE_TOO_LONG` - Message exceeds Telegram limits

#### Payment Processing
- `PAYMENT_FAILED` - Payment processing failed
- `INVALID_AMOUNT` - Invalid payment amount
- `MERCHANT_ERROR` - Zarinpal merchant configuration error

#### Module System
- `MODULE_NOT_FOUND` - Requested module not available
- `MODULE_DISABLED` - Module is disabled
- `CONFIGURATION_ERROR` - Module configuration invalid

### Logging

All API interactions are logged with appropriate levels:

```php
// Info level - successful operations
Log::info('Payment completed', [
    'user_id' => $user->id,
    'amount' => $amount,
    'authority' => $authority
]);

// Warning level - recoverable errors
Log::warning('Rate limit exceeded', [
    'user_id' => $user->id,
    'endpoint' => '/api/telegram/webhook',
    'rate_limit' => '60/min'
]);

// Error level - system errors
Log::error('Database connection failed', [
    'error' => $exception->getMessage(),
    'query' => $query
]);
```

## Rate Limiting

### Telegram API Limits
- Messages: 30 per second
- Bulk operations: 20 per minute
- Webhook updates: No limit (handled by Telegram)

### Application Limits
- Admin API: 100 requests per minute per user
- Public API: 60 requests per minute per IP
- Payment API: 10 requests per minute per user

### Rate Limit Headers
```
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
X-RateLimit-Reset: 1640995260
```

## Development Examples

### Creating a Custom Module

```php
<?php

namespace App\Modules\Custom;

use App\Contracts\TelegramModuleInterface;
use App\DTOs\TelegramMessage;
use App\DTOs\TelegramCallback;
use App\DTOs\TelegramResponse;

class CustomModule implements TelegramModuleInterface
{
    public function getModuleName(): string
    {
        return 'custom';
    }

    public function getModuleVersion(): string
    {
        return '1.0.0';
    }

    public function getDependencies(): array
    {
        return ['analytics']; // Depends on analytics module
    }

    public function handleMessage(TelegramMessage $message): ?TelegramResponse
    {
        if ($message->text === '/custom') {
            return TelegramResponse::text('Custom module response!');
        }

        return null; // Not handled by this module
    }

    public function handleCallback(TelegramCallback $callback): ?TelegramResponse
    {
        if ($callback->data === 'custom_action') {
            // Track the interaction
            EventBus::track($callback->userId, 'custom_action', [
                'button' => 'custom_action'
            ]);

            return TelegramResponse::text('Custom action executed!');
        }

        return null;
    }

    public function getConfigurationSchema(): array
    {
        return [
            'enabled' => ['type' => 'boolean', 'default' => true],
            'custom_setting' => ['type' => 'string', 'default' => 'value']
        ];
    }

    public function install(): void
    {
        // Module installation logic
    }

    public function uninstall(): void
    {
        // Module cleanup logic
    }

    public function isEnabled(): bool
    {
        return config('modules.custom.enabled', true);
    }

    public function getPriority(): int
    {
        return 50; // Medium priority
    }
}
```

### Registering the Module

```php
// In a service provider or bootstrap file
$moduleManager = app(ModuleManager::class);
$moduleManager->registerModule(new CustomModule());
```

This completes the comprehensive API documentation for the LarBot Template framework. All services, modules, and endpoints are documented with examples and proper usage guidelines.