<?php

function save_tracked($in) {
	global $tracklocation_dir, $pgconn;
	if ($in["batch"]) {
		$response = [
			"retval" => PHP_API_OK,
			"status" => 0,
			"error" => NULL,
			"details" => []
		];
		try {
			$sessionId = null;
			$deviceToken = null;
			$requestHeaders = getallheaders();
			if (array_key_exists("x-session-id",$requestHeaders)) {
				$sessionId = $requestHeaders["x-session-id"];
			}
			if (array_key_exists("x-devicetoken",$requestHeaders)) {
				$deviceToken = $requestHeaders["x-devicetoken"];
				$q = "SELECT * FROM members_devices WHERE access_token='".pg_escape_string($deviceToken)."'";
				$r = pg_query($pgconn, $q);
				if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
					$q = "UPDATE members_devices SET updated=now(), status=1 WHERE id=".((int)$f['id'])." RETURNING *";
					$r = pg_query($pgconn, $q);
					if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
						error_log('Status updated at: '.$f['updated']);
					}
				}
			}
			$data = [
				"batch" => $in["batch"],
				"loc" => $in["loc"],
			  "sessionId" => $sessionId,
				"deviceToken" => $deviceToken
			];
			$session = $in["session"];
			file_put_contents( $tracklocation_dir.'tl_'.getmygid().'_'.$sessionId.'_'.microtime(true).'.json', json_encode($data));
		} catch(Exception $e) {
			$response["retval"] = -1;
			$response["error"] = $e->getMessage();
		}
		return $response;
	} else {
		return save_tracked_vintage($in);
	}
}

function save_tracked_vintage($in) {
	global $pgconn_gps;
	$message = "";
	list ($pass, $device, $session) = checkRequestHeaders(
		'tracklocation',
		$in,
		[],
		['tracklocation' => 1]
	);

	if ($in["member_id"]>0 && $in["lng"]!="" && $in["lat"]!="") {
		$device_id = (isset($device) && array_key_exists("id",$device) && $device["id"]>0) ? $device["id"] : "NULL";
		$mysql = "INSERT INTO members_tracking (member_id,traked_group,speed,lat,lng,gps,ttime,loc,device_id) ";
		$mysql.= " VALUES(" . $in["member_id"] . ",'" . $in["traked_group"] . "','" . $in["speed"] . "', " . $in["lat"] . "," . $in["lng"] . ",ST_SetSRID(ST_MakePoint(" . $in["lng"] . "," . $in["lat"] . "),4326)::geography,now(),'" . $in["loc"] . "',";
		$mysql.= "${device_id}) RETURNING *";
		LogString("Query->", $mysql);
		$r = pg_query($pgconn_gps, $mysql);
		if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
			$nid = $f["id"];
			$gps = $f["gps"];
			$ttime = $f["ttime"];
			// TODO: merge two next queries into one???
			$q = "SELECT id AS pid, ST_Distance(gps,'${gps}'::geometry) AS distance,";
			$q.= "EXTRACT(epoch FROM '${ttime}'::timestamp-ttime) AS duration ";
			$q.= "FROM members_tracking ";
			$q.= "WHERE member_id=".$in["member_id"]." AND ttime<'${ttime}'::timestamp AND ";
			$q.= ($device_id=="NULL" ? "device_id IS NULL" : "device_id=${device_id}");
			$q.= " ORDER BY ttime DESC LIMIT 1";
			LogString("Query->", $q);
			$r = pg_query($pgconn_gps, $q);
			if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
				$pid = $f["pid"];
				/*
				$q = "SELECT a.id AS nid, b.id AS pid, ";
				$q.= "ST_Distance(a.gps,b.gps) AS distance, EXTRACT(epoch FROM a.ttime-b.ttime) AS duration ";
				$q.= "FROM members_tracking a LEFT JOIN members_tracking b ON (b.id=${pid}) WHERE a.id=${nid}";
				$r = pg_query($pgconn_gps, $q);
				$f = pg_fetch_assoc($r);
				*/
				// Update! previous_id | distance |  duration
				$q = "UPDATE members_tracking SET previous_id=".$f["pid"].",distance=".((int)$f["distance"]).",duration=".((int)(1000*$f["duration"]));
				$q.= " WHERE id=${nid}";
				LogString("Query->", $q);
				$r = pg_query($pgconn_gps, $q);
			}
		}
		$message = pg_last_error($pgconn_gps);
	} else {
		$message = "Invalid input";
	}
	return array(
		"retval" => pg_affected_rows($r) ? PHP_API_OK : -1,
		"status" => pg_affected_rows($r),
		"error" => $message
	);
}

function decompress($str) {
	return gzinflate(base64_decode($str));
}

function compress($str) {
	return base64_encode(gzdeflate($str, 9));
}
