<?php
ini_set("display_errors", 1);
if (!defined('BASEPATH'))
	exit('No direct script access allowed');


class Md_cargo extends CI_Model {

	public function getNearby($lat, $long) {
		$otherdb = $this->load->database('cargo', TRUE);
		$otherdb->select('*, (ACOS(COS(RADIANS('.$lat.')) * COS(RADIANS(latitud)) * COS(RADIANS(longitud) - RADIANS('.$long.')) + SIN(RADIANS('.$lat.')) * SIN(RADIANS(latitud)))) / 0.000156961230576 AS distance FROM sucursales HAVING distance <= 30 ORDER BY distance ASC');
		$otherdb->limit(5);
		$return = $otherdb->get()->result_array();
		return $return;
	}

	public function getCotizacion($codigoPobladoDestino, $codigoPieza, $tipoServicio, $peso) {

		$curl = curl_init();

		curl_setopt_array($curl, array(
		  CURLOPT_URL => "http://ws.caexlogistics.com/wsCAEXLogisticsSB/wsCAEXLogisticsSB.asmx",
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => "",
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 30,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => "POST",
		  CURLOPT_POSTFIELDS => "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n  <soap:Body>\n    <ObtenerTarifaEnvio xmlns=\"http://www.caexlogistics.com/ServiceBus\">\n      <Autenticacion>\n        <Login>WSSMART</Login>\n        <Password>2dec02a897deb2e345c366258e2d4292</Password>\n      </Autenticacion>\n      <DatosEnvio>\n        <CodigoPobladoDestino>$codigoPobladoDestino</CodigoPobladoDestino>\n        <CodigoPieza>$codigoPieza</CodigoPieza>\n        <TipoServicio>$tipoServicio</TipoServicio>\n        <PesoTotal>$peso</PesoTotal>\n        <CodigoCredito></CodigoCredito>\n      </DatosEnvio>\n    </ObtenerTarifaEnvio>\n  </soap:Body>\n</soap:Envelope>",
		  CURLOPT_HTTPHEADER => array(
		    "cache-control: no-cache",
		    "content-type: text/xml",
		    "postman-token: 3a066806-b8f1-0c1f-3b0c-6678c69a999d"
		  ),
		));

		$response = curl_exec($curl);
		$err = curl_error($curl);

		curl_close($curl);

		if ($err) {
			return FALSE;
		} else {

			function xmlToArray($xml, $options = array()) {
				$defaults = array(
						'namespaceSeparator' => ':',//you may want this to be something other than a colon
						'attributePrefix' => '@',   //to distinguish between attributes and nodes with the same name
						'alwaysArray' => array(),   //array of xml tag names which should always become arrays
						'autoArray' => true,        //only create arrays for tags which appear more than once
						'textContent' => '$',       //key used for the text content of elements
						'autoText' => true,         //skip textContent key if node has no attributes or child nodes
						'keySearch' => false,       //optional search and replace on tag and attribute names
						'keyReplace' => false       //replace values for above search values (as passed to str_replace())
				);
				$options = array_merge($defaults, $options);
				$namespaces = $xml->getDocNamespaces();
				$namespaces[''] = null; //add base (empty) namespace

				//get attributes from all namespaces
				$attributesArray = array();
				foreach ($namespaces as $prefix => $namespace) {
						foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
								//replace characters in attribute name
								if ($options['keySearch']) $attributeName =
												str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
								$attributeKey = $options['attributePrefix']
												. ($prefix ? $prefix . $options['namespaceSeparator'] : '')
												. $attributeName;
								$attributesArray[$attributeKey] = (string)$attribute;
						}
				}

				//get child nodes from all namespaces
				$tagsArray = array();
				foreach ($namespaces as $prefix => $namespace) {
						foreach ($xml->children($namespace) as $childXml) {
								//recurse into child nodes
								$childArray = xmlToArray($childXml, $options);
								list($childTagName, $childProperties) = each($childArray);

								//replace characters in tag name
								if ($options['keySearch']) $childTagName =
												str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
								//add namespace prefix, if any
								if ($prefix) $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;

								if (!isset($tagsArray[$childTagName])) {
										//only entry with this key
										//test if tags of this type should always be arrays, no matter the element count
										$tagsArray[$childTagName] =
														in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
														? array($childProperties) : $childProperties;
								} elseif (
										is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
										=== range(0, count($tagsArray[$childTagName]) - 1)
								) {
										//key already exists and is integer indexed array
										$tagsArray[$childTagName][] = $childProperties;
								} else {
										//key exists so convert to integer indexed array with previous value in position 0
										$tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
								}
						}
				}

				//get text content of node
				$textContentArray = array();
				$plainText = trim((string)$xml);
				if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;

				//stick it all together
				$propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
								? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;

				//return node as array
				return array(
						$xml->getName() => $propertiesArray
				);
			}

			$xmlNode = simplexml_load_string($response);

			$arrayData = xmlToArray($xmlNode);
			//echo json_encode($arrayData);

			if($arrayData['Envelope']['soap:Body']['ObtenerTarifaEnvioResponse']['ResultadoObtenerTarifa']['ResultadoOperacion']['ResultadoExitoso'])

			return $arrayData['Envelope']['soap:Body']['ObtenerTarifaEnvioResponse']['ResultadoObtenerTarifa']['MontoTarifa'];

			else

			return FALSE;
		}


	}





	public function getTracking($guia) {

		$curl = curl_init();

		curl_setopt_array($curl, array(
		  CURLOPT_URL => "http://ws.caexlogistics.com/wsCAEXLogisticsSB/wsCAEXLogisticsSB.asmx",
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => "",
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 30,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => "POST",
		  CURLOPT_POSTFIELDS => "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n  <soap:Body>\n    <ObtenerTrackingGuia xmlns=\"http://www.caexlogistics.com/ServiceBus\">\n      <Autenticacion>\n        <Login>WSSMART</Login>\n        <Password>2dec02a897deb2e345c366258e2d4292</Password>\n      </Autenticacion>\n      <NumeroGuia>$guia</NumeroGuia>\n    </ObtenerTrackingGuia>\n  </soap:Body>\n</soap:Envelope>",
		  CURLOPT_HTTPHEADER => array(
		    "cache-control: no-cache",
		    "content-type: text/xml",
		    "postman-token: 3a066806-b8f1-0c1f-3b0c-6678c69a999d"
		  ),
		));

		$response = curl_exec($curl);
		$err = curl_error($curl);

		curl_close($curl);

		if ($err) {
		  echo FALSE;
		} else {

			function xmlToArray($xml, $options = array()) {
				$defaults = array(
						'namespaceSeparator' => ':',//you may want this to be something other than a colon
						'attributePrefix' => '@',   //to distinguish between attributes and nodes with the same name
						'alwaysArray' => array(),   //array of xml tag names which should always become arrays
						'autoArray' => true,        //only create arrays for tags which appear more than once
						'textContent' => '$',       //key used for the text content of elements
						'autoText' => true,         //skip textContent key if node has no attributes or child nodes
						'keySearch' => false,       //optional search and replace on tag and attribute names
						'keyReplace' => false       //replace values for above search values (as passed to str_replace())
				);
				$options = array_merge($defaults, $options);
				$namespaces = $xml->getDocNamespaces();
				$namespaces[''] = null; //add base (empty) namespace

				//get attributes from all namespaces
				$attributesArray = array();
				foreach ($namespaces as $prefix => $namespace) {
						foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
								//replace characters in attribute name
								if ($options['keySearch']) $attributeName =
												str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
								$attributeKey = $options['attributePrefix']
												. ($prefix ? $prefix . $options['namespaceSeparator'] : '')
												. $attributeName;
								$attributesArray[$attributeKey] = (string)$attribute;
						}
				}

				//get child nodes from all namespaces
				$tagsArray = array();
				foreach ($namespaces as $prefix => $namespace) {
						foreach ($xml->children($namespace) as $childXml) {
								//recurse into child nodes
								$childArray = xmlToArray($childXml, $options);
								list($childTagName, $childProperties) = each($childArray);

								//replace characters in tag name
								if ($options['keySearch']) $childTagName =
												str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
								//add namespace prefix, if any
								if ($prefix) $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;

								if (!isset($tagsArray[$childTagName])) {
										//only entry with this key
										//test if tags of this type should always be arrays, no matter the element count
										$tagsArray[$childTagName] =
														in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
														? array($childProperties) : $childProperties;
								} elseif (
										is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
										=== range(0, count($tagsArray[$childTagName]) - 1)
								) {
										//key already exists and is integer indexed array
										$tagsArray[$childTagName][] = $childProperties;
								} else {
										//key exists so convert to integer indexed array with previous value in position 0
										$tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
								}
						}
				}

				//get text content of node
				$textContentArray = array();
				$plainText = trim((string)$xml);
				if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;

				//stick it all together
				$propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
								? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;

				//return node as array
				return array(
						$xml->getName() => $propertiesArray
				);
			}

			$xmlNode = simplexml_load_string($response);

			$arrayData = xmlToArray($xmlNode);
			//echo json_encode($arrayData);

			if($arrayData['Envelope']['soap:Body']['ObtenerTrackingGuiaResponse']['ResultadoObtenerTrackingGuia']['ResultadoOperacion']['ResultadoExitoso']) {
				return '<br>'.$arrayData['Envelope']['soap:Body']['ObtenerTrackingGuiaResponse']['ResultadoObtenerTrackingGuia']['DatosGuia']['Detalle']['Evento'][0]['NombreRuta'].'<br><b>Fecha de registro:</b> '.
				$arrayData['Envelope']['soap:Body']['ObtenerTrackingGuiaResponse']['ResultadoObtenerTrackingGuia']['DatosGuia']['Detalle']['Evento'][0]['FechaHoraScan'].'<br>';
			}	else 	return 'El número de rastreo no fue encontrado';
		}


	}



	public function getRecoleccion($guia) {

		$curl = curl_init();

		curl_setopt_array($curl, array(
		  CURLOPT_URL => "http://ws.caexlogistics.com/wsCAEXLogisticsSB/wsCAEXLogisticsSB.asmx",
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => "",
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 30,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => "POST",
		  CURLOPT_POSTFIELDS => "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n  <soap:Body>\n    <ObtenerTrackingGuia xmlns=\"http://www.caexlogistics.com/ServiceBus\">\n      <Autenticacion>\n        <Login>WSSMART</Login>\n        <Password>2dec02a897deb2e345c366258e2d4292</Password>\n      </Autenticacion>\n      <NumeroGuia>$guia</NumeroGuia>\n    </ObtenerTrackingGuia>\n  </soap:Body>\n</soap:Envelope>",
		  CURLOPT_HTTPHEADER => array(
		    "cache-control: no-cache",
		    "content-type: text/xml",
		    "postman-token: 3a066806-b8f1-0c1f-3b0c-6678c69a999d"
		  ),
		));

		$response = curl_exec($curl);
		$err = curl_error($curl);

		curl_close($curl);

		if ($err) {
		  echo FALSE;
		} else {

			function xmlToArray($xml, $options = array()) {
				$defaults = array(
						'namespaceSeparator' => ':',//you may want this to be something other than a colon
						'attributePrefix' => '@',   //to distinguish between attributes and nodes with the same name
						'alwaysArray' => array(),   //array of xml tag names which should always become arrays
						'autoArray' => true,        //only create arrays for tags which appear more than once
						'textContent' => '$',       //key used for the text content of elements
						'autoText' => true,         //skip textContent key if node has no attributes or child nodes
						'keySearch' => false,       //optional search and replace on tag and attribute names
						'keyReplace' => false       //replace values for above search values (as passed to str_replace())
				);
				$options = array_merge($defaults, $options);
				$namespaces = $xml->getDocNamespaces();
				$namespaces[''] = null; //add base (empty) namespace

				//get attributes from all namespaces
				$attributesArray = array();
				foreach ($namespaces as $prefix => $namespace) {
						foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
								//replace characters in attribute name
								if ($options['keySearch']) $attributeName =
												str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
								$attributeKey = $options['attributePrefix']
												. ($prefix ? $prefix . $options['namespaceSeparator'] : '')
												. $attributeName;
								$attributesArray[$attributeKey] = (string)$attribute;
						}
				}

				//get child nodes from all namespaces
				$tagsArray = array();
				foreach ($namespaces as $prefix => $namespace) {
						foreach ($xml->children($namespace) as $childXml) {
								//recurse into child nodes
								$childArray = xmlToArray($childXml, $options);
								list($childTagName, $childProperties) = each($childArray);

								//replace characters in tag name
								if ($options['keySearch']) $childTagName =
												str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
								//add namespace prefix, if any
								if ($prefix) $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;

								if (!isset($tagsArray[$childTagName])) {
										//only entry with this key
										//test if tags of this type should always be arrays, no matter the element count
										$tagsArray[$childTagName] =
														in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
														? array($childProperties) : $childProperties;
								} elseif (
										is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
										=== range(0, count($tagsArray[$childTagName]) - 1)
								) {
										//key already exists and is integer indexed array
										$tagsArray[$childTagName][] = $childProperties;
								} else {
										//key exists so convert to integer indexed array with previous value in position 0
										$tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
								}
						}
				}

				//get text content of node
				$textContentArray = array();
				$plainText = trim((string)$xml);
				if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;

				//stick it all together
				$propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
								? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;

				//return node as array
				return array(
						$xml->getName() => $propertiesArray
				);
			}

			$xmlNode = simplexml_load_string($response);

			$arrayData = xmlToArray($xmlNode);
			//echo json_encode($arrayData);

			if($arrayData['Envelope']['soap:Body']['ObtenerTrackingGuiaResponse']['ResultadoObtenerTrackingGuia']['ResultadoOperacion']['ResultadoExitoso']) {
				return '<br>'.$arrayData['Envelope']['soap:Body']['ObtenerTrackingGuiaResponse']['ResultadoObtenerTrackingGuia']['DatosGuia']['Detalle']['Evento'][0]['NombreRuta'].'<br><b>Fecha de registro:</b> '.
				$arrayData['Envelope']['soap:Body']['ObtenerTrackingGuiaResponse']['ResultadoObtenerTrackingGuia']['DatosGuia']['Detalle']['Evento'][0]['FechaHoraScan'].'<br>';
			}	else 	return 'El número de rastreo no fue encontrado';
		}


	}

}
