<?php

class Wsceobase
{
  private $registry;
  private $usuario;
  private $senha;
  private $error;
  protected static $API_URL = 'https://ceo.futurasistemas.com.br/';
  protected static $API_NFE_URL = 'https://ceo.futurasistemas.com.br/webdanfe/WEBService/rest.php?class=ServiceREST&method=generatedanfe';
  private $db;
  private $request;
  private $config;
  public function __construct($registry)
  {
    $this->registry = $registry;
    $this->db = $registry->get('db');
    $this->request = $registry->get('request');
    $this->config = $registry->get('config');

    $retorno = $this->db->query('select ceo_usuario, ceo_senha from parametros_efutura')->row;

    //consulta usuário e senha configurados...
    $this->usuario = $retorno['ceo_usuario'];
    $this->senha = $retorno['ceo_senha'];

    if (defined('URL_CEO')) {
       self::$API_URL = URL_CEO.'ceo/';
       self::$API_NFE_URL = URL_CEO.'webdanfe/WEBService/rest.php?class=ServiceREST&method=generatedanfe';
    }

  }

  public function getError() {
      return $this->error;
  }

  public function setError($value) {
      $this->error = json_decode($value);
  }

  public function __get($name)
  {
    return $this->registry->get($name);
  }

  public function callJson($url, $posts = null, $method = 'GET')
  {
    try {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//returns the transference value like a string
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', 'X-AUTH-TOKEN: ' . $this->usuario . ':' . $this->senha));//sets the header
      curl_setopt($ch, CURLOPT_URL, $url); //oauth API
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);//time out em segundos

      if ($method == 'POST') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
      }

      //descomentar as estas opçoes caso for testar curl local para que funcione com o ssl 'falso';
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

      if (isset($posts)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
      }//file_put_contents('E:\\_Fontes\\eCommerce\\Trunk\\teste666666.txt', $jsonresult)

      $jsonresult = curl_exec($ch);//execute the conection
      //$result['result'][0][0]['id_ecommerce'] count($result['result'][0][0])
      //file_put_contents('Z:\\AtualizadorEcommerce\\teste666666.html', $jsonresult);

      $this->httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

      if ($jsonresult === false) {
        throw new Exception(curl_error($ch));
      } else {

        curl_close($ch);
        $result = json_decode($jsonresult, true);
        //var_dump($result['result'][0][0]['id_ecommerce']);
        //echo '<br>';
        //var_dump($result['result']);
        //exit;
        if (in_array($this->httpcode, array('200', '201'))) {
          return $result;
        } else {
            if ($this->config->get('config_error_log')) {
              $logData = [
                'event'    => 'wsceobase_error',
                'message'  => 'Erro ao conectar com o WSCEOBAS',
                'httpcode' => $this->httpcode,
                'jsonresult'=> $jsonresult,
                'datetime' => date('Y-m-d H:i:s'),
              ];
              $this->log->write(json_encode($logData, JSON_UNESCAPED_UNICODE));
            }
            $this->setError($jsonresult);
          return false;
        }

      }
    } catch (Exception $e) {
      if ($this->config->get('config_error_log')) {
        $logData = [
          'event'    => 'wsceobase_error',
          'message'  => 'Erro ao conectar com o WSCEOBAS',
          'httpcode' => $this->httpcode,
          'jsonresult'=> $jsonresult,
          'exception'=> [
              'type'    => get_class($e),
              'message' => $e->getMessage(),
              'code'    => $e->getCode(),
              'file'    => $e->getFile(),
              'line'    => $e->getLine(),
              'trace'   => $e->getTraceAsString()
          ],
          'datetime' => date('Y-m-d H:i:s'),
        ];
        $this->log->write(json_encode($logData, JSON_UNESCAPED_UNICODE));
      }
      $this->setError($e);
      return false;
    }

  }

  public function getHttpCode()
  {
    return $this->httpcode;
  }

}



