<?php
namespace Bot\Commands\UserCommands;

use Bot\Localization;
use Bot\Services\VirtualCardTemplateService;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\InlineKeyboard;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;

class VirtualcardCommand extends UserCommand
{
    protected $name = 'virtualcard';
    protected $description = 'Buy virtual cards';
    protected $usage = '/virtualcard';
    protected $version = '1.0.0';

    private VirtualCardTemplateService $templates;

    public function __construct($telegram, $update = null)
    {
        parent::__construct($telegram, $update);
        $this->templates = new VirtualCardTemplateService();
    }

    public function execute(): ServerResponse
    {
        $message = $this->getMessage();
        $user = $message->getFrom();
        $lang = $user ? ($user->getLanguageCode() ?? 'en') : 'en';
        $template = $this->templates->getTemplate();
        $text = $template['text'] ?? Localization::t($lang, 'virtual_card_soon');
        $payload = [
            'chat_id' => $message->getChat()->getId(),
            'text'    => $text,
        ];
        if (!empty($template['parse_mode'])) {
            $payload['parse_mode'] = $template['parse_mode'];
        }
        if (!empty($template['buttons'])) {
            $keyboardRows = [];
            foreach ($template['buttons'] as $row) {
                $buttons = [];
                foreach ((array) $row as $button) {
                    if (empty($button['text'])) {
                        continue;
                    }
                    $btn = ['text' => $button['text']];
                    if (!empty($button['url'])) {
                        $btn['url'] = $button['url'];
                    } elseif (!empty($button['callback_data'])) {
                        $btn['callback_data'] = $button['callback_data'];
                    } else {
                        continue;
                    }
                    $buttons[] = $btn;
                }
                if ($buttons) {
                    $keyboardRows[] = $buttons;
                }
            }
            if ($keyboardRows) {
                $payload['reply_markup'] = new InlineKeyboard(...$keyboardRows);
            }
        }
        return Request::sendMessage($payload);
    }
}
