<?php
session_start();
include "connect.php";


$consulta = "select erpc_clientes.id 
				,concat_ws('-',erpc_clientes.ds_endereco,erpc_municipios.ds_municipio,erpc_municipios.ds_uf) as endereco
				,latitude
				,longitude
				from erpc_clientes
				inner join erpc_municipios
				on erpc_clientes.id_municipio = erpc_municipios.id
				where ((longitude is null 
					or latitude is null)
					or
					(longitude = 0 or latitude = 0))
					and st_end_falho is null;";


$user_id = array();
$user_end = array();

$resultado = mysqli_query($conexao, $consulta) or die ($erro = mysqli_error($conexao));
	if (mysqli_num_rows($resultado)>0) {
        while ($registro = mysqli_fetch_assoc($resultado)){
			$usuarios_id = $registro['id'];
			$usuarios_enderecos = $registro['endereco'];
			echo $usuarios_id . ": ";
			echo $usuarios_enderecos . "<br>";
			
			array_push($user_id, $usuarios_id);
			array_push($user_end, $usuarios_enderecos);
		}
	}
?>
<html>
<head></head>

<body>

<div id="resultado">

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyD4vwiv66S3lbvvLb0DxB67mW_2pEiBtJY"></script>
<script type="text/javascript">
$(function() {

  var geocoder = new google.maps.Geocoder();

  var enderecos = [
    <?php
	for($i = 0; $i < sizeof($user_end); $i++) {
	  $endereco = $user_end[$i];
      $endereco = json_encode($endereco);
      echo "$endereco," . PHP_EOL; 
    }
    ?>
  ];

  var etiquetas = [
    <?php
    for($i = 0; $i < sizeof($user_end); $i++) { 
	  $etiqueta = $user_id[$i]; 
      $etiqueta = json_encode($etiqueta); 
      echo "$etiqueta," . PHP_EOL; 
    }
    ?>
  ];
  
  for (var i = 0; i < enderecos.length; i++) {
    var address = enderecos[i];
    geocoder.geocode( { 'address': address}, getCallback(etiquetas[i], enderecos[i]));
  }

  function getCallback(addressId, addressStr) {
    var aFuncao = function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latitude = results[0].geometry.location.lat();
        var longitude = results[0].geometry.location.lng();
        $.post("latitude_longitude_salva_clientes.php", {id: addressId, lat: latitude, lon: longitude});
      } else {
		if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
			var falha_end = "1";
			$.post("latitude_longitude_salva_clientes.php", {id: addressId, end_ruim: falha_end });
		}
      }
    }
    return aFuncao;
  }
});
</script>

</body>
</html>