<?php
	require_once('modules/unirest-php/Unirest.php');
	require_once('config.php');
	require_once('criptar.php');

	$json = utf8_encode($_POST['HTTP_JSON']);
	//$json = file_get_contents('php://input');
	$json = str_replace('', '', $json);
	$json = str_replace('', '', $json);
	$json = str_replace('', '', $json);

	$arr = json_decode($json);

	$sql = "select first 1 API_SERVICO_WMC_URL, API_SERVICO_WMC_USER, API_SERVICO_WMC_TOKEN from CONFIG";
	$query = ibase_query($sql) or die(ibase_errmsg());
	$row = ibase_fetch_row($query);
	
	$url = $row[0];
	$apiKey = Criptar::Cripto('D', $row[1]);
	$token = Criptar::Cripto('D', $row[2]);	

	foreach ($arr as $data) {
		$stop = false;
		
		do {
			//envia os dados da localização
			$headers = array('Content-Type' => 'application/json', 'Authorization' => 'Bearer '.$token);
			$body = json_encode(array(
				'codvendedor' => $data->codvendedor, 
				'datahora' => $data->datahora, 
				'latitude' => $data->latitude,
				'longitude' => $data->longitude,
				'provider' => $data->provider,
				'distance' => $data->distance,
				'speed' => $data->speed,
			));

			$res = Unirest\Request::post($url.'/app/vendedores-location', $headers, $body);	

			if ($res->code == 401) { //caso ocorrer erro de unauthorized,  
				//efetua o login
				$headers = array('Content-Type' => 'application/json', 'api_key' => $apiKey);
				$res = Unirest\Request::post($url.'/auth/login', $headers); 
				$token = $res->body->access_token;

				//grava no banco
				$query = ibase_query("update CONFIG set API_SERVICO_WMC_TOKEN = '".Criptar::Cripto('E', $token)."'") or die(ibase_errmsg()); 
			} else {
				$stop = true;
			}
			
			unset($data);
		} while($stop == false);
	}
	
	http_response_code(200);
	echo "importado com sucesso";
?>