<?php
/**
 * @author Oleg Isaev
 * @contacts vk.com/id50416641, t.me/pandcar, github.com/pandcar
 */

class vkquery
{
	public $access_token,
		   $version,
		   $lang,
		   $last_error;
	
	public function __construct($access_token = '', $version = '5.131', $lang = 'ru')
	{
		$this->access_token = trim($access_token);
		$this->version = trim($version);
		$this->lang = trim($lang);
	}
	
	public function query($method, $params = [], $version = false)
	{
		$params = (! empty($params) ? http_build_query($params).'&' : null) . 'lang='.$this->lang.'&v=' . ($version ? trim($version) : $this->version) . (! empty($this->access_token) ? '&access_token='.$this->access_token : null);
		
		if ($json = $this->curl('https://api.vk.com/method/'.$method, $params))
		{
			if ($array = json_decode($json, true))
			{
				$this->last_error = @$array['error'];
				
				if (empty($this->last_error))
				{
					return $array['response'];
				}
				elseif ($this->last_error['error_code'] == 6)
				{
					usleep(1100000);
					
					return $this->query($method, $params, $version);
				}
			}
		}
		
		return false;
	}
	
	protected function curl($url, $post)
	{
		if ($ci = curl_init())
		{
			curl_setopt($ci, CURLOPT_URL, $url);
			curl_setopt($ci, CURLOPT_POST, true);
			curl_setopt($ci, CURLOPT_POSTFIELDS, $post);
			curl_setopt($ci, CURLOPT_HEADER, false);
			curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
			
			$output = curl_exec($ci);
			
			curl_close($ci);
			
			return $output;
		}
		
		return false;
	}
}