<?php
/*
	      test yandex api
*/
namespace app\models;

use yii\base\Component;
use Yii;

class Ya extends Component
{
	/**
	 * @var string
	 */
	private $_token = "";
	private $FOLDER_ID = "b1gn8r9mc6pl01n6bjk4";
	private $_login = 'amicru';
	private $context = array();
	public   $config = array();

	/**
	 * Constructor
	 *
	 * @param bool $use_only_cache
	 */
	function __construct()
	{
		$this->config = Yii::$app->components['ya'];
		$this->SetToken($this->config['tokenAI']);
	}

	function SetHeader(){
		$opts = array(
			'http'=>array(
				'method'=>"GET",
				'header'=>"Accept-language: ru\r\n" .
				'Authorization: Bearer '.$this->_token."\r\n".
				'Content-Type: application/json'."\r\n".
				"x-folder-id: ".$this->FOLDER_ID."\r\n"
			)
		);
		$this->context = stream_context_create($opts);
	}

	function SetToken( $token ){
		$this->_token = $token;
	}

	function SetFolderID( $id ){
		$this->FOLDER_ID = $id;
	}

	function GetToken(){
		return $this->_token;
	}

	function Send(){
		$url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion';
//		$url = 'https://dev.amic.ru/manager/ya';
		$test = '{
  "modelUri": "gpt://b1gn8r9mc6pl01n6bjk4/yandexgpt-lite",
  "completionOptions": {
    "stream": false,
    "temperature": 0.1,
    "maxTokens": "1000"
  },
  "messages": [
    {
      "role": "system",
      "text": "Переведи текст"
    },
    {
      "role": "user",
      "text": "To be, or not to be: that is the question."
    }
  ]
}';
$data = json_decode($test);
$json = json_encode($data);

var_dump( $json );
//return '';
		$header = array(
			'Content-Type:application/json; charset=utf-8;',
			'Authorization: Bearer '.$this->_token,
			"x-folder-id: ".$this->FOLDER_ID,
		);
		$curl_handle=curl_init();
		curl_setopt($curl_handle, CURLOPT_URL, $url);
		curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 20);
		curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl_handle, CURLOPT_USERAGENT, 'amicru');
		curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $header);
		curl_setopt($curl_handle, CURLOPT_POST, 1);
		curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $json);
		$query = curl_exec($curl_handle);
		echo curl_error($curl_handle);
		print_a(curl_getinfo($curl_handle));
		curl_close($curl_handle);
//		print_r($query);
		return $query;
/*
		$opts = array(
			'http'=>array(
				'method'=>"POST",
				'header'=>"Accept-language: ru\r\n" .
				'Authorization: Bearer '.$this->_token."\r\n".
				'Content-Type: application/json'."\r\n".
				"x-folder-id: ".$this->FOLDER_ID."\r\n",
				'content' => $test
			)
		);
		$this->context = stream_context_create($opts);

		return  file_get_contents($url, false, $this->context);
		*/
	}

}
