<?php

namespace App\TelegramBot;


use App\tmp_messages;
use App\vk_account;

class Api
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */

    private $chat_id;
    public $token;

    public function __construct($chat_id,$token)
    {
        $this->chat_id = $chat_id;
        $this->token = $token;
    }

    public function execute($method,$params){
        if(isset($params['disable_web_page_preview']) and $params['disable_web_page_preview'] == false){
            $params['disable_web_page_preview'] = false;
        }else{
            $params['disable_web_page_preview'] = true;
        }

        if(!isset($params['chat_id'])){
            $params['chat_id'] = $this->chat_id;
        }

        if(!isset($params['parse_mode'])) {
            $params['parse_mode'] = "markdown";
        }

        if(isset($params['inline_keyboard']) and $params['inline_keyboard'] != 0) {
            $params['reply_markup'] = json_encode(['resize_keyboard' => true, 'inline_keyboard' => $params['inline_keyboard']]);
            unset($params['inline_keyboard']);
        }

        if(isset($params['one_time_keyboard'])) {
            $params['one_time_keyboard'] = true;
        }else{
            $params['one_time_keyboard'] = false;
        }

        if(isset($params['keyboard'])) {
            $params['reply_markup'] = json_encode(['resize_keyboard' => true, 'keyboard' => $params['keyboard'],"one_time_keyboard" => $params['one_time_keyboard']]);
            unset($params['keyboard']);
        }

        if(!isset($params['token'])){
            $params['token'] = $this->token;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,  CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot{$params['token']}/{$method}");
        $data = curl_exec($ch);
        $data = json_decode($data);
        curl_close($ch);

        return $data;
    }

    public function getElementValue($string,$strStart,$strEnd){
        $str_search = strpos($string,$strStart);
        if($str_search===false){
            return false;
        }
        $str_1 = substr($string,$str_search+strlen($strStart));
        $str_search = strpos($str_1,$strEnd);
        $res = substr($str_1,0,$str_search);
        return $res;
    }
}
