<?php
class ModelShippingJamef extends Model {

	public function getQuote($address) {
		$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')) {
			$status = true;
		} elseif ($query->num_rows) {
			$status = true;
		} else {
			return array();
		}

		if (!$this->config->get('jamef_status')) {
			return array();
		}

		// limites
		$peso_real = $this->cart->getWeight();
		$total_real = $this->cart->getSubTotal();
		$p_min = $this->config->get('jamef_peso_minimo');
		$t_min = $this->config->get('jamef_total_minimo');
		if ($peso_real < $p_min || $total_real < $t_min) {
			return array();
		}

		$method_data = array();
		$quote_data = array();

		$tipoa = $this->config->get('jamef_tipoa');
		$tipor = $this->config->get('jamef_tipor');

		if ($status) {

			$titulo = $this->config->get('jamef_nome');

			//jamef rodoviario
			if ($tipor == 1) {
				$mt3 = $this->ProdutosMt3();
				$url = "https://www.jamef.com.br/frete/rest/v1/1/".preg_replace('/\D/', '', $this->config->get('jamef_user'))."/".trim($this->config->get('jamef_cidade'))."/".trim($this->config->get('jamef_uf'))."/4/".number_format(($mt3*300), 2, '.', '')."/".number_format($total_real, 2, '.', '')."/".$mt3."/".preg_replace('/\D/', '', $address['postcode'])."/".trim($this->config->get('jamef_filial'))."/".date('d')."/".date('m')."/".date('Y')."/".trim($this->config->get('jamef_login'))."";

				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$server_output = curl_exec($ch);
				$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
				curl_close($ch);

				if ($server_output && $httpcode == 200) {
					$calculo = json_decode($server_output, true);
					if (isset($calculo['valor'])) {
						$valor_frete = $calculo['valor'];
						$valor_frete += (float)$this->config->get('jamef_taxa');

						if (isset($calculo['previsao_entrega']) && !empty($calculo['previsao_entrega'])) {
							$data = $this->dta($calculo['previsao_entrega']);
							$prazo = "(entrega até {$data})";
						} else {
							$prazo = '';
						}

						$quote_data['1'] = array(
							'code'         => 'jamef.1',
							'title'        => trim("{$titulo} Rodoviário {$prazo}"),
							'cost'         => $this->tax->calculate($valor_frete, $this->config->get('jamef_tax_class_id'), $this->config->get('config_tax')),
							'tax_class_id' => $this->config->get('jamef_tax_class_id'),
							'text'         => $this->formatar($this->tax->calculate($valor_frete, $this->config->get('jamef_tax_class_id'), $this->config->get('config_tax')))
						);
					}
				} else {
					$server_output = print_r($server_output, true);
					$this->log->write("Jamef REST Rodoviário ERRO: HTTP {$httpcode}\n{$url}\n{$server_output}");
				}
			}

			//jamef aereo
			if ($tipoa == 1) {
				$mt3 = $this->ProdutosMt3();
				$url = "https://www.jamef.com.br/frete/rest/v1/2/".preg_replace('/\D/', '', $this->config->get('jamef_user'))."/".trim($this->config->get('jamef_cidade'))."/".trim($this->config->get('jamef_uf'))."/4/".number_format(($mt3*166), 2, '.', '')."/".number_format($total_real, 2, '.', '')."/".$mt3."/".preg_replace('/\D/', '', $address['postcode'])."/".trim($this->config->get('jamef_filial'))."/".date('d')."/".date('m')."/".date('Y')."/".trim($this->config->get('jamef_login'))."";

				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$server_output = curl_exec($ch);
				$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
				curl_close($ch);

				if ($server_output && $httpcode == 200) {
					$calculo = json_decode($server_output, true);
					if (isset($calculo['valor'])) {
						$valor_frete = $calculo['valor'];
						$valor_frete += (float)$this->config->get('jamef_taxa');

						if (isset($calculo['previsao_entrega']) && !empty($calculo['previsao_entrega'])) {
							$data = $this->dta($calculo['previsao_entrega']);
							$prazo = "(entrega até {$data})";
						} else {
							$prazo = '';
						}

						$quote_data['2'] = array(
							'code'         => 'jamef.2',
							'title'        => trim("{$titulo} Aéreo {$prazo}"),
							'cost'         => $this->tax->calculate($valor_frete, $this->config->get('jamef_tax_class_id'), $this->config->get('config_tax')),
							'tax_class_id' => $this->config->get('jamef_tax_class_id'),
							'text'         => $this->formatar($this->tax->calculate($valor_frete, $this->config->get('jamef_tax_class_id'), $this->config->get('config_tax')))
						);
					}
				} else {
					$server_output = print_r($server_output, true);
					$this->log->write("Jamef REST Aéreo ERRO: HTTP {$httpcode}\n{$url}\n{$server_output}");
				}
			}

			//se retornou fretes
			if (count($quote_data) > 0) {
				$method_data = array(
					'code'       => 'jamef',
					'title'      => $this->config->get('jamef_nome'),
					'quote'      => $quote_data,
					'sort_order' => $this->config->get('jamef_sort_order'),
					'error'      => false
				);
			}
		}

		return $method_data;
	}

	public function formatar($valor){
		if (version_compare(VERSION, '2.2.0.0', '>=')) {
			return $this->currency->format($valor, $this->session->data['currency']);
		} else {
			return $this->currency->format($valor);
		}
	}

	public function ProdutosMt3(){
		$produtos = $this->cart->getProducts();
		$metro_cubico = 0;
		foreach ($produtos as $prod) {
			$lar = $this->getDimensaoEmMetro($prod['length_class_id'], $prod['length']);
			$alt = $this->getDimensaoEmMetro($prod['length_class_id'], $prod['height']);
			$com = $this->getDimensaoEmMetro($prod['length_class_id'], $prod['width']);
			$metro_cubico += ($lar * $com * $alt * $prod['quantity']);
		}
		return number_format($metro_cubico, 3, '.', '');
	}

	public function ProdutosQtd(){
		$produtos = $this->cart->getProducts();
		$qtd = 0;
		foreach ($produtos as $prod) {
			$qtd += $prod['quantity'];
		}
		return $qtd;
	}

	private function dta($data){
		$ex = (int)$this->config->get('jamef_prazo');
		if ($ex > 0) {
			$e = explode('/', $data);
			$nova = (string)$e[2].'-'.$e[1].'-'.$e[0];
			$a1 = strtotime("{$nova} +{$ex} days");
			return date('d/m/Y', (int)$a1);
		} else {
			return $data;
		}
	}

	private function getDimensaoEmMetro($unidade_id, $dimensao){
		if (is_numeric($dimensao)) {
			$length_class_product_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "length_class mc LEFT JOIN " . DB_PREFIX . "length_class_description mcd ON (mc.length_class_id = mcd.length_class_id) WHERE mcd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND mc.length_class_id = '" . (int)$unidade_id . "'");
			if (isset($length_class_product_query->row['unit'])) {
				if ($length_class_product_query->row['unit'] == 'mm') {
					return $dimensao / 1000;
				}
				if ($length_class_product_query->row['unit'] == 'cm') {
					return $dimensao / 100;
				}
			}
		}
		return $dimensao;
	}

	private function getPesoEmKg($unidade_id, $peso){
		if (is_numeric($peso)) {
			$weight_class_product_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "weight_class wc LEFT JOIN " . DB_PREFIX . "weight_class_description wcd ON (wc.weight_class_id = wcd.weight_class_id) WHERE wcd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND wc.weight_class_id = '" . (int)$unidade_id . "'");
			if (isset($weight_class_product_query->row['unit'])) {
				if ($weight_class_product_query->row['unit'] == 'g') {
					return ($peso / 1000);
				}
			}
		}
		return $peso;
	}
}
