<?php
namespace Bot\Commands\AdminCommands;

use Bot\Config;
use Bot\Database;
use Longman\TelegramBot\Commands\AdminCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;
use PDO;

class AdminbroadcastCommand extends AdminCommand
{
    protected $name = 'adminbroadcast';
    protected $description = 'Broadcast a message to all users';
    protected $usage = '/adminbroadcast Your message here';
    protected $version = '1.0.0';

    public function execute(): ServerResponse
    {
        $message = $this->getMessage();
        $payload = trim($message->getText(true) ?? '');
        if ($payload === '') {
            return Request::sendMessage([
                'chat_id' => $message->getChat()->getId(),
                'text'    => 'Usage: `/adminbroadcast [markdown|markdownv2|html|text] Your message`',
                'parse_mode' => 'Markdown',
            ]);
        }

        $allowedModes = [
            'markdownv2' => 'MarkdownV2',
            'markdown'   => 'Markdown',
            'html'       => 'HTML',
            'text'       => null,
        ];
        $parseMode = null;
        $text = $payload;
        if (str_contains($payload, ' ')) {
            [$maybeMode, $rest] = explode(' ', $payload, 2);
            $key = strtolower($maybeMode);
            if (array_key_exists($key, $allowedModes)) {
                $parseMode = $allowedModes[$key];
                $text = $rest;
            }
        }
        if ($text === '') {
            return Request::sendMessage([
                'chat_id' => $message->getChat()->getId(),
                'text'    => 'Broadcast content cannot be empty.',
            ]);
        }

        $pdo = Database::connection();
        $batchSize = (int) Config::get()->getValue('broadcast_batch_size', 500);
        $offset = 0;
        $sent = 0;
        $failed = 0;

        do {
            $stmt = $pdo->prepare('SELECT telegram_id FROM users ORDER BY id LIMIT :limit OFFSET :offset');
            $stmt->bindValue(':limit', $batchSize, PDO::PARAM_INT);
            $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
            $stmt->execute();
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rows as $row) {
                $payload = [
                    'chat_id' => $row['telegram_id'],
                    'text'    => $text,
                ];
                if ($parseMode !== null) {
                    $payload['parse_mode'] = $parseMode;
                }
                $response = Request::sendMessage($payload);
                if ($response->isOk()) {
                    $sent++;
                } else {
                    $failed++;
                }
                usleep(200000); // 5 msgs/sec to stay below Telegram limit
            }
            $offset += $batchSize;
        } while (!empty($rows));

        return Request::sendMessage([
            'chat_id' => $message->getChat()->getId(),
            'text'    => sprintf('Broadcast complete. Sent: %d, Failed: %d', $sent, $failed),
        ]);
    }
}
