<?php
namespace Bot\Commands\AdminCommands;

use Bot\Services\VirtualCardTemplateService;
use Longman\TelegramBot\Commands\AdminCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;

class AdminvirtualcardCommand extends AdminCommand
{
    protected $name = 'adminvirtualcard';
    protected $description = 'Configure the virtual card marketing message';
    protected $usage = '/adminvirtualcard <view|set|buttons>';
    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
    {
        $payload = trim($this->getMessage()->getText(true) ?? '');
        if ($payload === '') {
            return $this->replyUsage();
        }
        [$action, $rest] = array_pad(explode(' ', $payload, 2), 2, '');
        $action = strtolower($action);
        return match ($action) {
            'view'    => $this->handleView(),
            'set'     => $this->handleSet($rest),
            'buttons' => $this->handleButtons($rest),
            default   => $this->replyUsage(),
        };
    }

    private function replyUsage(): ServerResponse
    {
        $text = "Virtual card template commands:\n"
            . " `/adminvirtualcard view` - show current copy & buttons\n"
            . " `/adminvirtualcard set [MarkdownV2|Markdown|HTML] <text>` - update message body\n"
            . " `/adminvirtualcard buttons <json|clear>` - define inline button rows as JSON array";
        return Request::sendMessage([
            'chat_id' => $this->getMessage()->getChat()->getId(),
            'text'    => $text,
            'parse_mode' => 'Markdown',
        ]);
    }

    private function handleView(): ServerResponse
    {
        $template = $this->templates->getTemplate();
        if (!$template) {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => "No virtual card template configured. Use `/adminvirtualcard set` to add one.",
                'parse_mode' => 'Markdown',
            ]);
        }
        $summary = sprintf(
            "*Text:* %s\n*Parse mode:* %s\n*Buttons:* %s",
            $template['text'],
            $template['parse_mode'] ?? 'default',
            json_encode($template['buttons'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
        );
        return Request::sendMessage([
            'chat_id' => $this->getMessage()->getChat()->getId(),
            'text'    => $summary,
            'parse_mode' => 'Markdown',
        ]);
    }

    private function handleSet(string $payload): ServerResponse
    {
        $payload = trim($payload);
        if ($payload === '') {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'Provide the text body. Optionally prefix with MarkdownV2/Markdown/HTML.',
            ]);
        }
        $allowedModes = ['markdownv2', 'markdown', 'html'];
        $parseMode = null;
        $text = $payload;
        if (str_contains($payload, ' ')) {
            [$first, $rest] = explode(' ', $payload, 2);
            $firstLower = strtolower($first);
            if (in_array($firstLower, $allowedModes, true)) {
                $parseMode = match ($firstLower) {
                    'markdownv2' => 'MarkdownV2',
                    'markdown'   => 'Markdown',
                    'html'       => 'HTML',
                };
                $text = $rest;
            }
        }
        $this->templates->setTemplate($text, $parseMode);
        return Request::sendMessage([
            'chat_id' => $this->getMessage()->getChat()->getId(),
            'text'    => 'Virtual card message updated.',
        ]);
    }

    private function handleButtons(string $payload): ServerResponse
    {
        $payload = trim($payload);
        if ($payload === '') {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'Send button layout as JSON array (e.g., [[{"text":"Apply","url":"https://..."}]]) or send `clear`.',
            ]);
        }
        if (strtolower($payload) === 'clear') {
            $this->templates->setButtons([]);
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'Virtual card buttons cleared.',
            ]);
        }
        $decoded = json_decode($payload, true);
        if (!is_array($decoded)) {
            return Request::sendMessage([
                'chat_id' => $this->getMessage()->getChat()->getId(),
                'text'    => 'Invalid JSON. Expecting an array of button rows.',
            ]);
        }
        $this->templates->setButtons($decoded);
        return Request::sendMessage([
            'chat_id' => $this->getMessage()->getChat()->getId(),
            'text'    => 'Virtual card buttons updated.',
        ]);
    }
}
