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

/**
 * R-LLM SEO License Guard
 */
add_action('admin_init', 'r_llm_seo_license_guard_admin_init', 1);
add_action('admin_notices', 'r_llm_seo_license_guard_admin_notice', 20);

function r_llm_seo_license_guard_admin_init(): void
{
	if (!is_admin()) {
		return;
	}

	$page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS);
	$page = is_string($page) ? sanitize_key(wp_unslash($page)) : '';
	if ($page === '' || strpos($page, 'r-llm-seo') === false) {
		return;
	}

	if (isset($_GET['refresh'])) {
		check_admin_referer('r_llm_seo_refresh_license');
		r_llm_seo_license_guard_clear_cache();
	}
}

function r_llm_seo_license_guard_plan_label(string $plan): string
{
	$p = strtolower(trim($plan));
	if ($p === 'light' || $p === 'lite') return esc_html__('ライトプラン', 'r-llm-seo');
	if ($p === 'basic' || $p === 'bsc') return esc_html__('ベーシックプラン', 'r-llm-seo');
	if ($p === 'standard' || $p === 'std') return esc_html__('スタンダードプラン', 'r-llm-seo');
	if ($p === 'pro' || $p === 'professional') return esc_html__('プロプラン', 'r-llm-seo');
	if ($p === 'trial' || $p === 'free_trial') return esc_html__('トライアルプラン', 'r-llm-seo');
	return ($plan !== '') ? $plan : esc_html__('不明', 'r-llm-seo');
}

function r_llm_seo_license_guard_status_label(string $status): string
{
	$s = strtolower(trim($status));
	if ($s === 'active') return esc_html__('有効', 'r-llm-seo');
	if ($s === 'free_trial') return esc_html__('トライアル中', 'r-llm-seo');
	if ($s === 'trial_expired') return esc_html__('トライアル終了', 'r-llm-seo');
	if ($s === 'canceled') return esc_html__('停止中', 'r-llm-seo');
	if ($s === 'suspended') return esc_html__('一時停止', 'r-llm-seo');
	if ($s === 'revoked') return esc_html__('失効', 'r-llm-seo');
	if ($s === 'inactive') return esc_html__('無効', 'r-llm-seo');
	return ($status !== '') ? $status : esc_html__('不明', 'r-llm-seo');
}

function r_llm_seo_license_guard_admin_notice(): void
{
	if (!is_admin()) {
		return;
	}

	$page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS);
	$page = is_string($page) ? sanitize_key(wp_unslash($page)) : '';
	if ($page === '' || strpos($page, 'r-llm-seo') === false) {
		return;
	}

	$st = r_llm_seo_license_guard_get_status();

	if (!empty($st['ok'])) {
		$plan_raw   = (string)($st['plan'] ?? '');
		$status_raw = (string)($st['status'] ?? 'active');

		$plan_label   = r_llm_seo_license_guard_plan_label($plan_raw);
		$status_label = r_llm_seo_license_guard_status_label($status_raw);

		$label = sprintf(
			/* translators: 1: license status label, 2: plan label */
			esc_html__('R-LLM ライセンス: %1$s（%2$s）', 'r-llm-seo'),
			$status_label,
			$plan_label
		);

		$refresh_url = wp_nonce_url(
			admin_url('admin.php?page=' . rawurlencode($page) . '&refresh=1'),
			'r_llm_seo_refresh_license'
		);

		echo '<div class="notice notice-success" style="padding:10px 12px;">';

		$quota = function_exists('r_llm_seo_quota_get_cache') ? r_llm_seo_quota_get_cache() : null;
		$quota_line = ($quota && function_exists('r_llm_seo_format_quota_message'))
			? r_llm_seo_format_quota_message($quota)
			: '';

		echo '<p style="margin:0;"><strong>' . esc_html($label) . '</strong> ';

		if ($quota_line !== '') {
			echo '<span id="r-llm-seo-quota-line" style="margin-left:10px;">' . esc_html($quota_line) . '</span>';
		}

		echo '<a href="' . esc_url($refresh_url) . '" style="margin-left:10px;">' . esc_html__('再チェック', 'r-llm-seo') . '</a>';
		echo '</p>';
		echo '</div>';
		return;
	}

	if ($page !== 'r-llm-seo-settings') {
		return;
	}

	echo wp_kses_post(r_llm_seo_license_guard_render_notice($st));
}

function r_llm_seo_license_guard_api_key_fingerprint(string $api_key): string
{
	$api_key = trim($api_key);
	if ($api_key === '') {
		return '';
	}

	return hash('sha256', $api_key);
}

function r_llm_seo_license_guard_get_status(): array
{
	$cache_key   = 'r_llm_seo_license_status_v1';
	$last_ok_key = 'r_llm_seo_license_status_last_ok_v1';

	try {
		$cfg = r_llm_seo_get_rllm_config();
		$api_key = trim((string)($cfg['api_key'] ?? ''));
	} catch (Throwable $e) {
		$api_key = '';
	}

	$current_fingerprint = r_llm_seo_license_guard_api_key_fingerprint($api_key);

	$cached = get_transient($cache_key);
	$cached_is_usable = (
		is_array($cached)
		&& !empty($cached['api_key_fingerprint'])
		&& $current_fingerprint !== ''
		&& hash_equals((string) $cached['api_key_fingerprint'], $current_fingerprint)
	);

	if ($cached_is_usable) {
		return $cached;
	}

	$last_ok = get_transient($last_ok_key);
	if (!is_array($last_ok)) {
		$last_ok = null;
	}

	$last_ok_is_usable = (
		is_array($last_ok)
		&& !empty($last_ok['ok'])
		&& !empty($last_ok['api_key_fingerprint'])
		&& $current_fingerprint !== ''
		&& hash_equals((string) $last_ok['api_key_fingerprint'], $current_fingerprint)
	);

	if ($api_key === '') {
		$data = [
			'ok'      => false,
			'status'  => 'inactive',
			'plan'    => 'none',
			'message' => esc_html__('APIキーが未設定です。', 'r-llm-seo'),
		];
		set_transient($cache_key, $data, 30);
		return $data;
	}

	try {
		$res    = r_llm_seo_gateway_post('core', 'status', []);
		$meta   = is_array($res['meta'] ?? null) ? $res['meta'] : [];
		$result = is_array($res['result'] ?? null) ? $res['result'] : [];

		$status = (string)($meta['status'] ?? ($result['status'] ?? 'inactive'));
		$plan   = (string)($meta['plan'] ?? ($result['plan'] ?? 'light'));

		$ok = in_array($status, ['active', 'free_trial'], true);

		$data = [
			'ok'                  => $ok,
			'status'              => $status,
			'plan'                => $plan,
			'message'             => $ok ? '' : esc_html__('ライセンスが無効です。', 'r-llm-seo'),
			'api_key_fingerprint' => $current_fingerprint,
		];

		if ($ok) {
			set_transient($last_ok_key, $data, 12 * HOUR_IN_SECONDS);
		}

		set_transient($cache_key, $data, 15 * MINUTE_IN_SECONDS);
		return $data;
	} catch (Throwable $e) {
		if ($e instanceof R_LLM_SEO_GatewayException && $e->code_name === 'DAILY_TOKEN_QUOTA_EXCEEDED') {
			if ($last_ok_is_usable) {
				$data = $last_ok;
				$data['message'] = $e->getMessage();
				set_transient($cache_key, $data, 2 * MINUTE_IN_SECONDS);
				return $data;
			}

			$data = [
				'ok'                  => true,
				'status'              => 'unknown',
				'plan'                => 'unknown',
				'message'             => $e->getMessage(),
				'api_key_fingerprint' => $current_fingerprint,
			];
			set_transient($cache_key, $data, 2 * MINUTE_IN_SECONDS);
			return $data;
		}

		if ($last_ok_is_usable) {
			$data = $last_ok;
			$data['message'] = esc_html__('ライセンス確認に失敗しました（前回OKの状態を継続表示）。', 'r-llm-seo');
			set_transient($cache_key, $data, 30);
			return $data;
		}

		$data = [
			'ok'                  => false,
			'status'              => 'inactive',
			'plan'                => 'none',
			'message'             => esc_html__('ライセンス確認に失敗しました。APIキー設定をご確認ください。', 'r-llm-seo'),
			'api_key_fingerprint' => $current_fingerprint,
		];
		set_transient($cache_key, $data, 30);
		return $data;
	}
}

function r_llm_seo_license_guard_clear_cache(): void
{
	delete_transient('r_llm_seo_license_status_v1');
	delete_transient('r_llm_seo_license_status_last_ok_v1');

	if (function_exists('r_llm_seo_quota_clear_cache')) {
		r_llm_seo_quota_clear_cache();
	}
}

function r_llm_seo_license_guard_render_notice(array $status): string
{
	$msg = (string)($status['message'] ?? '');
	if ($msg === '') {
		$msg = esc_html__('R-LLMの設定が必要です。', 'r-llm-seo');
	}

	$html  = '<div class="notice notice-error" style="padding:15px;">';
	$html .= '<p style="font-size:1.1em; margin:0 0 8px;"><strong>' . esc_html__('⚠️ R-LLM 設定が必要です', 'r-llm-seo') . '</strong></p>';
	$html .= '<p style="margin:0;">' . esc_html($msg) . '</p>';
	$html .= '</div>';

	return $html;
}