<?php

require_once('freteutils.php');

class ModelShippingFrenet extends FreteUtils {

  public function getQuote($address, $pProduct = []) {

    $method_data = [];

    $status = false;
    if (!$address['zone_id'] && isset($address['layout_id']) && $address['layout_id'] == Type_SendPostcode::Tp_Product) {
      $status = true;
    } else {
      $query = $this->db->query(
        "SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone 
          WHERE geo_zone_id = '" . (int)$this->config->get('frenet_geo_zone_id') . "' 
          AND country_id = '" . (int)$address['country_id'] . "' 
          AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')"
      );

      if (!$this->config->get('frenet_geo_zone_id') || $query->num_rows) {
        $status = true;
      }
    }

    if (!$status) return $method_data;

    try {
      $products = sizeof($pProduct) > 0 ? $pProduct : $this->cart->getProducts();

      $shipments = [];
      foreach ($products as $product) {
        $item = [
          "Height"   => (float)$product['height'],
          "Length"   => (float)$product['length'],
          "Quantity" => (int)$product['quantity'],
          "Weight"   => (float)$product['weight'],
          "Width"    => (float)$product['width'],
        ];

        if (!empty($product['sku'])) {
          $item["SKU"] = (string)$product['sku'];
        }

        $shipments[] = $item;
      }

      $dataSend = [
        "SellerCEP"            => str_replace('-', '', $this->config->get('frenet_cep_origem')),
        "RecipientCEP"         => str_replace('-', '', $address['postcode']),
        "ShipmentInvoiceValue" => (float)$this->cart->getSubTotal(),
        "ShippingServiceCode"  => null,
        "ShippingItemArray"    => $shipments,
        "RecipientCountry"     => "BR",
      ];

      // chamada a api
      $return = $this->frenet->getQuote($dataSend);

      $quote_data = [];
      if (!empty($return)) {
        foreach ($return as $service) {
          if (empty($service['Error'])) {
            $title = $service['Carrier'] . ' (' . $service['ServiceDescription'] . ')';
            if ((int)$service['DeliveryTime'] > 0) {
              $title .= ' - Previsão: ' . $service['DeliveryTime'] . ' dias úteis';
            }

            $quote_data[$service['ServiceCode']] = [
              'code'  => 'frenet.' . $service['ServiceCode'],
              'title' => $title,
              'cost'  => round((float)$service['ShippingPrice'], 2, PHP_ROUND_HALF_UP),
              'days'  => (int)$service['DeliveryTime'],
              'text'  => $this->currency->format((float)$service['ShippingPrice']),
            ];
          }
        }
      }

      if ($quote_data) {
        $method_data = [
          'code'       => 'frenet',
          'title'      => $this->config->get('frenet_descricao'),
          'quote'      => $quote_data,
          'sort_order' => $this->config->get('frenet_sort_order'),
          'error'      => false
        ];
      }

    } catch (Exception $e) {
      $logData = [
        'event'     => 'ShippingFrenet::getQuote',
        'exception' => [
          'type'    => get_class($e),
          'message' => $e->getMessage(),
          'code'    => $e->getCode(),
          'file'    => $e->getFile(),
          'line'    => $e->getLine(),
          'trace'   => $e->getTraceAsString()
        ],
        'datetime' => date('c'), // data/hora no padrão ISO
      ]; 
      $this->log->write(json_encode($logData, JSON_UNESCAPED_UNICODE));
    }
    
    return $method_data;
  }
}