<?php

namespace App\Http\Admin\Telegram;

use AdminSection;
use App\Setting;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Psr\Log\NullLogger;
use Telegram\Bot\Api;

class SettingController extends Controller
{
    public function index(){
        return AdminSection::view(view('admin.telegram', Setting::getSettings()));
    }

    public function store(Request $request){
        Setting::where('key', '!=', NULL)->delete();

        foreach ($request->except('_token') as $key => $value){
            $setting = new Setting;
            $setting->key = $key;
            $setting->value = $request->$key;
            $setting->save();
        }

        return redirect()->route('admin.setting.index');
    }

    public function setWebhook(Request $request){
        $result = $this->sendTelegramData($request->url ? 'setWebhook' : 'deleteWebhook', [
            'query' => ['url' => $request->url . '/' . \Telegram::getAccessToken()]
        ]);

        return redirect()->route('admin.setting.index')->with('status', $result);
    }

    public function getWebhookInfo(){

        $result = $this->sendTelegramData('getWebhookInfo');
        return redirect()->route('admin.setting.index')->with('status', $result);
    }

    public function sendTelegramData ($rout = '', $params = [], $method = 'POST'){
        $client = new Client( ['base_uri' => 'https://api.telegram.org/bot' . \Telegram::getAccessToken() . '/'] );
        $result = $client->request( $method, $rout, $params);
        return (string) $result->getBody();
    }
}