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

/**
 * R-LLM SEO F02 Ajax
 */
function r_llm_seo_f02_ajax_require_cap(): void
{
	$uid = function_exists('get_current_user_id') ? (int)get_current_user_id() : 0;
	if ($uid <= 0) {
		wp_send_json_error(
			[
				'code'    => 'UNAUTHORIZED',
				'message' => esc_html__('ログインが必要です。', 'r-llm-seo'),
				'meta'    => null,
			],
			401
		);
	}

	if (!function_exists('r_llm_seo_user_can_use') || !r_llm_seo_user_can_use()) {
		wp_send_json_error(
			[
				'code'    => 'FORBIDDEN',
				'message' => esc_html__('権限がありません。', 'r-llm-seo'),
				'meta'    => null,
			],
			403
		);
	}
}

function r_llm_seo_f02_ajax_sanitize_post_type(string $post_type): string
{
	$post_type = sanitize_key($post_type ?: 'post');
	if ($post_type === '' || !post_type_exists($post_type)) {
		$post_type = 'post';
	}

	return $post_type;
}

function r_llm_seo_f02_ajax_get_post_id(): string
{
	$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
	return is_string($id) ? sanitize_text_field(wp_unslash($id)) : '';
}

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

function r_llm_seo_f02_ajax_get_post_type(): string
{
	$post_type = filter_input(INPUT_POST, 'post_type', FILTER_SANITIZE_SPECIAL_CHARS);
	$post_type = is_string($post_type) ? wp_unslash($post_type) : 'post';

	return r_llm_seo_f02_ajax_sanitize_post_type($post_type);
}

function r_llm_seo_f02_ajax_get_keywords(): array
{
	$raw_keywords = filter_input(INPUT_POST, 'keywords', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_REQUIRE_ARRAY);

	if (!is_array($raw_keywords)) {
		$single = filter_input(INPUT_POST, 'keywords', FILTER_SANITIZE_SPECIAL_CHARS);
		$raw_keywords = is_string($single) ? [$single] : [];
	}

	$keywords = array_map(
		static function ($keyword): string {
			return sanitize_text_field(wp_unslash((string)$keyword));
		},
		$raw_keywords
	);

	return array_values(
		array_filter(
			$keywords,
			static function (string $keyword): bool {
				return $keyword !== '';
			}
		)
	);
}

function r_llm_seo_f02_ajax_get_max_length(): int
{
	$max_length = filter_input(INPUT_POST, 'max_length', FILTER_VALIDATE_INT);
	return is_int($max_length) && $max_length > 0 ? $max_length : 32;
}

function r_llm_seo_f02_ajax_get_is_fav(): bool
{
	$is_fav = filter_input(INPUT_POST, 'is_fav', FILTER_SANITIZE_SPECIAL_CHARS);
	$is_fav = is_string($is_fav) ? strtolower(wp_unslash($is_fav)) : '';

	return in_array($is_fav, ['1', 'true', 'yes', 'on'], true);
}

function r_llm_seo_f02_ajax_build_rows_html(array $items, string $post_type = 'post'): string
{
	$html = '';

	foreach ($items as $it) {
		if (!is_array($it)) {
			continue;
		}

		$row = (string)r_llm_seo_f02_render_row($it, $post_type);
		$html .= $row;
	}

	return $html;
}

function r_llm_seo_f02_store_update_one(string $id, array $patch): ?array
{
	if (!function_exists('r_llm_seo_f02_store_get') || !function_exists('r_llm_seo_f02_store_set')) {
		return null;
	}

	$items = r_llm_seo_f02_store_get();
	$found = null;

	foreach ($items as &$it) {
		if (!is_array($it)) {
			continue;
		}
		if ((string)($it['id'] ?? '') !== $id) {
			continue;
		}

		$it = array_merge($it, $patch);

		if (function_exists('r_llm_seo_f02_normalize_item')) {
			$it = r_llm_seo_f02_normalize_item($it);
		}

		$found = $it;
		break;
	}
	unset($it);

	if ($found !== null) {
		r_llm_seo_f02_store_set($items);
	}

	return $found;
}

function r_llm_seo_f02_ajax_generate(): void
{
	r_llm_seo_f02_ajax_require_cap();
	check_ajax_referer('llm_seo_nonce', 'nonce');

	if (!function_exists('r_llm_seo_f02_generate')) {
		wp_send_json_error(['code' => 'MISSING_SERVICE', 'message' => esc_html__('F02 Service が読み込まれていません。', 'r-llm-seo')], 500);
	}
	if (!function_exists('r_llm_seo_f02_render_row')) {
		wp_send_json_error(['code' => 'MISSING_VIEW', 'message' => esc_html__('F02 View が読み込まれていません。', 'r-llm-seo')], 500);
	}
	if (!function_exists('r_llm_seo_f02_store_get')) {
		wp_send_json_error(['code' => 'MISSING_SERVICE', 'message' => esc_html__('F02 Store が読み込まれていません。', 'r-llm-seo')], 500);
	}

	$keywords  = r_llm_seo_f02_ajax_get_keywords();
	$max_len   = r_llm_seo_f02_ajax_get_max_length();
	$post_type = r_llm_seo_f02_ajax_get_post_type();

	try {
		$rv = r_llm_seo_f02_generate($keywords, $max_len);

		if (!is_array($rv) || empty($rv['ok'])) {
			$err_code = is_array($rv) ? (string)($rv['code'] ?? 'LLM_ERROR') : 'LLM_ERROR';
			$err_msg  = is_array($rv) ? (string)($rv['error'] ?? esc_html__('生成に失敗しました。', 'r-llm-seo')) : esc_html__('生成に失敗しました。', 'r-llm-seo');
			wp_send_json_error(
				[
					'code'    => $err_code,
					'message' => $err_msg,
					'meta'    => null,
				],
				200
			);
		}

		$items = r_llm_seo_f02_store_get();
		$items = is_array($items) ? array_values($items) : [];

		$rows_html = r_llm_seo_f02_ajax_build_rows_html($items, $post_type);

		wp_send_json_success(
			[
				'items'     => $items,
				'rows_html' => $rows_html,
				'meta'      => null,
			],
			200
		);
	} catch (Throwable $e) {
		wp_send_json_error(
			[
				'code'    => 'INTERNAL_ERROR',
				'message' => $e->getMessage(),
				'meta'    => null,
			],
			200
		);
	}
}
add_action('wp_ajax_r_llm_seo_run_ai_title_generate_f02', 'r_llm_seo_f02_ajax_generate');

function r_llm_seo_f02_ajax_list_items(): void
{
	r_llm_seo_f02_ajax_require_cap();
	check_ajax_referer('llm_seo_nonce', 'nonce');

	if (!function_exists('r_llm_seo_f02_store_get')) {
		wp_send_json_error(
			[
				'code'    => 'MISSING_SERVICE',
				'message' => esc_html__('F02 Service が読み込まれていません。', 'r-llm-seo'),
				'meta'    => null,
			],
			500
		);
	}
	if (!function_exists('r_llm_seo_f02_render_row')) {
		wp_send_json_error(
			[
				'code'    => 'MISSING_VIEW',
				'message' => esc_html__('F02 View が読み込まれていません。', 'r-llm-seo'),
				'meta'    => null,
			],
			500
		);
	}

	$post_type = r_llm_seo_f02_ajax_get_post_type();

	try {
		$items = r_llm_seo_f02_store_get();
		$items = is_array($items) ? array_values($items) : [];

		$rows_html = r_llm_seo_f02_ajax_build_rows_html($items, $post_type);

		wp_send_json_success(
			[
				'items'     => $items,
				'rows_html' => $rows_html,
				'meta'      => null,
			],
			200
		);
	} catch (Throwable $e) {
		wp_send_json_error(
			[
				'code'    => 'STORE_ERROR',
				'message' => esc_html__('保存データの取得に失敗しました。', 'r-llm-seo'),
				'meta'    => null,
			],
			200
		);
	}
}
add_action('wp_ajax_r_llm_seo_f02_list_items', 'r_llm_seo_f02_ajax_list_items');

function r_llm_seo_f02_ajax_toggle_fav(): void
{
	r_llm_seo_f02_ajax_require_cap();
	check_ajax_referer('llm_seo_nonce', 'nonce');

	if (!function_exists('r_llm_seo_f02_store_toggle_fav')) {
		wp_send_json_error(
			[
				'code'    => 'MISSING_SERVICE',
				'message' => esc_html__('F02 Service が読み込まれていません。', 'r-llm-seo'),
				'meta'    => null,
			],
			500
		);
	}

	$id   = r_llm_seo_f02_ajax_get_post_id();
	$next = r_llm_seo_f02_ajax_get_is_fav();

	if ($id === '') {
		wp_send_json_error(
			[
				'code'    => 'BAD_REQUEST',
				'message' => esc_html__('IDが不正です。', 'r-llm-seo'),
				'meta'    => null,
			],
			200
		);
	}

	try {
		$item = r_llm_seo_f02_store_toggle_fav($id, $next);

		if (!$item) {
			wp_send_json_error(
				[
					'code'    => 'NOT_FOUND',
					'message' => esc_html__('対象データが見つかりません。', 'r-llm-seo'),
					'meta'    => null,
				],
				200
			);
		}

		wp_send_json_success(
			[
				'item' => $item,
				'meta' => null,
			],
			200
		);
	} catch (Throwable $e) {
		wp_send_json_error(
			[
				'code'    => 'STORE_ERROR',
				'message' => esc_html__('更新に失敗しました。', 'r-llm-seo'),
				'meta'    => null,
			],
			200
		);
	}
}
add_action('wp_ajax_r_llm_seo_f02_toggle_fav', 'r_llm_seo_f02_ajax_toggle_fav');

function r_llm_seo_f02_ajax_delete_item(): void
{
	r_llm_seo_f02_ajax_require_cap();
	check_ajax_referer('llm_seo_nonce', 'nonce');

	if (!function_exists('r_llm_seo_f02_store_delete')) {
		wp_send_json_error(
			[
				'code'    => 'MISSING_SERVICE',
				'message' => esc_html__('F02 Service が読み込まれていません。', 'r-llm-seo'),
				'meta'    => null,
			],
			500
		);
	}

	$id = r_llm_seo_f02_ajax_get_post_id();
	if ($id === '') {
		wp_send_json_error(
			[
				'code'    => 'BAD_REQUEST',
				'message' => esc_html__('IDが不正です。', 'r-llm-seo'),
				'meta'    => null,
			],
			200
		);
	}

	try {
		$ok = r_llm_seo_f02_store_delete($id);

		wp_send_json_success(
			[
				'ok'   => (bool)$ok,
				'meta' => null,
			],
			200
		);
	} catch (Throwable $e) {
		wp_send_json_error(
			[
				'code'    => 'STORE_ERROR',
				'message' => esc_html__('削除に失敗しました。', 'r-llm-seo'),
				'meta'    => null,
			],
			200
		);
	}
}
add_action('wp_ajax_r_llm_seo_f02_delete_item', 'r_llm_seo_f02_ajax_delete_item');

function r_llm_seo_f02_ajax_delete_all(): void
{
	r_llm_seo_f02_ajax_require_cap();
	check_ajax_referer('llm_seo_nonce', 'nonce');

	if (!function_exists('r_llm_seo_f02_store_set')) {
		wp_send_json_error(
			[
				'code'    => 'MISSING_SERVICE',
				'message' => esc_html__('F02 Service が読み込まれていません。', 'r-llm-seo'),
				'meta'    => null,
			],
			500
		);
	}

	try {
		r_llm_seo_f02_store_set([]);

		wp_send_json_success(
			[
				'ok'   => true,
				'meta' => null,
			],
			200
		);
	} catch (Throwable $e) {
		wp_send_json_error(
			[
				'code'    => 'STORE_ERROR',
				'message' => esc_html__('一括削除に失敗しました。', 'r-llm-seo'),
				'meta'    => null,
			],
			200
		);
	}
}
add_action('wp_ajax_r_llm_seo_f02_delete_all', 'r_llm_seo_f02_ajax_delete_all');

function r_llm_seo_f02_ajax_create_draft(): void
{
	r_llm_seo_f02_ajax_require_cap();
	check_ajax_referer('llm_seo_nonce', 'nonce');

	if (!function_exists('r_llm_seo_f02_create_draft')) {
		wp_send_json_error(
			[
				'code'    => 'MISSING_SERVICE',
				'message' => esc_html__('F02 Service が読み込まれていません。', 'r-llm-seo'),
				'meta'    => null,
			],
			500
		);
	}

	$id        = r_llm_seo_f02_ajax_get_post_id();
	$title     = r_llm_seo_f02_ajax_get_post_title();
	$post_type = r_llm_seo_f02_ajax_get_post_type();

	if ($id === '') {
		wp_send_json_error(
			[
				'code'    => 'BAD_REQUEST',
				'message' => esc_html__('IDが不正です。', 'r-llm-seo'),
				'meta'    => null,
			],
			200
		);
	}

	try {
		$res = r_llm_seo_f02_create_draft($title, $post_type);

		$post_id  = (int)($res['post_id'] ?? 0);
		$edit_url = (string)($res['edit_url'] ?? '');

		$updated = r_llm_seo_f02_store_update_one(
			$id,
			[
				'is_created' => true,
				'post_id'    => $post_id,
			]
		);

		$payload = [
			'post_id'  => $post_id,
			'edit_url' => $edit_url,
			'meta'     => null,
		];

		if ($updated !== null) {
			$payload['item'] = $updated;
		}

		wp_send_json_success($payload, 200);
	} catch (Throwable $e) {
		wp_send_json_error(
			[
				'code'    => 'DRAFT_CREATE_FAILED',
				'message' => esc_html__('下書きの作成に失敗しました。', 'r-llm-seo'),
				'meta'    => null,
			],
			200
		);
	}
}
add_action('wp_ajax_r_llm_seo_create_ai_draft_f02', 'r_llm_seo_f02_ajax_create_draft');