# Technical Reference - Implementation Details

## Architecture Overview

```
┌─────────────────────────────────────────────────────────┐
│                    Telegram User                        │
└────────────────────────┬────────────────────────────────┘
                         │
                         ↓
        ┌────────────────────────────────┐
        │     Telegram Bot API           │
        │   (TelegramClient.php)         │
        └────────────┬───────────────────┘
                     │
                     ↓
        ┌────────────────────────────────┐
        │      BotApp.php                │
        │  (Message Routing & Logic)     │
        └────────────┬───────────────────┘
                     │
        ┌────────────┴───────────────┐
        ↓                             ↓
    ┌─────────────────┐  ┌──────────────────────┐
    │ Repository.php  │  │ PersianText.php      │
    │ (Data Access)   │  │ (Translations)       │
    └────────┬────────┘  └──────────────────────┘
             │
             ↓
    ┌────────────────────────────────┐
    │   SQLite Database              │
    │   storage/bot.sqlite           │
    └────────────────────────────────┘
```

## Class Hierarchy

### BotApp

Main orchestrator that handles:

- Message parsing
- State management
- Flow routing
- Admin callbacks
- User interactions

**Key Methods:**

- `handle(update)` - Main update handler
- `handleMessage(message)` - Text message routing
- `handleCallback(callback)` - Inline button clicks
- `handleStateMessage(message, state)` - Multi-step input handling

### Repository

Data access layer for:

- User CRUD
- Service/Plan management
- Order management
- Settings
- Payment cards
- Admin permissions

**Pattern:** Prepared statements for all queries (SQL injection safe)

### PersianText

Static text constants and helpers:

- All user-facing strings in Persian
- Text escaping utilities
- Money formatting
- Status translation

### TelegramClient

Wrapper around Telegram Bot API:

- `sendMessage()` - Send text message
- `sendPhoto()` - Send image
- `editMessageText()` - Edit existing message
- `answerCallbackQuery()` - Button acknowledgment

### Database

SQLite initialization and migration:

- Schema creation
- Table initialization
- Foreign key setup

### Keyboard

Helper for inline keyboard markup:

- `button(text, callbackData)` - Single button
- `inline(rows)` - Keyboard layout

## Data Flow Examples

### Creating an Order (User Flow)

```
1. User clicks plan button
   ↓
2. BotApp.handleCallback() → showPlanPayment()
   ↓
3. setState('awaiting_receipt') with plan_id
   ↓
4. User uploads photo
   ↓
5. handleMessage() → handleStateMessage()
   ↓
6. handleReceiptUpload()
   ├─ repo.createOrder()
   ├─ repo.clearState()
   └─ notifyAdmins()
   ↓
7. Order created in database
8. Admin notified with photo
```

### Rejecting an Order (Admin Flow)

```
1. Admin clicks reject button
   ↓
2. handleAdminCallback() → setState('admin_reject_order_reason')
   ↓
3. Admin sends rejection reason
   ↓
4. handleAdminStateMessage() → adminRejectOrderReason()
   ├─ repo.rejectOrder(orderId, reason)
   ├─ telegram.sendMessage(userId, rejection_msg)
   └─ showAdminMenu()
   ↓
5. Order marked as 'rejected'
6. User notified
```

### Editing Setting (Admin Flow)

```
1. Admin clicks edit setting button
   ↓
2. handleAdminCallback() → setState('admin_edit_setting')
   ↓
3. Admin sends new value
   ↓
4. adminEditSetting()
   ├─ repo.setSetting(key, value)
   ├─ Update $this->currency/contactText/defaultCardNumber
   └─ showAdminSettings()
   ↓
5. Setting saved to database
6. Takes effect immediately
```

## Database Schema

### users

```sql
telegram_id (PK)
username
first_name
last_name
created_at
last_seen_at
```

### admins

```sql
telegram_id (PK)
name
created_at
```

### services

```sql
id (PK)
name
emoji
description
sort_order
is_active
created_at
updated_at
```

### plans

```sql
id (PK)
service_id (FK)
name
price
description
card_number
payment_description
sort_order
is_active
created_at
updated_at
```

### orders

```sql
id (PK)
user_telegram_id (FK)
service_id (FK)
plan_id (FK)
receipt_file_id
status (pending, contacted, completed, rejected)
admin_note
created_at
updated_at
```

### payment_cards

```sql
id (PK)
card_number (UNIQUE)
card_holder
description
is_active
created_at
updated_at
```

### settings

```sql
key (PK)
value
updated_at
```

### admin_permissions

```sql
id (PK)
admin_telegram_id (FK)
feature
created_at
```

### user_states

```sql
telegram_id (PK)
state
data_json
updated_at
```

## State Machine

States are managed via `user_states` table:

### User States

- `awaiting_receipt` - Waiting for payment receipt upload
  - Data: `{plan_id}`

### Admin States

- `admin_add_service_name` - Step 1 of service creation
- `admin_add_service_description` - Step 2
- `admin_add_service_emoji` - Step 3
- `admin_add_plan_name` - Step 1 of plan creation
- `admin_add_plan_price` - Step 2
- `admin_add_plan_description` - Step 3
- `admin_add_plan_card` - Step 4
- `admin_add_plan_payment` - Step 5
- `admin_contact_user_id` - Step 1 of messaging
- `admin_contact_message` - Step 2
- `admin_add_admin_id` - Add admin admin
- `admin_reject_order_reason` - Rejection reason
  - Data: `{order_id}`
- `admin_add_card_number` - Step 1 of card creation
- `admin_add_card_holder` - Step 2
- `admin_add_card_description` - Step 3
- `admin_edit_setting` - Editing configuration
  - Data: `{setting: currency|contact_text|default_card_number}`

## Callback Query Pattern

Callbacks are encoded as strings with colons:

- `menu:home` - Home menu
- `menu:services` - Services menu
- `menu:my_orders` - User orders
- `menu:contact` - Contact menu
- `service:{id}` - Show service plans
- `plan:{id}` - Show plan payment
- `admin:menu` - Admin menu
- `admin:add_service` - Add service
- `admin:services` - View services
- `admin:service:{id}` - Edit service
- `admin:add_plan:{serviceId}` - Add plan
- `admin:orders` - View orders
- `admin:order:{orderId}` - View order
- `admin:order_status:{orderId}:{status}` - Update status
- `admin:users` - View users
- `admin:contact_user:{userId}` - Contact user
- `admin:contact_prompt` - Prompt for user ID
- `admin:add_admin` - Add admin
- `admin:reject_order:{orderId}` - Reject order
- `admin:payment_cards` - View cards
- `admin:add_card` - Add card
- `admin:settings` - View settings
- `admin:edit_setting:{key}` - Edit setting

## Security Measures

1. **SQL Injection Prevention**: All database queries use prepared statements
2. **XSS Prevention**: `PersianText::escape()` used for all user input
3. **Card Masking**: Card numbers never fully displayed to users
4. **Admin Verification**: Every admin action checks `isAdmin()` first
5. **State Validation**: States cleared after completion
6. **File Permissions**: Storage directory created with 0775

## Performance Considerations

- **Indexes**: Created on frequently queried columns
  - `idx_plans_service`
  - `idx_orders_user`
  - `idx_orders_status`
  - `idx_admin_perms`
  - `idx_payment_cards_active`

- **Lazy Loading**: Settings loaded once on startup
- **In-Memory Cache**: `$this->currency`, `$this->contactText`, etc.
- **Query Optimization**: Only fetch necessary columns

## Extension Points

### Adding New Permissions

1. Update `PersianText` with permission name
2. Add permission check in handler
3. Update `showAdminMenu()` to hide if no permission

### Adding New Settings

1. Add to `showAdminSettings()` display
2. Add callback handler in `handleAdminCallback()`
3. Update state matching in `handleAdminStateMessage()`

### Adding New Admin States

1. Define state constant
2. Add handler method
3. Add to match statement in `handleAdminStateMessage()`
4. Add clearing on completion

## Testing Approach

### Unit Testing

- Mock Repository for database-free tests
- Test state transitions
- Test message parsing

### Integration Testing

- Test with actual SQLite database
- Test complete user flows
- Test admin workflows

### Manual Testing Checklist

- [ ] New service creation
- [ ] Plan creation with card selection
- [ ] Order upload and notification
- [ ] Order rejection
- [ ] Order history viewing
- [ ] Payment card management
- [ ] Settings modification
- [ ] Admin addition
- [ ] Direct messaging

## Error Handling

- All exceptions caught in `BotApp::handle()`
- Errors logged to `error_log()`
- User receives generic error message
- Admin can see detailed errors in logs

## Future Enhancements

1. **Permission Levels**:
   - Implement granular permission checking
   - Use `admin_permissions` table fully

2. **Analytics**:
   - Track order conversion rates
   - User retention analysis
   - Popular services/plans

3. **Webhooks**:
   - Replace polling with webhook
   - Better real-time performance

4. **Caching**:
   - Redis for user sessions
   - Cache settings in memory with TTL

5. **Notifications**:
   - Order status email notifications
   - Admin notifications for new orders
