<?php

class nc_services_direct_api
{

    public $direct_api_url = "https://api.direct.yandex.ru/v4/json/";
//    public $direct_api_url = "https://api-sandbox.direct.yandex.ru/v4/json/";
    public $req_data = array();
    protected $locale = "ru";
    public $token = "";
    public $login = "";
    public $finance_token = "";
    public $error;
    public $result;

    public function __construct()
    {
        require_once "HTTP/Request.php";
    }

    public function set_token($token)
    {
        $this->token = $token;
    }
    
    public function set_finance_token($token)
    {
        $this->finance_token = $token;
    }

    public function set_login($login)
    {
        $this->login = $login;
    }

    public function reset_data()
    {
        $this->result = null;
        $this->error = "";
        $this->req_data = array();
    }

    public function set_method($value = '')
    {
        $this->req_data["method"] = $value;
    }

    public function add_param($key, $value = '')
    {
        if (!isset($this->req_data["param"])) {
            $this->req_data["param"] = array();
        }
        $this->req_data["param"][$key] = $value;
    }

    public function set_request_data($key, $value = '')
    {
        $this->req_data[$key] = $value;
    }

    public function send_request()
    {
        $this->req_data['locale'] = $this->locale;
        $this->req_data['token'] = $this->token;
        $req = new HTTP_Request($this->direct_api_url);
        $req->setMethod(HTTP_REQUEST_METHOD_POST);
        $req->addRawPostData(json_encode($this->req_data));
        $response = $req->sendRequest();
        $this->error = PEAR::isError($response);

        if (!$this->error) {
            $this->result = json_decode($req->getResponseBody(),  true);
            if (isset($this->result['data'])) {
                return true;
            } else if (!empty($this->result['error_code'])) {
                $this->error = NETCAT_MODULE_SERVICES_ERROR.": ".NETCAT_MODULE_SERVICES_ERROR_CODE." = " . $this->result['error_code'] . ", ".NETCAT_MODULE_SERVICES_ERROR_STRING." = " . $this->result['error_str'] . ", ".NETCAT_MODULE_SERVICES_ERROR_DETAILS." = " . (!empty($this->result['error_detail'])? $this->result['error_detail']: NETCAT_MODULE_SERVICES_MISSING);
            } else {
                $this->error = "Unknown error";
            }
        }
        return false;
    }

}
