<?php
namespace Bot\Services;

class VirtualCardTemplateService
{
    private const SETTING_KEY = 'virtual_card_template';

    private SettingService $settings;

    public function __construct(?SettingService $settings = null)
    {
        $this->settings = $settings ?? new SettingService();
    }

    /**
     * @return array{text:string,parse_mode:string|null,buttons:array<int,array<int,array<string,string>>>}|null
     */
    public function getTemplate(): ?array
    {
        $raw = $this->settings->get(self::SETTING_KEY);
        if (!$raw) {
            return null;
        }
        $decoded = json_decode($raw, true);
        if (!is_array($decoded) || empty($decoded['text'])) {
            return null;
        }
        $decoded['buttons'] = $decoded['buttons'] ?? [];
        $decoded['parse_mode'] = $decoded['parse_mode'] ?? null;
        return $decoded;
    }

    public function setTemplate(string $text, ?string $parseMode = null): void
    {
        $template = $this->getTemplate() ?? ['buttons' => []];
        $template['text'] = $text;
        $template['parse_mode'] = $parseMode ?: null;
        $this->settings->set(self::SETTING_KEY, json_encode($template, JSON_UNESCAPED_UNICODE));
    }

    /**
     * @param array<int,array<int,array{text:string,url?:string,callback_data?:string}>> $buttons
     */
    public function setButtons(array $buttons): void
    {
        $template = $this->getTemplate() ?? ['text' => '', 'parse_mode' => null];
        $template['buttons'] = $buttons;
        $this->settings->set(self::SETTING_KEY, json_encode($template, JSON_UNESCAPED_UNICODE));
    }
}
