<?php

class Scooter {

	public function getAddressById($db, $id) {
		$result = array();
		$q = "SELECT * FROM address WHERE id=".((int)$id);
		$r = pg_query($db, $q);
		if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
      $f["address"] = html_entity_decode ($f["address"],ENT_QUOTES|ENT_HTML5,"UTF-8");
			$result = $f;
		}
		return $result;
	}

	public function save($db, $result) {
		return Address::save($db, $result);
	}

	public function getTimezone($db, $timezone) {
		$db_timezone = pg_escape_string($timezone);
		$q = "SELECT id FROM address_timezone WHERE timezone='${db_timezone}'";
		$r = pg_query($db, $q);
		if ($r && pg_num_rows($r) && $f=pg_fetch_row($r)) {
			return $f[0];
		}
		$q = "INSERT INTO address_timezone (timezone) VALUES('${db_timezone}') RETURNING id";
		$r = pg_query($db, $q);
		if ($r && pg_num_rows($r) && $f=pg_fetch_row($r)) {
			return $f[0];
		}
		return NULL;
	}

	public function checkDistanceCache($db, $fromLat, $fromLng, $toLat, $toLng) {
		$db_fromLat = (float)$fromLat;
		$db_fromLng = (float)$fromLng;
		$db_toLat = (float)$toLat;
		$db_toLng = (float)$toLng;
		$q = "SELECT distance,duration FROM address_distance_cache WHERE ";
		$q.= "start_lat=${db_fromLat} AND start_lng=${db_fromLng} AND end_lat=${db_toLat} AND end_lng=${db_toLng}";
		$r = pg_query($db, $q);
		if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
			return array($f, NULL);
		}
		return array(NULL,pg_last_error($db));
	}

	public function saveDistanceCache($db, $fromLat, $fromLng, $toLat, $toLng, $data) {
		$db_fromLat = (float)$fromLat;
		$db_fromLng = (float)$fromLng;
		$db_toLat = (float)$toLat;
		$db_toLng = (float)$toLng;
		$distance = $data["distance"];
		$duration = $data["duration"];
		$q = "INSERT INTO address_distance_cache (start_lat,start_lng,end_lat,end_lng,distance,duration) VALUES (";
		$q.= "${db_fromLat},${db_fromLng},${db_toLat},${db_toLng},${distance},${duration}) RETURNING id";
		$r = pg_query($db, $q);
		if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
			return array($f, NULL);
		}
		return array(NULL,pg_last_error($db));
	}
}

// vi:ts=2

