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

/**
 * R-LLM SEO Settings Page
 */
add_action('admin_init', 'r_llm_seo_settings_handle_post', 0);

function r_llm_seo_settings_get_current_page(): string
{
	$page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS);
	return is_string($page) ? sanitize_key(wp_unslash($page)) : '';
}

function r_llm_seo_settings_get_updated_flag(): bool
{
	$key = 'r_llm_seo_settings_saved_' . get_current_user_id();
	if (get_transient($key)) {
		delete_transient($key);
		return true;
	}
	return false;
}

function r_llm_seo_settings_get_post_types_input(): array
{
	$post_types = filter_input(INPUT_POST, 'post_types', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_REQUIRE_ARRAY);

	if (!is_array($post_types)) {
		return [];
	}

	return array_map(
		static function ($value): string {
			return sanitize_key(wp_unslash((string)$value));
		},
		$post_types
	);
}

function r_llm_seo_settings_get_api_key_input(): string
{
	$api_key = filter_input(INPUT_POST, 'r_llm_api_key', FILTER_SANITIZE_SPECIAL_CHARS);
	return is_string($api_key) ? trim(sanitize_text_field(wp_unslash($api_key))) : '';
}

function r_llm_seo_settings_get_desc_target_input(): string
{
	$desc_target = filter_input(INPUT_POST, 'r_llm_seo_desc_target', FILTER_SANITIZE_SPECIAL_CHARS);
	return is_string($desc_target) ? sanitize_key(wp_unslash($desc_target)) : '';
}

function r_llm_seo_settings_get_desc_custom_key_input(): string
{
	$custom_key = filter_input(INPUT_POST, 'r_llm_seo_desc_custom_key', FILTER_SANITIZE_SPECIAL_CHARS);
	return is_string($custom_key) ? sanitize_key(wp_unslash($custom_key)) : '';
}

function r_llm_seo_settings_get_min_capability_input(): string
{
	$cap = filter_input(INPUT_POST, 'r_llm_seo_min_capability', FILTER_SANITIZE_SPECIAL_CHARS);
	return is_string($cap) ? sanitize_text_field(wp_unslash($cap)) : '';
}

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

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

	if (!isset($_POST['save_settings'])) {
		return;
	}

	if (!current_user_can('manage_options')) {
		wp_die(esc_html__('このページにアクセスする権限がありません。', 'r-llm-seo'));
	}

	check_admin_referer('llm_seo_settings_verify');

	$args      = ['public' => true, 'show_ui' => true];
	$all_types = get_post_types($args, 'names');
	if (!is_array($all_types)) {
		$all_types = [];
	}
	$all_types = array_values(array_filter(array_map('sanitize_key', $all_types)));

	$selected_types_raw = r_llm_seo_settings_get_post_types_input();
	$selected_types     = array_values(array_intersect($selected_types_raw, $all_types));

	if ($selected_types === []) {
		$selected_types = ['post'];
	}

	update_option('r_llm_seo_post_types', $selected_types);

	$desc_target = r_llm_seo_settings_get_desc_target_input();
	if ($desc_target !== '') {
		update_option('r_llm_seo_desc_target', $desc_target);
	}

	$custom_key = r_llm_seo_settings_get_desc_custom_key_input();
	if ($custom_key !== '') {
		update_option('r_llm_seo_desc_custom_key', $custom_key);
	}

	$wp_site_url = rtrim((string)site_url(), '/');
	update_option(R_LLM_SEO_OPT_SITE_URL, $wp_site_url);

	$new_api_key = r_llm_seo_settings_get_api_key_input();
	if ($new_api_key !== '') {
		update_option(R_LLM_SEO_OPT_API_KEY, $new_api_key);
	}

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

	$cap = r_llm_seo_settings_get_min_capability_input();
	if ($cap !== '') {
		$choices = function_exists('r_llm_seo_min_capability_choices') ? r_llm_seo_min_capability_choices() : [];
		if (!isset($choices[$cap])) {
			$cap = 'manage_options';
		}
		update_option(r_llm_seo_min_capability_option_key(), $cap);
	}

	set_transient('r_llm_seo_settings_saved_' . get_current_user_id(), 1, 60);
	$to = admin_url('admin.php?page=r-llm-seo-settings');
	wp_safe_redirect($to);
	exit;
}

function r_llm_seo_render_settings_page(): void
{
	$selected_post_types = get_option('r_llm_seo_post_types', ['post']);

	$desc_target     = get_option('r_llm_seo_desc_target', 'post_excerpt');
	$desc_custom_key = get_option('r_llm_seo_desc_custom_key', '');

	$min_cap     = function_exists('r_llm_seo_get_min_capability') ? r_llm_seo_get_min_capability() : 'manage_options';
	$cap_choices = function_exists('r_llm_seo_min_capability_choices') ? r_llm_seo_min_capability_choices() : [
		'manage_options' => esc_html__('管理者のみ（manage_options）', 'r-llm-seo'),
	];

	$site_url = (string)get_option(R_LLM_SEO_OPT_SITE_URL, rtrim((string)site_url(), '/'));
	$api_key  = (string)get_option(R_LLM_SEO_OPT_API_KEY, '');

	$api_key_masked = ($api_key !== '')
		? (substr($api_key, 0, 6) . str_repeat('*', max(0, strlen($api_key) - 10)) . substr($api_key, -4))
		: '';

	$args      = ['public' => true, 'show_ui' => true];
	$all_types = get_post_types($args, 'objects');
	if (!is_array($all_types)) {
		$all_types = [];
	}

	unset(
		$all_types['attachment'],
		$all_types['nav_menu_item'],
		$all_types['revision'],
		$all_types['custom_css'],
		$all_types['customize_changeset'],
		$all_types['oembed_cache'],
		$all_types['user_request'],
		$all_types['wp_block'],
		$all_types['wp_template'],
		$all_types['wp_template_part'],
		$all_types['wp_navigation']
	);

	$updated_flag = r_llm_seo_settings_get_updated_flag();
	?>

	<div class="wrap" id="r-llm-seo-settings">

		<?php if ($updated_flag): ?>
			<div class="updated notice is-dismissible"><p><?php echo esc_html__('設定を保存しました。', 'r-llm-seo'); ?></p></div>
		<?php endif; ?>

		<div class="rllm-pagehead">
			<div>
				<p class="rllm-lead"><?php echo esc_html__('AI機能の対象・保存先・接続情報をまとめて管理します。', 'r-llm-seo'); ?></p>
			</div>
		</div>

		<form method="post" action="">
			<?php wp_nonce_field('llm_seo_settings_verify'); ?>

			<div class="rllm-stack">

				<section class="rllm-card">
					<header class="rllm-cardhead">
						<h2 class="rllm-h2"><?php echo esc_html__('機能設定', 'r-llm-seo'); ?></h2>
					</header>

					<div class="rllm-body">

						<div class="rllm-field">
							<label class="rllm-label" for="r_llm_seo_min_capability"><?php echo esc_html__('利用ユーザー', 'r-llm-seo'); ?></label>
							<div class="rllm-control">
								<select id="r_llm_seo_min_capability" name="r_llm_seo_min_capability" class="rllm-select">
									<?php foreach ($cap_choices as $cap => $label): ?>
										<option value="<?php echo esc_attr($cap); ?>" <?php selected($min_cap, $cap); ?>>
											<?php echo esc_html($label); ?>
										</option>
									<?php endforeach; ?>
								</select>
								<p class="rllm-help"><?php echo esc_html__('この権限以上のユーザーのみ、生成・分析・反映機能を利用できます。', 'r-llm-seo'); ?></p>
							</div>
						</div>

						<div class="rllm-field">
							<div class="rllm-label"><?php echo esc_html__('投稿タイプ', 'r-llm-seo'); ?></div>
							<div class="rllm-control">
								<div class="rllm-checkgrid">
									<?php foreach ($all_types as $type): ?>
										<label class="rllm-check">
											<input type="checkbox" name="post_types[]"
												value="<?php echo esc_attr($type->name); ?>"
												<?php checked(in_array($type->name, (array)$selected_post_types, true)); ?>>
											<span class="rllm-checktext">
												<span class="rllm-checklabel"><?php echo esc_html($type->label); ?></span>
												<code class="rllm-code"><?php echo esc_html($type->name); ?></code>
											</span>
										</label>
									<?php endforeach; ?>
								</div>
								<p class="rllm-help"><?php echo esc_html__('チェックした投稿タイプのみAI機能の対象になります。', 'r-llm-seo'); ?></p>
							</div>
						</div>

						<div class="rllm-field">
							<label class="rllm-label" for="r_llm_seo_desc_target"><?php echo esc_html__('保存先（ディスクリプション）', 'r-llm-seo'); ?></label>
							<div class="rllm-control">
								<select name="r_llm_seo_desc_target" id="r_llm_seo_desc_target" class="rllm-select">
									<option value="post_excerpt" <?php selected($desc_target, 'post_excerpt'); ?>><?php echo esc_html__('WordPress標準（抜粋）', 'r-llm-seo'); ?></option>
									<option value="_yoast_wpseo_metadesc" <?php selected($desc_target, '_yoast_wpseo_metadesc'); ?>><?php echo esc_html__('Yoast SEO', 'r-llm-seo'); ?></option>
									<option value="_aioseo_description" <?php selected($desc_target, '_aioseo_description'); ?>><?php echo esc_html__('All in One SEO', 'r-llm-seo'); ?></option>
									<option value="_rank_math_description" <?php selected($desc_target, '_rank_math_description'); ?>><?php echo esc_html__('Rank Math', 'r-llm-seo'); ?></option>
									<option value="custom" <?php selected($desc_target, 'custom'); ?>><?php echo esc_html__('カスタム（メタキー直接指定）', 'r-llm-seo'); ?></option>
								</select>

								<div id="desc-custom-key-wrap" class="<?php echo ($desc_target === 'custom') ? '' : 'is-hidden'; ?>">
									<input type="text" name="r_llm_seo_desc_custom_key"
										value="<?php echo esc_attr($desc_custom_key); ?>"
										class="rllm-input"
										placeholder="<?php echo esc_attr__('例: _my_seo_description', 'r-llm-seo'); ?>">
									<p class="rllm-help"><?php echo esc_html__('AIが生成したディスクリプションを書き込むメタキーを指定します。', 'r-llm-seo'); ?></p>
								</div>

								<?php if ($desc_target !== 'custom'): ?>
									<p class="rllm-help"><?php echo esc_html__('AIが生成したディスクリプションを書き込む場所を選択します。', 'r-llm-seo'); ?></p>
								<?php endif; ?>
							</div>
						</div>

					</div>
				</section>

				<section class="rllm-card">
					<header class="rllm-cardhead">
						<h2 class="rllm-h2"><?php echo esc_html__('接続設定', 'r-llm-seo'); ?></h2>
					</header>

					<div class="rllm-body">

						<div class="rllm-field">
							<label class="rllm-label"><?php echo esc_html__('サイトURL（固定）', 'r-llm-seo'); ?></label>
							<div class="rllm-control">
								<input type="text" readonly value="<?php echo esc_attr($site_url); ?>" class="rllm-input is-readonly">
								<input type="hidden" name="r_llm_site_url" value="<?php echo esc_attr($site_url); ?>">
								<p class="rllm-help"><?php echo wp_kses_post(__('マイページでAPIキー発行時に、このURLを「<strong>WordPressのサイトURL（site_url）</strong>」として登録してください。', 'r-llm-seo')); ?></p>
							</div>
						</div>

						<div class="rllm-field">
							<label class="rllm-label"><?php echo esc_html__('APIキー', 'r-llm-seo'); ?></label>
							<div class="rllm-control">
								<input type="password" name="r_llm_api_key" value="" class="rllm-input"
									placeholder="<?php echo esc_attr($api_key_masked ?: esc_html__('（未設定）', 'r-llm-seo')); ?>">
								<p class="rllm-help"><?php echo esc_html__('空で保存すると既存キーは維持します。', 'r-llm-seo'); ?></p>
							</div>
						</div>

					</div>
				</section>

				<div class="rllm-actions">
					<button type="submit" name="save_settings" class="rllm-btn rllm-btn-primary"><?php echo esc_html__('設定を保存', 'r-llm-seo'); ?></button>
				</div>

			</div>
		</form>

	</div>
	<?php
}