<?php
namespace Bot\Commands\UserCommands;

use Bot\Database;
use Bot\Localization;
use Bot\Services\ReferralService;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;
use PDO;

class ConvertpointsCommand extends UserCommand
{
    protected $name = 'convertpoints';
    protected $description = 'Convert referral points into wallet balance';
    protected $usage = '/convertpoints 100';
    protected $version = '1.0.0';

    private PDO $pdo;
    private ReferralService $referrals;

    public function __construct($telegram, $update)
    {
        parent::__construct($telegram, $update);
        $this->pdo = Database::connection();
        $this->referrals = new ReferralService();
    }

    public function execute(): ServerResponse
    {
        $message = $this->getMessage();
        $chatId = $message->getChat()->getId();
        $telegramId = $message->getFrom()->getId();
        $stmt = $this->pdo->prepare('SELECT * FROM users WHERE telegram_id = ?');
        $stmt->execute([$telegramId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return Request::sendMessage([
                'chat_id' => $chatId,
                'text'    => 'Please send /start first.',
            ]);
        }
        if (!empty($user['is_banned'])) {
            return Request::sendMessage([
                'chat_id' => $chatId,
                'text'    => Localization::t($user['language'] ?? 'en', 'account_banned_message'),
            ]);
        }
        $amountText = trim($message->getText(true) ?? '');
        if ($amountText === '' || !is_numeric($amountText)) {
            return Request::sendMessage([
                'chat_id' => $chatId,
                'text'    => 'Usage: /convertpoints <points>',
            ]);
        }
        try {
            $usd = $this->referrals->convertPoints((int) $user['id'], (float) $amountText);
        } catch (\Throwable $e) {
            return Request::sendMessage([
                'chat_id' => $chatId,
                'text'    => 'Conversion failed: ' . $e->getMessage(),
            ]);
        }
        return Request::sendMessage([
            'chat_id' => $chatId,
            'text'    => sprintf('Converted %.4f points to %.2f USDT in your wallet.', (float) $amountText, $usd),
        ]);
    }
}
