<?php
	require_once(dirname(__FILE__).'/class.module.php');
	class ISC_JSONFRETE extends ISC_MODULE
	{
	
	public function Simulador(){
	if(isset($_REQUEST['produto']) && isset($_REQUEST['qtd']) && isset($_REQUEST['cep'])){
		$dados = $this->DadosProduto((int)$_REQUEST['produto']);
		$cep = preg_replace('/\D/', '', $_REQUEST['cep']);
		$produto[0]['id'] = (int)$_REQUEST['produto'];
		$produto[0]['peso'] = $dados['prodweight'];
		$produto[0]['com'] = ($dados['proddepth'] <= 0) ? "20" : $dados['proddepth'];
		$produto[0]['alt'] = ($dados['prodheight'] <= 0) ? "20" : $dados['prodheight'];
		$produto[0]['lar'] = ($dados['prodwidth'] <= 0) ? "20" : $dados['prodwidth'];
		$produto[0]['preco'] = $dados['prodcalculatedprice'];
		$produto[0]['tipo'] = $dados['prodtype'];
		$produto[0]['gratis'] = $dados['prodfreeshipping'];
		$produto[0]['fretefixo'] = $dados['prodfixedshippingcost'];
		$produto[0]['qtd'] = (int)$_REQUEST['qtd'];
		echo json_encode($this->MeiosAtivosPorCep($produto,$cep));
	}else{
		$this->ProcessarJson('Informe seu CEP!');
	}
	}
	
	public function ProcessarJson($erro){
		$dados['erro'] = 'sim';
		$dados['msg'] = $erro;
		echo json_encode($dados);
		exit;
	}
	
	public function DadosProduto($id){
		$query = sprintf("select * from [|PREFIX|]products WHERE productid='%d'", $id);
		$con = $GLOBALS['ISC_CLASS_DB']->Query($query);
		return $GLOBALS['ISC_CLASS_DB']->Fetch($con);
	}
	
	public function MeiosAtivosPorCep($produtos,$cep){
			//dados envio
			$address = array(
				'shipcountryid' => 30,
				'shipstateid' => '',
				'shipzip' => $cep
			);
			//pega a zona de envio
			$products = $produtos;
			$shippingZone = GetShippingZoneIdByAddress($address, 0);
			$zone = GetShippingZoneById($shippingZone);
			$shippingQuotes = array();
			$shippableTotal = 0;
			$subTotal = 0;
			$fixedShippingCost = 0;
			$fixedShippingProducts = 0;
			$methodHandling = 0;
			$shippingQuoteProducts = array();
			$includesDigitalProducts = false;
			$freteGratis = false;
			//lista os produtos
			foreach($products as $k => $product) {
				$quantity = (int)$product['qtd'];
				$price = $product['preco'];
				$subTotal += $quantity * $price;

				if($product['tipo'] == PT_PHYSICAL && $product['fretefixo'] == 0) {
					$shippableTotal += $quantity * $price;
				}
				
				if($product['gratis']==1){
				$freteGratis = true;
				}

				if ($product['tipo'] == PT_PHYSICAL && (!isset($product['gratis']) || $product['gratis'] != 1)) {
					if ($product['fretefixo'] > 0) {
						$fixedShippingCost += $product['fretefixo'] * $quantity;
						++$fixedShippingProducts;
					}
					else {
						$shippingQuoteProducts[$k] = $k;
					}
				}
				else if($product['tipo'] == PT_DIGITAL) {
					$includesDigitalProducts = true;
				}
			}
			
			//taxas
			$zoneHandlingFee = 0;
			if($zone['zonehandlingtype'] == 'global' && $zone['zonehandlingseparate']) {
				$zoneHandlingFee = $zone['zonehandlingfee'];
				if($includesDigitalProducts) {
					$zoneHandlingFee += GetConfig('DigitalOrderHandlingFee');
				}
			}
			
			//se for frete gratis
			if(($zone['zonefreeshipping'] == 1 && $subTotal >= $zone['zonefreeshippingtotal']) || $freteGratis) {
				$adjustedPrice = $this->FactorInZoneHandling($shippingZone, 0, 0, $includesDigitalProducts);
				if($adjustedPrice > 0) {
					$freeShippingName = GetModuleVariable('addon_simuladorpro','tag_fixo');
					$modulo = 'frete_fixo';
					$prazo = GetModuleVariable('addon_simuladorpro','prazo_fixo');
				}
				else {
					$freeShippingName = GetModuleVariable('addon_simuladorpro','tag_gratis');
					$modulo = 'frete_gratis';
					$prazo = GetModuleVariable('addon_simuladorpro','prazo_gratis');
				}
				$shippingQuotes[] = array(
					'description' => $freeShippingName,
					'price' => $adjustedPrice,
					'methodId' => -1,
					'module' => $modulo,
					'handling' => $zoneHandlingFee,
					'transit' => $prazo
				);
				return $shippingQuotes;
			}
			
			//todos os produtos com custo fixo de envio
			if($fixedShippingProducts == count($products) || empty($shippingQuoteProducts)) {
				$adjustedPrice = $this->FactorInZoneHandling($shippingZone, $fixedShippingCost, 0, $includesDigitalProducts);
				if($adjustedPrice > 0) {
					$shippingName = GetModuleVariable('addon_simuladorpro','tag_fixo');
					$modulo = 'frete_fixo';
					$prazo = GetModuleVariable('addon_simuladorpro','prazo_fixo');
				}
				else {
					$shippingName = GetModuleVariable('addon_simuladorpro','tag_gratis');
					$modulo = 'frete_gratis';
					$prazo = GetModuleVariable('addon_simuladorpro','prazo_gratis');
				}
				$shippingQuotes[] = array(
					'description' => $shippingName,
					'price' => $adjustedPrice,
					'methodId' => -1,
					'module' => $modulo,
					'handling' => $zoneHandlingFee,
					'transit' => $prazo
				);
				return $shippingQuotes;
			}
			
			//lista os meios de envio por zona
			$query = "
				SELECT *
				FROM [|PREFIX|]shipping_methods
				WHERE zoneid='".(int)$shippingZone."' AND methodenabled='1'";
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
			while($method = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			
				if($zone['zonehandlingtype'] == 'module' && $zone['zonehandlingseparate']) {
					$methodHandling = $method['methodhandlingfee'];
					if($includesDigitalProducts) {
						$methodHandling += GetConfig('DigitalOrderHandlingFee');
					}
				}
				else {
					$methodHandling = $zoneHandlingFee;
				}

			$shippingModule = null;
			GetModuleById('shipping', $shippingModule, $method['methodmodule']);
			if(!is_object($shippingModule)) {
					continue;
			}

			$shippingModule->SetMethodId($method['methodid']);
			
			foreach($produtos as $id=>$item) {
			        //$shippableTotal += $item['qtd'] * $item['preco'];
					$shippingModule->AddItem($item['peso'],
						$item['com'],
						$item['lar'],
						$item['alt'],
						$item['qtd'],
						'',
						$item['preco']
					);
			}
			
			//configuracoes de destino
			$shippingModule->SetDestinationCountry($address['shipcountryid']);
			if(!isset($address['shipstate'])) {
				$address['shipstate'] = GetStateById($address['shipstateid']);
			}
			$shippingModule->SetDestinationState($address['shipstate']);
			$shippingModule->SetDestinationZip($address['shipzip']);
			$shippingModule->SetDestinationType("RES");
			$shippingModule->SetSubTotal($shippableTotal);
			
					//pega as contacoes
					$moduleQuotes = array();
					if(method_exists($shippingModule, 'GetServiceQuotes')) {
					$methodQuotes = $shippingModule->GetServiceQuotes();
					
					if($methodQuotes === false) {
						continue;
					}
					if(!is_array($methodQuotes)) {
						$methodQuotes = array($methodQuotes);
					}
					// For each of the returned quotes, add them to the quote stack
					foreach($methodQuotes as $quote) {
						if(!is_object($quote)) {
							$quote = $quote[0];
						}
						$nome = $shippingModule->GetDisplayName();
						if(GetModuleVariable('addon_simuladorpro','nomes')=='1'){
						$nome = $quote->getdesc(true);
						}
						$shippingQuotes[] = array(
							'description' => utf8_encode($nome),
							'price' => number_format($this->FactorInZoneHandling($shippingZone, $quote->GetPrice()+$fixedShippingCost, $method['methodhandlingfee'], $includesDigitalProducts), 2, '.', ''),
							'handling' => $methodHandling,
							'module' => $method['methodmodule'],
							'methodId' => $method['methodid']
						);

						// Get the transit time
						if($quote->GetTransit() != '' && $quote->GetTransit() != -1) {
							$shippingQuotes[count($shippingQuotes)-1]['transit'] = utf8_encode($quote->GetTransit());
						}
					}
					}else{//flate rate
					$err = '';
					$quote = $shippingModule->GetQuote($err);
					if($quote !== false) {
						$nome = $shippingModule->GetDisplayName();
						if(GetModuleVariable('addon_simuladorpro','nomes')=='1'){
						$nome = $quote->getdesc(true);
						}
						$shippingQuotes[] = array(
							'description' => $nome,
							'price' => number_format($this->FactorInZoneHandling($shippingZone, $quote->GetPrice()+$fixedShippingCost, $method['methodhandlingfee'], $includesDigitalProducts), 2, '.', ''),
							'handling' => $methodHandling,
							'module' => $method['methodmodule'],
							'methodId' => $method['methodid']
						);
					}
					}
			}
			//ordena por os menores valores
			uasort($shippingQuotes, array($this, 'SortShippingQuotes'));
			return $shippingQuotes;
	}
	private function SortShippingQuotes($a, $b) {
			if($a['price'] == $b['price']) {
				return 0;
			}
			else if($a['price'] < $b['price']) {
				return -1;
			}
			else {
				return 1;
			}
	}
	public function FactorInZoneHandling($zoneId, $price, $methodHandling, $includeDigitalHandling=false){
			$zone = GetShippingZoneById($zoneId);

			if(!is_array($zone)) {
				return $price;
			}
			else if($zone['zonehandlingseparate'] == 1) {
				return $price;
			}

			$digitalHandling = 0;
			if($includeDigitalHandling == true && GetConfig('DigitalOrderHandlingFee')) {
				$digitalHandling = GetConfig('DigitalOrderHandlingFee');
			}

			if($zone['zonehandlingtype'] == 'module') {
				return $price + $methodHandling + $digitalHandling;
			}
			else if($zone['zonehandlingtype'] == 'global') {
				return $price + $zone['zonehandlingfee'] + $digitalHandling;
			}
			else {
				return $price + $digitalHandling;
			}
	}
	}
?>