<?php
namespace Bot\Commands\UserCommands;

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

class PointsCommand extends UserCommand
{
    protected $name = 'points';
    protected $description = 'View referral points and rewards';
    protected $usage = '/points';
    protected $version = '1.0.0';

    private PDO $pdo;
    private BalanceService $balances;
    private ReferralService $referrals;

    public function __construct($telegram, $update)
    {
        parent::__construct($telegram, $update);
        $this->pdo = Database::connection();
        $this->balances = new BalanceService();
        $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.',
            ]);
        }
        $lang = $user['language'] ?? 'en';
        $pointsBalance = $this->balances->getBalance((int) $user['id'], 'POINT');
        $points = number_format((float) $pointsBalance['available'], 4);
        $rate = $this->referrals->getPointRate();
        $usd = number_format((float) $pointsBalance['available'] * $rate, 2);
        $text = sprintf(
            "Referral Points: %s\nApprox. value: %s USDT\nLevel: %s\n\nUse `/convertpoints <amount>` to convert points into USDT in your wallet.",
            $points,
            $usd,
            $user['referral_level'] ?? 'Bronze'
        );
        return Request::sendMessage([
            'chat_id' => $chatId,
            'text'    => $text,
        ]);
    }
}
