<?php
defined('ABSPATH') || exit;

/**
 * R-LLM SEO Quota
 */
function r_llm_seo_quota_cache_key(): string
{
	$bid = function_exists('get_current_blog_id') ? (int)get_current_blog_id() : 0;
	return 'rllm_seo_quota_v1_' . $bid;
}

function r_llm_seo_quota_set_cache(array $quota): void
{
	set_transient(r_llm_seo_quota_cache_key(), $quota, 30 * MINUTE_IN_SECONDS);
}

function r_llm_seo_quota_get_cache(): ?array
{
	$v = get_transient(r_llm_seo_quota_cache_key());
	return is_array($v) ? $v : null;
}

function r_llm_seo_quota_clear_cache(): void
{
	delete_transient(r_llm_seo_quota_cache_key());
}

function r_llm_seo_format_quota_message(?array $quota): string
{
	if (!is_array($quota)) return '';

	$limit = isset($quota['limit_tokens']) ? (int)$quota['limit_tokens'] : 0;
	$used  = isset($quota['used_tokens']) ? (int)$quota['used_tokens'] : 0;
	$rem   = isset($quota['remaining_tokens']) ? max(0, (int)$quota['remaining_tokens']) : max(0, $limit - $used);

	if ($limit <= 0) return '';

	$resets_at = (isset($quota['resets_at']) && is_string($quota['resets_at'])) ? $quota['resets_at'] : '';
	$reset_txt = '';

	if ($resets_at !== '') {
		$dt = date_create($resets_at);
		if ($dt) {
			$reset_txt = sprintf(
				/* translators: %s: reset time */
				esc_html__('%sリセット', 'r-llm-seo'),
				$dt->format('G:i')
			);
		}
	}

	$msg = sprintf(
		/* translators: 1: used tokens, 2: token limit, 3: remaining tokens */
		esc_html__('本日トークン: %1$s / %2$s（残: %3$s）', 'r-llm-seo'),
		number_format($used),
		number_format($limit),
		number_format($rem)
	);

	if ($reset_txt !== '') $msg .= $reset_txt;

	return $msg;
}