<?php

class Frenet extends RestApi {

  private $header;
  private $environment;

  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->setEnvironment();
    $this->setHeader();
  }

  private function setHeader() {
    $this->header = [
      "Accept: application/json",
      "Content-Type: application/json",
      "token: " . trim((string)$this->config->get('frenet_token')),
    ];
  }

  private function setEnvironment() {
    $this->environment = 'https://api.frenet.com.br/';
  }

  public function getQuote($dataSend) {
    $url = $this->environment . 'shipping/quote';
    $payload = is_string($dataSend) ? $dataSend : json_encode($dataSend);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

    $raw = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if (curl_errno($ch)) {
      $err = curl_error($ch);
      curl_close($ch);
      throw new Exception("Erro de comunicação com a Frenet: {$err}");
    }
    curl_close($ch);

    $response = json_decode($raw);
    if (!is_object($response)) {
      throw new Exception("Resposta inválida da Frenet (HTTP {$httpCode}).");
    }

    if (!isset($response->ShippingSevicesArray) || !is_array($response->ShippingSevicesArray)) {
      $msg = isset($response->Message) ? (string)$response->Message : 'Retorno inesperado';
      throw new Exception($msg);
    }

    $result = [];
    foreach ($response->ShippingSevicesArray as $service) {
      $result[] = [
        'ServiceCode'        => isset($service->ServiceCode) ? (string)$service->ServiceCode : '',
        'ServiceDescription' => isset($service->ServiceDescription) ? (string)$service->ServiceDescription : '',
        'Carrier'            => isset($service->Carrier) ? (string)$service->Carrier : '',
        'ShippingPrice'      => isset($service->ShippingPrice) ? (float)$service->ShippingPrice : 0.0,
        'DeliveryTime'       => isset($service->DeliveryTime) ? (int)$service->DeliveryTime : 0,
        'Error'              => !empty($service->Error),
        'Msg'                => isset($service->Msg) ? (string)$service->Msg : '',
      ];
    }

    return $result;
  }
}