<?php
namespace Bot\Commands\UserCommands;

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

class WithdrawCommand extends UserCommand
{
    protected $name = 'withdraw';
    protected $description = 'Start a withdrawal request';
    protected $usage = '/withdraw';
    protected $version = '1.0.0';

    private PDO $pdo;
    private StateService $stateService;
    private BalanceService $balances;

    public function __construct($telegram, $update)
    {
        parent::__construct($telegram, $update);
        $this->pdo = Database::connection();
        $this->stateService = new StateService();
        $this->balances = new BalanceService();
    }

    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 (($user['kyc_status'] ?? 'unverified') !== 'verified') {
            return Request::sendMessage([
                'chat_id' => $chatId,
                'text'    => Localization::t($user['language'] ?? 'en', 'withdraw_kyc_required'),
            ]);
        }

        return $this->startWithdrawFlow($user, $chatId);
    }

    private function startWithdrawFlow(array $user, int $chatId): ServerResponse
    {
        $currency = 'USDT';
        $network = strtoupper($user['default_network'] ?? 'ERC20');
        $balance = $this->balances->getBalance((int) $user['id'], $currency);
        $text = Localization::t($user['language'] ?? 'en', 'withdraw_enter_amount', [
            $currency,
            $balance['available'],
        ]);
        $this->stateService->setState((int) $user['id'], 'await_withdraw_amount', [
            'currency' => $currency,
            'network'  => $network,
        ]);
        return Request::sendMessage([
            'chat_id' => $chatId,
            'text'    => $text,
        ]);
    }
}
