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

/**
 * R-LLM SEO Option
 */
function r_llm_seo_normalize_site_url(string $url): string
{
	$url = trim($url);
	$url = esc_url_raw($url);
	return rtrim($url, '/');
}

function r_llm_seo_get_rllm_config(): array
{
	$base_url = rtrim(esc_url_raw((string)R_LLM_SEO_RLLM_BASE_URL_DEFAULT), '/');

	$wp_site_url = r_llm_seo_normalize_site_url((string)site_url());
	$saved_site_url = (string)get_option(R_LLM_SEO_OPT_SITE_URL, $wp_site_url);
	$saved_site_url = r_llm_seo_normalize_site_url($saved_site_url);

	$api_key = trim((string)get_option(R_LLM_SEO_OPT_API_KEY, ''));

	return [
		'base_url'       => $base_url,
		'wp_site_url'    => $wp_site_url,
		'saved_site_url' => $saved_site_url,
		'api_key'        => $api_key,
	];
}

function r_llm_seo_get_gateway_endpoint(): string
{
	$cfg = r_llm_seo_get_rllm_config();
	$base_url = rtrim((string)($cfg['base_url'] ?? ''), '/');
	return $base_url . R_LLM_SEO_RLLM_GATEWAY_PATH;
}

function r_llm_seo_assert_site_url_matches(): void
{
	$cfg = r_llm_seo_get_rllm_config();
	$wp  = (string)($cfg['wp_site_url'] ?? '');
	$sav = (string)($cfg['saved_site_url'] ?? '');

	if ($wp === '' || $sav === '' || $wp !== $sav) {
		throw new RuntimeException(
			esc_html__('site_url が一致しません。APIキーはこのWordPress（site_url）でのみ利用できます。設定画面を確認してください。', 'r-llm-seo')
		);
	}
}

function r_llm_seo_min_capability_option_key(): string
{
	return 'r_llm_seo_min_capability';
}

function r_llm_seo_min_capability_choices(): array
{
	return [
		'manage_options'     => esc_html__('管理者のみ（manage_options）', 'r-llm-seo'),
		'edit_others_posts'  => esc_html__('編集者以上（edit_others_posts）', 'r-llm-seo'),
		'edit_posts'         => esc_html__('投稿者以上（edit_posts）', 'r-llm-seo'),
	];
}

function r_llm_seo_get_min_capability(): string
{
	$default = 'manage_options';

	$cap = get_option(r_llm_seo_min_capability_option_key(), $default);
	$cap = is_string($cap) ? trim($cap) : $default;

	$choices = r_llm_seo_min_capability_choices();
	return isset($choices[$cap]) ? $cap : $default;
}

function r_llm_seo_user_can_use(): bool
{
	return current_user_can(r_llm_seo_get_min_capability());
}

function r_llm_seo_user_can_apply_to_post(int $post_id): bool
{
	if (!r_llm_seo_user_can_use()) return false;
	return current_user_can('edit_post', $post_id);
}