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

/**
 * R-LLM SEO F03 Ajax
 */

add_action('wp_ajax_r_llm_seo_run_ai_analysis_f03', 'r_llm_seo_f03_ajax_analyze');
add_action('wp_ajax_r_llm_seo_apply_ai_description', 'r_llm_seo_f03_ajax_apply');
add_action('wp_ajax_r_llm_seo_delete_ai_analysis_f03', 'r_llm_seo_f03_ajax_delete');
add_action('wp_ajax_r_llm_seo_bulk_delete_analysis_f03', 'r_llm_seo_f03_ajax_bulk_delete');

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

function r_llm_seo_f03_get_mode(): string
{
	$mode = filter_input(INPUT_POST, 'mode', FILTER_SANITIZE_SPECIAL_CHARS);
	$mode = is_string($mode) ? sanitize_key(wp_unslash($mode)) : 'keep';

	return in_array($mode, ['keep', 'pro'], true) ? $mode : 'keep';
}

function r_llm_seo_f03_get_new_desc(): string
{
	$new_desc = filter_input(INPUT_POST, 'new_desc', FILTER_SANITIZE_SPECIAL_CHARS);
	return is_string($new_desc) ? sanitize_textarea_field(wp_unslash($new_desc)) : '';
}

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

	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);
	}

	$post_id = r_llm_seo_f03_get_post_id();
	if ($post_id <= 0) {
		wp_send_json_error([
			'code'    => 'BAD_REQUEST',
			'message' => esc_html__('post_id が不正です', 'r-llm-seo'),
			'meta'    => null,
		], 400);
	}

	if (!current_user_can('edit_post', $post_id)) {
		wp_send_json_error([
			'code'    => 'FORBIDDEN',
			'message' => esc_html__('この投稿にアクセスできません', 'r-llm-seo'),
			'meta'    => null,
		], 403);
	}

	$post = get_post($post_id);
	if (!$post instanceof WP_Post) {
		wp_send_json_error([
			'code'    => 'NOT_FOUND',
			'message' => esc_html__('投稿が見つかりません', 'r-llm-seo'),
			'meta'    => null,
		], 404);
	}

	$mode = r_llm_seo_f03_get_mode();

	$current_desc = r_llm_seo_f03_get_current_description($post_id, $post);
	$content      = wp_strip_all_tags((string) $post->post_content);

	$ret = r_llm_seo_f03_analyze($current_desc, $content, $mode);

	if (!empty($ret['ok'])) {
		update_post_meta(
			$post_id,
			'_ai_desc_suggestions_full',
			(string) ($ret['full'] ?? '')
		);

		wp_send_json_success([
			'html' => r_llm_seo_f03_render_row_inner($post),
		]);
	}

	$msg  = (string) ($ret['message'] ?? $ret['error'] ?? esc_html__('API応答エラー', 'r-llm-seo'));
	$code = (string) ($ret['code'] ?? 'API_ERROR');
	$meta = (isset($ret['meta']) && is_array($ret['meta'])) ? $ret['meta'] : null;

	wp_send_json_error([
		'code'    => $code,
		'message' => $msg,
		'meta'    => $meta,
	], 502);
}

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

	$post_id  = r_llm_seo_f03_get_post_id();
	$new_desc = r_llm_seo_f03_get_new_desc();

	if ($post_id <= 0) {
		wp_send_json_error([
			'code'    => 'BAD_REQUEST',
			'message' => esc_html__('post_id が不正です', 'r-llm-seo'),
		], 400);
	}

	if ($new_desc === '') {
		wp_send_json_error([
			'code'    => 'BAD_REQUEST',
			'message' => esc_html__('ディスクリプションが空です', 'r-llm-seo'),
		], 400);
	}

	if (!function_exists('r_llm_seo_user_can_apply_to_post') || !r_llm_seo_user_can_apply_to_post($post_id)) {
		wp_send_json_error([
			'code'    => 'FORBIDDEN',
			'message' => esc_html__('反映する権限がありません', 'r-llm-seo'),
		], 403);
	}

	$target_field = r_llm_seo_f03_get_target_field();

	if ($target_field === 'post_excerpt') {
		$r = wp_update_post([
			'ID'           => $post_id,
			'post_excerpt' => $new_desc,
		], true);

		if (is_wp_error($r)) {
			wp_send_json_error([
				'code'    => 'UPDATE_FAILED',
				'message' => esc_html($r->get_error_message()),
			], 500);
		}
	} else {
		$updated = update_post_meta($post_id, $target_field, $new_desc);
		if ($updated === false) {
			wp_send_json_error([
				'code'    => 'UPDATE_FAILED',
				'message' => esc_html__('ディスクリプションの保存に失敗しました', 'r-llm-seo'),
			], 500);
		}
	}

	delete_post_meta($post_id, '_ai_desc_suggestions_full');

	$post = get_post($post_id);
	if (!$post instanceof WP_Post) {
		wp_send_json_error([
			'code'    => 'NOT_FOUND',
			'message' => esc_html__('投稿が見つかりません', 'r-llm-seo'),
		], 404);
	}

	wp_send_json_success([
		'html' => r_llm_seo_f03_render_row_inner($post),
	]);
}

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

	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'),
		], 403);
	}

	$post_id = r_llm_seo_f03_get_post_id();

	if ($post_id <= 0) {
		wp_send_json_error([
			'code'    => 'BAD_REQUEST',
			'message' => esc_html__('post_id が不正です', 'r-llm-seo'),
		], 400);
	}

	if (!current_user_can('edit_post', $post_id)) {
		wp_send_json_error([
			'code'    => 'FORBIDDEN',
			'message' => esc_html__('この投稿にアクセスできません', 'r-llm-seo'),
		], 403);
	}

	delete_post_meta($post_id, '_ai_desc_suggestions_full');

	$post = get_post($post_id);
	if (!$post instanceof WP_Post) {
		wp_send_json_error([
			'code'    => 'NOT_FOUND',
			'message' => esc_html__('投稿が見つかりません', 'r-llm-seo'),
		], 404);
	}

	wp_send_json_success([
		'html' => r_llm_seo_f03_render_row_inner($post),
	]);
}

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

	if (!current_user_can('manage_options')) {
		wp_send_json_error([
			'code'    => 'FORBIDDEN',
			'message' => esc_html__('この操作を実行する権限がありません。', 'r-llm-seo'),
		], 403);
	}

	$selected_post_types = get_option('r_llm_seo_post_types', ['post']);
	if (!is_array($selected_post_types)) {
		$selected_post_types = ['post'];
	}
	$selected_post_types = array_values(array_filter(array_map('sanitize_key', $selected_post_types)));

	if (empty($selected_post_types)) {
		wp_send_json_success([
			'deleted' => 0,
		]);
	}

	$q = new WP_Query([
		'post_type'              => $selected_post_types,
		'post_status'            => 'any',
		'posts_per_page'         => -1,
		'fields'                 => 'ids',
		'no_found_rows'          => true,
		'update_post_meta_cache' => false,
		'update_post_term_cache' => false,
	]);

	$deleted = 0;

	if (!empty($q->posts) && is_array($q->posts)) {
		foreach ($q->posts as $post_id) {
			$post_id = (int) $post_id;
			if ($post_id <= 0) {
				continue;
			}
			if (delete_post_meta($post_id, '_ai_desc_suggestions_full')) {
				$deleted++;
			}
		}
	}

	wp_send_json_success([
		'deleted' => $deleted,
	]);
}