# Telegram Bot & Cron Job Enhancements (v2.0)

## 1. Overview
This update introduces environment-specific Telegram bots, consolidated cron notifications, administrative commands for broker linking, and improved process stability.

---

## 2. Database Changes

### SQL Queries
Run the following to update your database schema manually, or use the provided migration script.

```sql
-- 1. Create table for linking Telegram users to Broker Accounts
CREATE TABLE IF NOT EXISTS telegram_subscriber_broker_mapping (
    id INT AUTO_INCREMENT PRIMARY KEY,
    telegram_subscriber_id INT NOT NULL,
    broker_account_id INT NOT NULL,
    is_active TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY unique_subscription (telegram_subscriber_id, broker_account_id),
    FOREIGN KEY (telegram_subscriber_id) REFERENCES telegram_subscribers(id) ON DELETE CASCADE,
    FOREIGN KEY (broker_account_id) REFERENCES broker_accounts(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 2. Add Admin Flag to Subscribers
ALTER TABLE telegram_subscribers 
ADD COLUMN is_admin TINYINT(1) DEFAULT 0 AFTER username;

-- 3. Promote First User to Admin (One-time)
UPDATE telegram_subscribers 
SET is_admin = 1 
ORDER BY id ASC LIMIT 1;
```

### Migration Script
A utility script was created to handle this automatically:
- Path: `bin/migrate_telegram_tables.php`
- Command: `php bin/migrate_telegram_tables.php`

---

## 3. Environment Configuration

New variables added to `.env` to support multiple bot identities:

```ini
# Default / Legacy Token
TELEGRAM_BOT_TOKEN=your_fallback_token

# Environment Specific Tokens
TELEGRAM_BOT_TOKEN_UAT=your_uat_token
TELEGRAM_BOT_LIVE=your_live_token
TELEGRAM_BOT_TOKEN_LOCAL=your_local_token
```

The system automatically selects the token based on `APP_ENV`.

---

## 4. Modified Files & Logic

### A. Telegram Bot Logic

| File Path | Changes |
|-----------|---------|
| `app/Support/Env.php` | Added `getTelegramToken()` with fallback logic (Env -> Local -> Legacy). |
| `app/Notification/Channels/TelegramChannel.php` | Updated to use dynamic token retrieval via `Env::getTelegramToken()`. |
| `app/Notification/Repository/TelegramSubscriberRepository.php` | Added `is_admin` support, `linkBrokerAccount`, `unlinkBrokerAccount`, and auto-admin promotion login. |
| `app/Notification/Telegram/TelegramUpdatePoller.php` | Added Admin commands: `/brokers`, `/link`, `/unlink`. Added network error handling. |
| `bin/telegram-bot-runner.php` | Updated to inject `BrokerRepository` for command handling. |

### B. Cron & Process Management

| File Path | Changes |
|-----------|---------|
| `bin/cron-entrypoint.php` | **Consolidated Notifications**: Sends signal report only on restart or hourly heartbeat.<br>**Windows Support**: Uses `start /B` for background processes.<br>**Error Handling**: Added try-catch blocks for notifications. |
| `bin/order-status-poller.php` | **Crash Fix**: Added a retry loop (5 attempts) for DB connections to prevent immediate crashes during startup. |

---

## 5. New Telegram Commands (Admin Only)

| Command | Usage | Description |
|---------|-------|-------------|
| `/brokers` | `/brokers` | Lists all active broker accounts with their IDs. |
| `/link` | `/link <id>` | Links the current Telegram user to the specified Broker Account ID. |
| `/unlink` | `/unlink <id>` | Unlinks the current Telegram user from the specified Broker Account ID. |

---

## 6. How to Apply

1. **Run Migration**:
   ```bash
   php bin/migrate_telegram_tables.php
   ```

2. **Update .env**:
   Add the new Telegram token variables.

3. **Restart Services**:
   ```bash
   # Restart the bot runner
   php bin/telegram-bot-runner.php
   ```
