<?php

namespace App\Http\Controllers\Admin\Config\Test;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Config;
use Telegram\Bot\Api;

class TelegramController extends Controller
{
    private Config $configModel;

    public function __construct(Config $config)
    {
        $this->configModel = $config;
    }

    /**
     * 텔레그램 발송 확인
     * @method GET
     * @see /admin/config/test/telegram
     */
    public function index()
    {
        $config = $this->configModel->getAllMeta();
        $response = $this->_getResponse($config);

        return view('admin.config.test.telegram', [
            'config' => $config,
            'response' => $response->getMe()
        ]);
    }

    /**
     * 텔레그램 발송 확인 실행
     * @method POST
     * @see /admin/config/test/telegram
     */
    public function store(Request $request)
    {
        $rules = [
            'g2a_order_bot_token' => 'nullable|string|max:255',
            'g2a_product_bot_token' => 'nullable|string|max:255',
            'g2a_error_bot_token' => 'nullable|string|max:255',
            'main_bot_token' => 'nullable|string|max:255',
            'message' => 'required|string'
        ];

        $attributes = [
            'g2a_order_bot_token' => 'G2A Order Bot Token',
            'g2a_product_bot_token' => 'G2A Product Bot Token',
            'g2a_error_bot_token' => 'G2A Error Bot Token',
            'main_bot_token' => 'Main Bot Token',
            'message' => '보낼 내용'
        ];

        $posts = $this->validate($request, $rules, [], $attributes);

        $this->configModel->save($posts, $attributes);

        $response = $this->_getResponse(
            $this->configModel->getAllMeta()
        );

        if (!$response->getMe()) {
            return back()->with('message', '텔레그램 설정이 잘못되었습니다.');
        }

        $chatID = last($response->getUpdates())->getChat()->get('id');
        $response->sendMessage([
            'chat_id' => $chatID,
            'text' => $posts['message']
        ]);

        $message = '텔레그램 문자를 발송하였습니다.';
        return redirect()->route('admin.config.test.telegram.index')->with('message', $message);
    }

    private function _getResponse(Config $config): Api
    {
        return new Api(
            $config->item('main_bot_token')
        );
    }
}
