<!DOCTYPE html>
<html>
  <head>
    <title>
      Simple Address App
    </title>
    <meta charset=utf-8 />    
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" media="screen" href="css/master.css" />
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <style>
      #gmap {
        width:100%;
        height:400px;
        border:thin solid black;
      }

    </style>
    <?php
    $gmap_api_key 
get_gmap_api_referer_key();
    
$page_log '';
    
$cwd getcwd();
    
$address_db_file "$cwd/address.db";
    if (!
is_writable($cwd)) {
      die (
"Error: SQLite can not write to $address_db_file unless $cwd is writable");
    }
    if (!
is_writable($address_db_file)) {
      die (
"Error: SQLite does not have write permission to $address_db_file\n");
    }
    
$dbh = new PDO ("sqlite:$address_db_file'''',
                    array(
PDO::ATTR_PERSISTENT => true));

    
$default_address_id '';
    
$default_street     '';
    
$default_city       '';
    
$default_state      '';
    
$default_zip        '';
    if (isset(
$_POST['save:new']) || isset($_POST['save:edit'])) {
      
$address_id $_POST['address_id'];
      
$street     $_POST['street'];
      
$city       $_POST['city'];
      
$state      $_POST['state'];
      
$zip        $_POST['zip'];

      
$loc geocode ($street$city$state$zip);
      
$lat $loc['lat'];
      
$lng $loc['lng'];

      if (isset(
$_POST['save:new'])) {
        
$sth $dbh->prepare ("
          INSERT INTO address (rowid, street, city, state, zip, lat, lng)
            VALUES (NULL, ?, ?, ?, ?, ?, ?)
        "
);
        
$sth->execute (array($street$city$state$zip$lat$lng));
      }
      elseif (isset(
$_POST['save:edit'])) {
        
$sth $dbh->prepare("
          UPDATE address
            SET street=?, city=?, state=?, zip=?,
              lat=?, lng=?
            WHERE id=?
        "
);
        
$sth->execute (array($street$city$state$zip$lat$lng$address_id));
      }
    }
    
$cmd_array preg_grep ('{(edit|delete):\d+}'array_keys($_POST));
    
$edit '';
    
$save 'new';
    if (
$cmd_array) {
      
$matches = array();
      
preg_match ('{(edit|delete):(\d+)}'array_shift($cmd_array), $matches);
      
$cmd $matches[1];
      
$id $matches[2];
      
$page_log .= "cmd: $cmd, id: $id\n";

      if (
$cmd == 'edit') {
        
$sth $dbh->prepare("SELECT * FROM address WHERE id=?");
        
$sth->execute(array($id));
        
$row $sth->fetch(PDO::FETCH_ASSOC);
        
$default_address_id $row['id'];
        
$default_street $row['street'];
        
$default_city   $row['city'];
        
$default_state  $row['state'];
        
$default_zip    $row['zip'];
        
$save 'edit';
      }
      elseif (
$cmd == 'delete') {
        
$sth $dbh->prepare("DELETE FROM address WHERE id=?");
        
$sth->execute (array($id));
      }
    }
    
$is_edit_mode $default_address_id != 0;
    
$page_log .= "city: $default_city\n";

    
$sth $dbh->query('SELECT * FROM address');
    
$sth->execute();
    
$all_addresses = array();
    while (
$row $sth->fetch(PDO::FETCH_ASSOC)) {
      
array_push ($all_addresses$row);
    }
    
?>
    <script type="text/javascript">
      function initMap() {
        var map = new google.maps.Map(
          document.getElementById("gmap"),
          {
            zoom: 10,
            center: {lat: 37.4230750, lng: -121.8818120},
          }
        );
        <?php 
        
foreach ($all_addresses as $address) {
          
$id $address['id'];
          
$street addslashes($address['street']);
          
$lat $address['lat'];
          
$lng $address['lng'];
          print 
"
            var marker
$id = new google.maps.Marker({
              position: new google.maps.LatLng(
$lat,$lng),
              map: map,
              title: '
$street'
            });
          "
;
        }
        
?>
      }

    </script>
    <script async defer 
      src="https://maps.googleapis.com/maps/api/js?key=<?php echo $gmap_api_key ?>&callback=initMap"
      type="text/javascript">
    </script>
  </head>
  <body>
    <div class='container-fluid'>
      <h2>Simple Address App</h2>
      <?php
        
#print "<pre>\n";
        #print "page_log: $page_log\n";
        #print "</pre>\n";
      
?>
      <form action="address_app.php" method="post">
      <input type="hidden" name="address_id"
            value="<?php echo $default_address_id ?>" />
      <div class="row">
        <div class="col-md-4">
          <?php 
            
if ($all_addresses) {
              print 
"<h3>Current Addresses</h3>\n";
            }
          
?>
          <ul class="list-group">
            <?php
              
foreach ($all_addresses as $address) {
                
$id     $address['id']; # database row id
                
$street htmlspecialchars($address['street']);
                
$city   htmlspecialchars($address['city']);
                
$state  htmlspecialchars($address['state']);
                
$zip    htmlspecialchars($address['zip']);
                print 
"
                <li class='list-group-item'>
                  <div class='btn-group' role='group' aria-label='edit_delete' style='float:right'>
                    <button type='submit' class='btn btn-default'
                        name='edit:
$id'>
                      Edit
                    </button>
                    <button type='submit' class='btn btn-default'
                      name='delete:
$id' >
                        Delete
                    </button>
                  </div>
                  <div>
                    
$street<br />
                    
$city$state $zip
                  </div>
                </li>
                "
;
              }
            
?>
          </ul>
        </div>
        <div class="col-md-4">
          <h3>
            <?php echo $is_edit_mode 'Edit address' 'Enter new address' ?>
          </h3>
          <div class="form-group">
            <label for="street">Street</label>
            <input type="text" class="form-control" id="street" name="street"
                   placeholder="Street" value="<?php echo $default_street ?>" >
          </div>
          <div class="form-group">
            <label for="city">City</label>
            <input type="text" class="form-control" id="city" name="city"
                   placeholder="City" value="<?php echo $default_city ?>" >
          </div>
          <div class="form-group">
            <label for="state">State</label>
            <input type="text" class="form-control" id="state" name="state"
                   placeholder="State" value="<?php echo $default_state ?>">
          </div>
          <div class="form-group">
            <label for="zip">Zip</label>
            <input type="text" class="form-control" id="zip" name="zip"
                   placeholder="Zip" value="<?php echo $default_zip ?>">
          </div>
          <button type="submit" class="btn btn-default" name="save:<?php echo $save?>" >
            Save <?php echo $is_edit_mode 'Edit' 'New'?>
          </button>
        </div>
        <div class="col-md-4">
          <div id="gmap">
          </div>
        </div>
      </div>
      </form>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
    </script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
    </script>
  </body>
</html>
<?php

function slurp_line($filename) {
  
$file_h fopen ($filename'r');
  
$line fgets($file_h);
  
fclose($file_h);

  return 
trim($line);
}

function 
get_gmap_api_referer_key () {
  return 
slurp_line('gmap_api_referer_key.txt');
}

function 
get_gmap_api_site_key () {
  return 
slurp_line('gmap_api_site_key.txt');
}


function 
geocode ($street$city$state$zip) {
  
$address_string "$street$city$state$zip";
  
$address_string urlencode($address_string);

  
// create curl resource
  
$ch curl_init();

  
$gmap_api_key get_gmap_api_site_key();
  
$url "https://maps.googleapis.com/maps/api/geocode/json?address=$address_string&key=$gmap_api_key";
  
curl_setopt($chCURLOPT_URL$url);

  
//return the transfer as a string
  
curl_setopt($chCURLOPT_RETURNTRANSFER1);

  
// $output contains the output string
  
$output curl_exec($ch);

  
// close curl resource to free up system resources
  
curl_close($ch);

  
#$geo_loc = new SimpleXMLElement ($output);
  #$lat = $geo_loc->result->geometry->location->lat;
  #$lng = $geo_loc->result->geometry->location->lng;
  
$geo_loc json_decode($output);
  
#$page_log .= var_export($geo_loc, TRUE);
  
$status $geo_loc->status;
  if (
$status != "OK") { 
    
$error_message $geo_loc->error_message;
    die(
"$status$error_message");
  }
  
$location $geo_loc->results[0]->geometry->location;
  
$lat $location->lat;
  
$lng $location->lng;

  return array(
"lat"=>$lat"lng"=>$lng);
}
?>