<?php

class Compare {
	
	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)
		];
	}

	public function compareYouVsAverage($you,$avg) {
		/*
			"category"=>$category,
			"member_id"=>$member_id,
			"days"=>$days,
			"count"=>0,
			"amount"=>0,
			"errors"=>[]
		*/
		if ($you["amount"]>0 || $avg["amount"]>0) {
			if ($you["amount"]==0) return 100;
			if ($avg["amount"]==0) return -100;
			if ($you["amount"]>$avg["amount"]) {
				return sprintf("%0.02f",-(100*(1-$avg["amount"]/$you["amount"])));
			}
			return sprintf("%0.02f",100*(1-$you["amount"]/$avg["amount"]));
		}
		return 0;
	}
}

// vi:ts=2

