<?
//------------------------ Update Bonus Points -------------------------//

function bytesToGiB($bytes) {
	if ($bytes > 1048576) {
		$GiB = $bytes / 1073741824;
	} else {
		$GiB = 0;
	}
	return $GiB;
}

function calculateBP() {
	global $DB;
	global $Cache;

	$getUsers = $DB->query("SELECT DISTINCT(uid) AS uid FROM xbt_files_users");
	if ($DB->has_results()) {
		$users = array();
		while ($result = $DB->next_record()) {
			$users[] = $result['uid'];
		}
		foreach($users as $UserID) {
			$DB->query("
				SELECT t.Size,
						t.Seeders,
						(us.SeedTime/60/60/24) AS days
				FROM xbt_files_users AS x
				LEFT JOIN torrents AS t ON t.ID=x.fid
				LEFT JOIN users_seedtime AS us ON x.fid=us.TorrentID AND x.uid=us.UserID
				WHERE x.uid = $UserID AND x.active=1 AND x.remaining=0
				GROUP BY x.fid, x.ip");

			$totalBP = 0;
			while ($torrent = $DB->next_record()) {
				$points = bytesToGiB($torrent['Size']) * ( 0.25 + ( 0.6 * log(1+$torrent['days']) / pow($torrent['Seeders'],0.6) ) );
				$totalBP = $totalBP + $points;
			}

			if ($totalBP > 0) {
				$DB->query("SELECT BonusPoints, BPDems FROM users_main WHERE ID=$UserID");
				list($BonusPoints, $BPDems) = $DB->next_record();
				$OldBP = (float) $BonusPoints.'.'.$BPDems;
				$NewBP = $OldBP + $totalBP;
				$NewDems = $NewBP - floor($NewBP);
				$NewBP = $NewBP - $NewDems;
				$NewDems = (int) substr($NewDems, 2);

				$DB->query("
					UPDATE users_main
					SET BonusPoints = $NewBP, BPDems = $NewDems
					WHERE ID=$UserID");

			}

		    $Cache->delete_value('user_info_heavy_'.$UserID);
		}

	}
}

calculateBP();

?>
