<?php
require("config.php");

// Opens a connection to a MySQL server
/**$connection = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$connection) {
  die("Not connected : " . mysql_error());
}

// Set the active MySQL database
$db_selected = mysql_select_db($dbname, $connection);
if (!$db_selected) {
  die("Can\'t use db : " . mysql_error());
}**/

// Select all the rows in the markers table
$query = "SELECT * FROM gforum_OpenWater WHERE openwater_lat != 0 AND openwater_lat IS NOT NULL";
$result = mysql_query($query);
if (!$result) {
  die("Invalid query: " . mysql_error());
}

// Initialize delay in geocode speed
$delay = 0;
$base_url = "http://" . MAPS_HOST . "/maps/geo?output=csv&key=" . KEY;

// Iterate through the rows, geocoding each address
while ($row = @mysql_fetch_assoc($result)) {
  $geocode_pending = true;

  while ($geocode_pending) {
    $address = "".$row['openwater_address'].", ".$row['openwater_address_two'].", ".$row['openwater_city'].", ".$row['openwater_state']." ".$row['openwater_zip']."";
    $id = $row["openwater_id"];
    $request_url = $base_url . "&q=" . urlencode($address);
    //echo ($request_url);
    //$csv = file_get_contents($request_url) or die("csv url not loading");

	// Create cUrl object to grab XML content using $request_url
	$c = curl_init();
	curl_setopt($c, CURLOPT_URL, $request_url);	
	curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
	$csv = trim(curl_exec($c));
	curl_close($c);

    $csvSplit = split(",", $csv);
    $status = $csvSplit[0];
    $accuracy = $csvSplit[1];
    $lat = $csvSplit[2];
    $lng = $csvSplit[3];
    if (strcmp($status, "200") == 0 && $accuracy >= 5) {
      // successful geocode
      $geocode_pending = false;
      $lat = $csvSplit[2];
      $lng = $csvSplit[3];

      $query = sprintf("UPDATE gforum_OpenWater " .
             " SET openwater_lat = '%s', openwater_lng = '%s' " .
             " WHERE openwater_id = %s LIMIT 1;",
             mysql_real_escape_string($lat),
             mysql_real_escape_string($lng),
             mysql_real_escape_string($id));
      $update_result = mysql_query($query);
      if (!$update_result) {
        die("Invalid query: " . mysql_error());
      }
    } else if (strcmp($status, "620") == 0) {
      // sent geocodes too fast
      $delay += 100000;
    } else if ($accuracy < 5) {
      // failure to geocode
      $geocode_pending = false;
      echo "Address " . $address . " did not geocode to great enough accuracy to be useful. ";
      echo "Accuracy match: " . $accuracy . "
\n";			
    } else {
      // failure to geocode
      $geocode_pending = false;
      echo "Address " . $address . " failed to geocode. ";
      echo "Received status " . $status . "
\n";
    }
    usleep($delay);
  }
}
?>