<?php


namespace Fliegerlogin;


class RequestCounter {

	public const DAILY_LIMIT = 500;

	private const TRANSIENT_KEY = 'fliegerlogin_api_request_counter';

	public static function increment(): int {
		$today = self::today();
		$data = self::load();

		if (($data['date'] ?? null) !== $today) {
			$data = ['date' => $today, 'count' => 0];
		}

		$data['count']++;
		self::store($data);

		return (int) $data['count'];
	}

	public static function getCount(): int {
		$data = self::load();

		if (($data['date'] ?? null) !== self::today()) {
			return 0;
		}

		return (int) ($data['count'] ?? 0);
	}

	public static function getRemaining(): int {
		return max(0, self::DAILY_LIMIT - self::getCount());
	}

	public static function getDate(): string {
		return self::today();
	}

	private static function today(): string {
		if (function_exists('wp_date')) {
			return wp_date('Y-m-d');
		}

		return gmdate('Y-m-d');
	}

	private static function load(): array {
		if (!function_exists('get_transient')) {
			return [];
		}

		$data = get_transient(self::TRANSIENT_KEY);

		return is_array($data) ? $data : [];
	}

	private static function store(array $data): void {
		if (!function_exists('set_transient')) {
			return;
		}

		$ttl = defined('DAY_IN_SECONDS') ? DAY_IN_SECONDS : 86400;
		set_transient(self::TRANSIENT_KEY, $data, $ttl);
	}

}
