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

if (count($matches) > 0) {
    set_include_path(get_include_path().':/var/www/html/library/');
} else {
    set_include_path(get_include_path().':/usr/share/php/:../library/');
}

require_once('Zend/Loader.php');
require_once('Zend/Http/Client.php');
require_once('Zend/Http/Client/Adapter/Curl.php');
require_once('Zend/Mail.php');
require_once('Zend/Mail/Transport/Smtp.php');
require_once('Zend/Config/Ini.php');

class Agro_Curl {
    private $env = null;
    private $config = null;
    private $curl_options = null;
    private $usuario = null;
    private $senha = 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;

    /*
     * Esse método faz o login no Agronet e salva a sessão no objeto client
     * para novas requisições serem feitas
    */
    public function __construct($host=null,$proto=null) {

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

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

            try {
            	if (!isset($host)) {
              		throw new Exception("Erro! Variável host precisa ser setada manualmente no construtor.\n");
            	} else {
		            $this->host = $host;
		            $this->proto = (is_null($proto) ? 'http' : $proto);
            	}
                $app = 'docker';
            } catch (Exception $e) {
            	die($e->getMessage());
            }
        }

        $env = new Zend_Config_Ini(__DIR__ . '/../application/config/application.ini', $app);
        $this->usuario = $env->constants->SYSTEM_USERNAME;
        $this->senha = $env->constants->SYSTEM_PASSWORD;

        $this->curl_options = 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->curl_options
        );

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

        $this->client = new Zend_Http_Client($this->url, $this->config);
        $this->postArray = array('usuario' => $this->usuario, 'senha' => $this->senha);
        $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());
    }

    // tranforma o resulta em um array
    public function getResult() {
    	try {
    		if(is_null(json_decode($this->result->getBody()))){
    			throw new Exception($this->result);
    		} else {
    			return json_decode($this->result->getBody());
    		}
    	} catch (Exception $e) {
    		die($e->getMessage());
    	}
    }

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

    // informa url para fazer requisao/post
    public function setUrl($valor) {
      $this->url = trim($this->proto.'://'.$this->host.$valor);
    }

    // recupera url informada
    public function getUrl() {
        return trim($this->url);
    }

    // informa o host, por padrão já setado no construtor da classe
    public function setHost($valor) {
        $this->host = $valor;
    }

    // recupera o host informado
    public function getHost() {
        return $this->host;
    }

    // informa o protocolo (http ou https), por padrão, já setado no construtor da classe
    public function setProto($valor) {
        $this->proto = $valor;
    }

    // recupera o protocolo
    public function getProto() {
        return $this->proto;
    }

    public function setPostArray($valor) {
        if (is_array($valor) || is_null($valor)) {
            $this->postArray = $valor;
        } else {
            throw new Exception("Valor informado não é um array");
        }
    }

    public function getPostArray() {
        return $this->postArray;
    }

    public function doRequest($tipo='POST',$post=null) {
        $this->response = null;
        $this->result = null;
       	$this->client->setParameterPost($post);
        try {
            $this->client->setUri($this->getUrl());
        } 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->getHost(),$this->getProto());
        $this->client->setHeaders($this->getHeader());
        $this->client->setMethod($tipo);
        $this->response = $this->client->request();
        $this->result = $this->response;
    }

    function sendMail($content, $subject='') {

        $mail = new Zend_Mail('UTF-8');
        $mail->setFrom("ti@agrobrasilseguros.com.br", "Agronet 2.0 - Sistema de noficação");
	$app = parse_ini_file(dirname(__DIR__).'/application/config/application.ini');

        $config = array(
            'ssl'      => $app['constants.MAIL_SSL'],
            'port'     => $app['constants.MAIL_PORT'],
            'auth'     => $app['constants.MAIL_AUTH'],
            'username' => $app['constants.MAIL_USERNAME'],
            'password' => $app['constants.MAIL_PASSWORD']
        );

        $transport = new Zend_Mail_Transport_Smtp($app['constants.MAIL_SMTP'], $config);
        $mail->setDefaultTransport($transport);

        $to = array('Tonismar Bernardo' => 'tonismar.bernardo@agrobrasilseguros.com.br');

        try {
            $mail->addTo($to);
            //$mail->addCc($cc);
            $mail->setBodyHtml($content);

            if (!is_null($subject)) {
                $mail->setSubject($subject);
            } else {
                $mail->setSubject("Endosso em lote de propostas");
            }
            
            $mail->send();

            return true;
        } catch (Exception $e) {
            return true;
        }
    }

    private function debug($var) {
    	echo "<pre>".var_dump($var)."</pre>";
    	die('debugged');
    }
}

