<?php

class DLog extends RestApi {

  private $header;
  private $enviroument;
  private $dataAutentication;

  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->setAutentication();

  }

  public function setEnviroument(){
    $this->enviroument = 'https://dlog.com.br/api2/';
  }

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

  public function setAutentication(){
    $this->dataAutentication = array(
      "ClieCod" => $this->config->get('dlog_codigo'),
      "login" => str_replace(array('.','-','/'),'',$this->config->get('dlog_login')),
      "token" => $this->config->get('dlog_token')
    );
  }

  public function getAutentication(){
    return $this->dataAutentication;
  }

  public function getQuote($dataSend) {
    $data = $this->getCalculaFrete($dataSend);

    if (isset($data) && is_array($data)){
      if ($data['opcoesFrete'][0]['retorno'] == true){
        return $data['opcoesFrete'];
        //Não retorna o campo status quando sucesso
      }else{
        $error = 'Error ao calcular o frete';
        $error.= 'Mensagem:' . $data['subStatus'];
        throw new exception($error);
      } 
    }else{
      $error = 'Error ao carregar módulo Dlog:';
      $error.= 'Mensagem: Erro na conexão com o Dlog';
      throw new exception($error);
    }

    return $data;

  }

  public function getCalculaFrete($datasend){
    $ch = curl_init();

    $url = $this->getEnviroument() . 'CalcularFrete/';

    $dlog_cod = $this->config->get('dlog_codigo');
    $login = preg_replace("/[^0-9]/", "", $this->config->get('dlog_login'));
    $token = $this->config->get('dlog_token');

    $header = [
      'Content-Type: application/json',
      'Clie-Cod:'. $dlog_cod, 
      'Login:'. $login, 
      'Token:'. $token,
    ];

    $volumes[] = array(
      'peso' => $datasend['peso'],
      'compr' => $datasend['compr'],
      'larg' => $datasend['larg'],
      'alt' => $datasend['alt']
    );

     $data = array(
       'idTabela' => null,
       'cep' => $datasend['cep'],
       'valor' => $datasend['vPed'],
       'volumes' => $volumes
    );

    $json_data = json_encode($data);

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

    $response = json_decode(curl_exec($ch), true);
    
    if($response['response']['codStatus'] == "00"){
      return $response['response'];
    }

    return null;
  }
}
