<?php

class JadLog extends RestApi {

  private $header;
  private $enviroument;

  public function __construct($registry) {
    $this->registry = $registry;
    $this->load     = $registry->get('load');
	  $this->config   = $registry->get('config');
    $this->db       = $registry->get('db');
    $this->log      = $registry->get('log');
    $this->session  = $registry->get('session');

    $this->curlOpts = array(
      CURLOPT_RETURNTRANSFER => 1
    );

    $this->setEnviroument();
    $this->setHeader();

  }


  public function setEnviroument(){
    $this->enviroument = 'https://www.jadlog.com.br/embarcador/api/frete/valor';
    //Fone: (11) 3563 2000 / 3563 2001 // operacional@jadlog.com.br
  }

  public function getEnviroument(){
    return $this->enviroument;
  }

  public function setHeader(){
    $this->header = array(
      "Content-Type: application/json",
      "Authorization:Bearer ".$this->config->get('jadlog_transport_token')
    );
  }

  public function getHeader(){
    return $this->header;
  }

  public function getQuote($dataSend) {
    $data = array();
    try {
      $url = $this->getEnviroument();
      $callReturn = parent::callAPI($url, 'POST', $dataSend, $this->getHeader(), false, $retorno);

      if (isset($callReturn->frete[0]->error)){
        $data['error'] = array(
          "id" =>$callReturn->frete[0]->error->id,
          "message" =>$callReturn->frete[0]->error->descricao
        );          
      }else if(isset($callReturn->error)){
        $data['error'] = array(
          "id" =>$callReturn->error->id,
          "message" =>$callReturn->error->descricao
        );             
      }

      if (!isset($data['error'])){
        $data = array(
          "valor" => $callReturn->frete[0]->vltotal,
          "prazo" => $callReturn->frete[0]->prazo
        );
      }else{
        $this->log->write('Módulo Jadlog dados enviados: '.print_r($dataSend,true));       
        $this->log->write('Módulo Jadlog erro retorno: '.print_r($data,true));   
      }
    } catch (Exception $e) {
      $this->log->write('Módulo Jadlog dados enviados: '.print_r($dataSend,true));  
      $this->log->write('Módulo Jadlog erro: '.print_r($e,true));
      $data['error'] = array(
        "message" => $e->getMessage()
      );   
    }

    return $data;

  }

}
