<?php

class Radius {

	public static function outboundTrips($db, $lat, $lng, $radius) {
		return self::radiusTrips($db, $lat, $lng, $radius, 'start');
	}
	
	public static function inboundTrips($db, $lat, $lng, $radius) {
		return self::radiusTrips($db, $lat, $lng, $radius, 'end');
	}

	public static function radiusTrips($db, $lat, $lng, $radius, $what) {
		$limit_lat = (float)$lat;
		$limit_lng = (float)$lng;
		$limit_rad = $radius;
		$q = "SELECT * FROM parsedemail_item WHERE ";
		$q.= "ST_DWithin(location_${what},ST_SetSRID(ST_MakePoint(${limit_lng},${limit_lat}),4326)::geography,${limit_rad})";
		$q.= " ORDER BY id DESC";
		$r = pg_query($db, $q);
		if ($r && pg_num_rows($r)) {
			$result = [];
			while ($f=pg_fetch_assoc($r)) {
				$result[] = $f;
			}
			return [$result, NULL];
		}
		return [NULL,pg_last_error()];
	}
		
	public static function anyTrips($db, $lat, $lng, $radius) {
		$limit_lat = (float)$lat;
		$limit_lng = (float)$lng;
		$limit_rad = $radius;
		$q = "SELECT * FROM parsedemail_item WHERE ";
		$q.= "ST_DWithin(location_start,ST_SetSRID(ST_MakePoint(${limit_lng},${limit_lat}),4326)::geography,${limit_rad})";
		$q.= " OR ST_DWithin(location_end,ST_SetSRID(ST_MakePoint(${limit_lng},${limit_lat}),4326)::geography,${limit_rad})";
		$q.= " ORDER BY id DESC";
		error_log($q);
		$r = pg_query($db, $q);
		if ($r && pg_num_rows($r)) {
			$result = [];
			while ($f=pg_fetch_assoc($r)) {
				$result[] = $f;
			}
			return [$result, NULL];
		}
		return [NULL,pg_last_error()];
	}

	public static function limitTrips($db, $ids, $limit, $what='travel_date', $how='DESC') {
		$q = "SELECT id FROM parsedemail_item WHERE id IN (".implode(",",$ids).") ORDER BY ${what} ${how} LIMIT ${limit}";
		$r = pg_query($db, $q);
		if ($r && pg_num_rows($r)) {
			$result = [];
			while ($f=pg_fetch_assoc($r)) {
				$result[] = $f;
			}
			return [$result, NULL];
		}
		return [NULL,pg_last_error()];
	}
}
// vi:ts=2

