<?php
use DateTime;

require_once('freteutils.php');
class ModelShippingJamef extends Model {
	function getQuote($address, $products = Array()) {

		$this->load->type('tipocomum');
    $this->load->type('tipofrete');
    $this->load->helper('ftr_geral');
    
    $status = $this->getStatus($address);

		$method_data = array();

		if ($status) {
		  try{  
            $this->updateBranches();

    		    $productData = $this->getProductValues($products);
            $customerType = $this->customer->getTipo_pessoa();
            $customerDocument = $customerType == 'F' ? $this->customer->getCpf() : $this->customer->getCnpj();
            $collectDate = $today = new DateTime(date('Y/m/d'));
            $addictionalDays = $this->config->get('jamef_periodoadicional') ?? 0;
            if ($addictionalDays) {
              $collectDate = $collectDate->modify('+'. $addictionalDays . ' days');
            }
           
            $dataSend = [
              "tipoTransporte" => $this->config->get('jamef_tipo_transporte') ?? '1', //Tipo de Transporte ( 1 = RODOVIÁRIO 2 = AÉREO)
              "documentoDevedor" => $customerDocument, //CNPJ/CPF do pagador do Frete
              "cepOrigem" => $this->config->get('jamef_cepOrigem') ?? "13178584",
              "cepDestino" => $address['postcode'],
              "quantidadeVolume" => 1, //Quantidade de volume da Nota Fiscal
              "pesoMercadoria" => floatval($productData['weight']),
              "valorNotaFiscal" => floatval($productData['value']),
              "metragemCubica" => floatval($productData['cubic']),
              "documentoRemetente" => $this->config->get('jamef_cnpj'), //CPF/CNPJ Remetente
              "documentoDestino" => $customerDocument, //CPF/CNPJ Destinatario
              "filialOrigem" => $this->config->get('jamef_filial'),
              "dataColeta" => $collectDate->format('d/m/Y') //example: 25/12/2024 .. Data da coleta da mercadoria (DD/MM/AAAA)
            ];

            $shippingData = $this->jamef->getQuoteVolume(json_encode($dataSend));

            if ($shippingData) {
              $deliveryTime = $shippingData->previsaoEntrega;
              $shippingValue = $shippingData->total;

              $jamefDate = DateTime::createFromFormat('d/m/Y', $deliveryTime);
              $jamefDate->format('Y/m/d');
              $deliveryDays = date_diff($today, $jamefDate);
              
              $deliveryDays = $deliveryDays->days + $addictionalDays;

              $deliveryTime = !$this->config->get('jamef_exibeprevisao') ? $this->config->get('jamef_nome') : 'Jamef - Previsão: Até ' . $deliveryDays .' dias.';
              
              $quote_data['jamef'] = array(
                'code'         => 'jamef.jamef',
                'title'        => $deliveryTime,
                'days'         => $deliveryDays,
                'cost'         => round((float)$shippingValue, 2, PHP_ROUND_HALF_UP),
                'text'         => $this->currency->format($shippingValue)
              );

              $method_data = array(
                'code'       => 'jamef',
                'title'      => $this->config->get('jamef_nome'),
                'quote'      => $quote_data,
                'sort_order' => $this->config->get('jamef_sort_order'),
                'error'      => false
              );
            }
		  }catch (Exception $ex){
		      //Não é para exibir o erro mesmo, isso valida o webservice se der erro não trava os demais módulos
		      //echo  '<div style="font-size:11px; margin-bottom:3px">*Forma de envio da Jamef Indisponivel no momento.</div>';
		  }
		}
		return $method_data;
	}

  protected function getStatus($address): bool {
    if((!$address['zone_id']) && ($address['layout_id'] == Type_SendPostcode::Tp_Product)){
      return true;
    }

    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('jamef_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('jamef_geo_zone_id') || $query->num_rows) {
      return true;
    }
      
    return false;
  }

  protected function getProductValues($products): array {
    $hasProducts = sizeof($products) > 0;
    $productWeight = $hasProducts ? 0 : $this->cart->getWeight();
    $productQtd = $hasProducts ? 0 : $this->cart->countProducts();
    $productValue = $hasProducts ? 0 : $this->cart->getSubTotal();
    
    if($hasProducts) {
      foreach ($products as $product) {
        $productWeight += $product['weight'];
        $productValue  += $product['price'] * $product['quantity'];
        $productQtd  += $product['quantity'];
      }
    }

    return [
      'weight' => number_format($productWeight,2,'.',''),
      'value' => number_format($productValue,2,'.',''),
      'qtd' => $productQtd,
      'cubic' => $this->getCubic($hasProducts ? $products : $this->cart->getProducts())
    ];
  }

  public function updateBranches(): void {
    //Atualizar lista uma vez por dia
    $this->jamef->getBranches();
    if (!$this->config->get('jamef_lista_filiais') || ($this->config->get('jamef_lista_filiais_save') < (time() - 86400))) {
    } 
  }

	public function CmToM($valor){
	return $valor/100;
	}

	public function Limpar($st){
	$st = str_replace('-','',$st);
	$st = str_replace(' ','',$st);
	$st = str_replace('.','',$st);
	return $st;
	}

	public function getCubic($products) {
      $cubic = 0;
      foreach ($products as $product) {
          $cubic += ($this->CmToM($product['length']) * $this->CmToM($product['width']) * $this->CmToM($product['height'])) * $product['quantity'];
      }
	    
      return number_format($cubic,4,'.','');
   }

   public function date_converter($_date = null) {
       $format = '/^([0-9]{2})\/([0-9]{2})\/([0-9]{2})$/';
       if ($_date != null && preg_match($format, $_date, $partes)) {
           return $partes[3].'-'.$partes[2].'-'.$partes[1];
       }
       return false;
   }

}
