<?php

declare(strict_types=1);

class Agro_RabbitMQ_Curl
{
    private $config = null;
    private $curlOptions = null;
    public $postArray =  null;
    public $host = null;
    public $proto = null;
    public $url = null;
    public $client = null;
    public $header = null;
    public $response = null;
    public $result = null;
    private $settings;
    private $env;

    public function execute(string $url, string $env, array $params): void
    {
        $this->env = $env;
        $this->initCurl();
        $this->url .= $url;
        $this->doRequest('POST', $params);
    }

    private function initCurl()
    {
        $this->settings = parse_ini_file( __DIR__ . '/../../../application/config/application.ini', true);
        
        if (!array_key_exists($this->env, $this->settings)) {
            throw new Exception('Ambiente informado não existe.');
        }

        $this->host = 'agronet.local';
        $this->proto = 'http';

        preg_match("/^agrobr-app02\.*/", gethostname(), $matches);

        if ((count($matches) > 0)) {
            $this->host = 'agronet.agrobrasilseguros.com.br';
            $this->proto = 'https';
        }

        $this->curlOptions = array(
        		'CURLOPT_FOLLOWLOCATION' => true,
        		'CURLOPT_SSL_VERIFYPEER' => true,
        );

        $this->config = array(
            'adapter'      => 'Zend_Http_Client_Adapter_Curl',
            'ssltransport' => 'tls',
            'strict'       => false,
            'persistent'   => true,
            'curloption'   => $this->curlOptions
        );

        $this->url = $this->proto.'://'.$this->host;

        $this->client = new Zend_Http_Client($this->url . '/login', $this->config);

        $this->postArray = [
            'usuario' => $this->settings[$this->env]['constants.CURL_USER'],
            'senha' => $this->settings[$this->env]['constants.CURL_PASSWORD']
        ];
        $this->client->setParameterPost($this->postArray);
        $this->setHeader($this->host, $this->proto);
        $this->client->setHeaders($this->getHeader());

        $this->client->setCookie('PHPSESSID', str_shuffle('agrobrasil'.rand().'seguros'));

        $this->response = $this->client->request('POST');
        $this->setResult($this->response);

        // zerando o array POST do client para não ter que fazer isso toda vez que for utilizar a classe
        // visto que ele é setado na linha 55 com usuário e senha
        // caso haja necessidade de setar novamente, usar os métodos set e get da variável $postArray
        $this->client->setParameterPost(array());
    }

    // adiciona host e protocolo ao header do objeto cliente
    public function setHeader($host, $proto)
    {
        $this->header = array(
            'Host: '.$host,
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0',
            'Accept: text/javascript, application/javascript, */*',
            'Accept-Language: en-gb,en;q=5.0',
            'Accept-Encoding: gzip, deflate',
            'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
            'X-Requested-With: XMLHttpRequest',
            'Referer: '.$proto.'://'.$host
        );
    }

    // retorna o header configurado
    public function getHeader()
    {
        return $this->header;
    }

    // transforma a saída visível para o objeto Http_Response
    public function setResult($valor)
    {
        $this->result = json_decode($valor->getBody());
    }

    public function getResult()
    {
        return $this->result;
    }

    public function doRequest($tipo='POST', $post=null)
    {
        $this->response = null;
        $this->result = null;
       	$this->client->setParameterPost($post);
        try {
            $this->client->setUri($this->url);
        } catch (Exception $e) {
            print('Erro de URL. Geralmente é um defeito que vem dos arquivos editados no windows. Cria o mesmo arquivo no VIM.');
        }
        $this->setHeader($this->host, $this->proto);
        $this->client->setHeaders($this->getHeader());
        $this->client->setMethod($tipo);
        $this->response = $this->client->request();
        $this->result = $this->response;
    }

}