<?php

class Geofence {

  public static function getAnchor($db, $lat, $lng) {
    error_log("Geofence::getAnchor(\$db, $lat, $lng)");
    $limit_lat = (float)$lat;
    $limit_lng = (float)$lng;
    // Step 0: Find out city
    $city_id = 2; // 1096; // TODO!!!!!!!!!!!

    // Step 1: Find out area
    $q = "SELECT * FROM geofence_area WHERE city_id=${city_id}";
    $r = pg_query($db, $q);
    if (!$r || pg_num_rows($r)<1) {
      // TODO: load closest city address
      return [NULL, "This city has no areas available"];
    }
    $area = NULL;
    while ($f=pg_fetch_assoc($r)) {
      // TODO: Remember area coordinates
      // TODO: Calculate distance to area coordinates
      if ($f["type"]=='polygon') {
        $data = json_decode($f["boundaries"],true);
        if (is_array($data) && array_key_exists('polygon',$data) && is_array($data["polygon"]) && count($data["polygon"])>0) {
          $polygon = $data["polygon"];
          $polygonCoords = [];
          foreach ($polygon as $coord) {
            $polygonCoords[] = "$coord[0] $coord[1]";
          }
          $polygonCoordsString = implode(",", $polygonCoords);
          $q = "SELECT ST_Contains(ST_GeomFromText('POLYGON((${polygonCoordsString}))', 4326), ST_SetSRID(ST_Point (" . $lng . ", " . $lat . "), 4326)) as iscorrect";
          $i = pg_query($db, $q);
          if ($i && pg_num_rows($i) && $j = pg_fetch_assoc($i)) {
            if ($j["iscorrect"] == 't') {
              $area = $f;
              break;
            } // Is not within the polygon
          } // Polyfon data processing failed
        } // Polygon data is missing
      } // Not polygon
    }
    // Step 2: Find out anchor
    if (is_array($area) && array_key_exists('id',$area) && $area["id"]>0) {
      $q = "SELECT a.title,b.*,ST_DistanceSphere(b.geometry::geometry, ST_SetSRID(ST_MakePoint(" . $lng . ", " . $lat . "),4326)) AS distance ";
      $q.= " FROM geofence_area_anchor a, address b WHERE a.geofence_area_id=" . $area["id"] . " AND b.id=a.address_id";
      $r = pg_query($db, $q);
      if (!$r || pg_num_rows($r)<1) {
        // TODO: other?
        return [NULL, "Geofence area has no anchors"];
      }
      $distance = PHP_INT_MAX;
      $address = NULL;
      while ($f=pg_fetch_assoc($r)) {
        // TODOL We might need direction or another parameter
        if ($distance>$f["distance"]) {
          $distance = $f["distance"];
          $address = $f;
        }
      }
      if (is_array($address) && array_key_exists('address',$address) && $address["address"]!="") {
        return [$address, NULL];
      }
    }
    // No area, try GPS coordinates? 
    return [NULL, "Anchor address not found"];
  }
	
	public function youVsOthersOnCategory($db, $gpsdb, $data) {
		error_log('Compare::youVsOthersOnCategory($db, $gpsdb, $data) ');
		$db_country = pg_escape_string($data['country']); // is not used for now...
		$db_address = pg_escape_string($data['address']);
		$member_id = (int)$data['member_id'];
		$category = $data['category']; // see ByCategory::CATEGORIES
		$days = (int)$data['days'];
		//$member_id = 3; // DEBUG
		if ($member_id<1) {
			error_log("Invalid member_id='${member_id}'");
			return NULL;
		}
		if ($category=='' || !array_key_exists($category,ByCategory::CATEGORIES)
		|| ByCategory::CATEGORIES[$category]!=1) {
			error_log("Invalid category='${category}'");
			return NULL;
		}
		if ($days<7) $daya = 7;

		$you = ByCategory::andMemberIdForDaysTotal($db, $category, $member_id, $days);
		$avg = ByCategory::averageForDaysTotal($db, $category, $member_id, $days);

		return [
			"member_id" => $member_id,
			"category" => $category,
			"days" => $days,
			"you" => $you,
			"average" => $avg,
			"compare" => self::compareYouVsAverage($you,$avg)
		];
	}

}

// vi:ts=2

