<?php
/**
 * Blog - 博客功能模块
 *
 * 功能说明：
 * 1. 注册博客归档 REST API 端点（用于 Ajax 加载）
 * 2. 处理文章列表、搜索、标签过滤和分页的 Ajax 请求
 * 3. 提供分类颜色映射辅助函数
 * 4. 处理评论 Ajax 提交
 * 5. 按需加载博客相关样式和脚本
 *
 * 如需禁用此功能，请在 puffergo.php 中注释掉相关 require_once 语句
 *
 * @package PufferGo
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// ─── REST API ──────────────────────────────────────────────────

/**
 * 博客归档 REST API。
 */
class PufferGo_Blog_Archive {

	/**
	 * 构造函数。
	 */
	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_api' ) );
	}

	/**
	 * 注册 REST API 端点。
	 */
	public function register_api() {
		register_rest_route( 'puffergo/v1', '/blog-archive', array(
			'methods'             => 'GET',
			'callback'            => array( $this, 'api_callback' ),
			'permission_callback' => '__return_true',
			'args'                => array(
				'search' => array(
					'default'           => '',
					'sanitize_callback' => 'sanitize_text_field',
				),
				'category' => array(
					'default'           => '',
					'sanitize_callback' => 'sanitize_text_field',
				),
				'paged' => array(
					'default'           => 1,
					'sanitize_callback' => 'absint',
				),
				'postsPerPage' => array(
					'default'           => 9,
					'sanitize_callback' => 'absint',
				),
				'defaultThumbnailUrl' => array(
					'default'           => '',
					'sanitize_callback' => 'esc_url_raw',
				),
				'defaultThumbnailAlt' => array(
					'default'           => '',
					'sanitize_callback' => 'sanitize_text_field',
				),
			),
		) );
	}

	/**
	 * API 回调函数。
	 *
	 * @param WP_REST_Request $request 请求对象。
	 * @return WP_REST_Response
	 */
	public function api_callback( $request ) {
		$search_query          = $request->get_param( 'search' );
		$category_slug         = $request->get_param( 'category' );
		$paged                 = $request->get_param( 'paged' );
		$posts_per_page        = $request->get_param( 'postsPerPage' );
		$default_thumbnail_url = $request->get_param( 'defaultThumbnailUrl' );
		$default_thumbnail_alt = $request->get_param( 'defaultThumbnailAlt' );

		$query_args = array(
			'post_type'      => 'post',
			'post_status'    => 'publish',
			'posts_per_page' => $posts_per_page,
			'paged'          => $paged,
		);

		if ( ! empty( $search_query ) ) {
			$query_args['s'] = $search_query;
		}
		if ( ! empty( $category_slug ) ) {
			$query_args['category_name'] = $category_slug;
		}

		$query = new WP_Query( $query_args );

		$current_url = home_url( add_query_arg( null, null ) );
		$current_url = remove_query_arg( array( 's', 'category', 'paged' ), $current_url );

		// 构建文章列表 HTML — 复用 Data 类的 build_post_card 方法
		$data_class_file = PUFFERGO_PLUGIN_DIR . '/templates/data/class-puffergo-blog-archive-data.php';
		if ( file_exists( $data_class_file ) ) {
			require_once $data_class_file;
		}

		ob_start();
		if ( $query->have_posts() ) {
			echo '<div class="articles-grid">';
			while ( $query->have_posts() ) : $query->the_post();
				$post_data = PufferGo_Blog_Archive_Data::build_post_card(
					get_the_ID(),
					$default_thumbnail_url,
					$default_thumbnail_alt ?: get_the_title()
				);
				puffergo_render_component( 'blog-article-card', array( 'post_data' => $post_data ) );
			endwhile;
			echo '</div>';
		} else {
			echo '<div class="no-posts"><p>' . esc_html__( 'No posts found', 'puffergo' ) . '</p></div>';
		}
		$articles_html = ob_get_clean();

		// 分页 HTML — 复用 blog-pagination 组件
		$pagination_base = $current_url;
		if ( ! empty( $search_query ) ) {
			$pagination_base = add_query_arg( 's', $search_query, $pagination_base );
		}
		if ( ! empty( $category_slug ) ) {
			$pagination_base = add_query_arg( 'category', $category_slug, $pagination_base );
		}

		ob_start();
		puffergo_render_component( 'blog-pagination', array(
			'current_page' => $paged,
			'max_pages'    => $query->max_num_pages,
			'current_url'  => $pagination_base,
		) );
		$pagination_html = ob_get_clean();

		wp_reset_postdata();

		return new WP_REST_Response( array(
			'success' => true,
			'data'    => array(
				'articles'    => $articles_html,
				'pagination'  => $pagination_html,
				'maxPages'    => $query->max_num_pages,
				'currentPage' => $paged,
				'totalPosts'  => $query->found_posts,
			),
		), 200 );
	}
}

new PufferGo_Blog_Archive();

// ─── 分类颜色映射 ──────────────────────────────────────────────

/**
 * 获取博客分类颜色样式。
 *
 * @param string $category_slug 分类 slug。
 * @return array 包含 color 和 bgColor 的数组。
 */
function puffergo_get_category_color_style( $category_slug ) {
	$category_colors = array(
		'ecommerce'    => array( 'color' => '#4F46E5', 'bgColor' => '#E5E4FF' ),
		'architecture' => array( 'color' => '#306BE3', 'bgColor' => '#DBE9FF' ),
		'ux'           => array( 'color' => '#12AB0A', 'bgColor' => '#E5FFE4' ),
		'performance'  => array( 'color' => '#E54649', 'bgColor' => '#FFE4E4' ),
	);

	/**
	 * Filters the category color style mapping.
	 *
	 * @param array $category_colors Slug → ['color' => '', 'bgColor' => ''] mapping.
	 */
	$category_colors = apply_filters( 'puffergo_category_colors', $category_colors );

	return isset( $category_colors[ $category_slug ] )
		? $category_colors[ $category_slug ]
		: array( 'color' => '#666', 'bgColor' => '#f0f0f1' );
}

// ─── 评论 Ajax 处理器 ─────────────────────────────────────────

/**
 * 处理 Ajax 评论提交。
 */
function puffergo_handle_ajax_comment() {
	$comment_post_ID = isset( $_POST['comment_post_ID'] ) ? absint( $_POST['comment_post_ID'] ) : 0;
	$comment_parent  = isset( $_POST['comment_parent'] ) ? absint( $_POST['comment_parent'] ) : 0;
	$author          = isset( $_POST['author'] ) ? trim( sanitize_text_field( $_POST['author'] ) ) : '';
	$email           = isset( $_POST['email'] ) ? trim( sanitize_email( $_POST['email'] ) ) : '';
	$comment         = isset( $_POST['comment'] ) ? trim( wp_kses_post( $_POST['comment'] ) ) : '';

	if ( empty( $author ) ) {
		wp_send_json_error( __( 'Please enter your name', 'puffergo' ) );
	}
	if ( empty( $email ) || ! is_email( $email ) ) {
		wp_send_json_error( __( 'Please enter a valid email address', 'puffergo' ) );
	}
	if ( empty( $comment ) ) {
		wp_send_json_error( __( 'Please enter your comment', 'puffergo' ) );
	}
	if ( mb_strlen( $comment ) < 5 ) {
		wp_send_json_error( __( 'Comment must be at least 5 characters', 'puffergo' ) );
	}
	if ( ! $comment_post_ID ) {
		wp_send_json_error( __( 'Invalid post ID', 'puffergo' ) );
	}
	if ( ! comments_open( $comment_post_ID ) ) {
		wp_send_json_error( __( 'Comments are closed for this post', 'puffergo' ) );
	}

	// Nonce 验证
	if ( ! isset( $_POST['_wp_nonce'] ) || ! wp_verify_nonce( $_POST['_wp_nonce'], 'puffergo_comment_nonce_' . $comment_post_ID ) ) {
		wp_send_json_error( __( 'Security check failed, please refresh and retry', 'puffergo' ) );
	}

	$commentdata = array(
		'comment_post_ID'      => $comment_post_ID,
		'comment_parent'       => $comment_parent,
		'comment_author'       => $author,
		'comment_author_email' => $email,
		'comment_content'      => $comment,
		'comment_type'         => 'comment',
		'comment_author_IP'    => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( $_SERVER['REMOTE_ADDR'] ) : '',
		'comment_agent'        => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] ) : '',
		'comment_date'         => current_time( 'mysql' ),
		'comment_date_gmt'     => current_time( 'mysql', 1 ),
	);

	if ( is_user_logged_in() ) {
		$user = wp_get_current_user();
		$commentdata['user_id']              = $user->ID;
		$commentdata['comment_author']       = $user->display_name;
		$commentdata['comment_author_email'] = $user->user_email;
	}

	$comment_id = wp_new_comment( $commentdata, true );

	if ( is_wp_error( $comment_id ) ) {
		wp_send_json_error( $comment_id->get_error_message() );
	}

	$comment_obj  = get_comment( $comment_id );
	$is_moderated = ( '0' === $comment_obj->comment_approved );

	$comment_html = '';
	if ( ! $is_moderated ) {
		ob_start();
		?>
		<li id="comment-<?php echo esc_attr( $comment_id ); ?>" class="comment-item">
			<div class="comment-body">
				<div class="comment-author-avatar"><?php echo get_avatar( $comment_obj, 48 ); ?></div>
				<div class="comment-content-wrap">
					<div class="comment-meta">
						<span class="comment-author-name"><?php echo get_comment_author_link( $comment_obj ); ?></span>
						<span class="comment-date"><?php echo get_comment_date( get_option( 'date_format' ) . ' H:i', $comment_obj ); ?></span>
					</div>
					<div class="comment-text"><?php comment_text( $comment_obj ); ?></div>
					<div class="comment-reply">
						<a href="#" class="comment-reply-link" data-comment-id="<?php echo esc_attr( $comment_id ); ?>"><?php esc_html_e( 'Reply', 'puffergo' ); ?></a>
					</div>
				</div>
			</div>
		</li>
		<?php
		$comment_html = ob_get_clean();
	}

	wp_send_json_success( array(
		'message'       => $is_moderated ? __( 'Your comment is awaiting moderation', 'puffergo' ) : __( 'Comment submitted successfully!', 'puffergo' ),
		'comment_id'    => $comment_id,
		'comment_parent' => $comment_parent,
		'comment_html'  => $comment_html,
		'is_moderated'  => $is_moderated,
	) );
}

add_action( 'wp_ajax_puffergo_submit_comment', 'puffergo_handle_ajax_comment' );
add_action( 'wp_ajax_nopriv_puffergo_submit_comment', 'puffergo_handle_ajax_comment' );

// ─── 样式和脚本加载 ──────────────────────────────────────────

/**
 * 按需加载博客相关资源。
 */
function puffergo_enqueue_blog_assets() {
	$plugin_url = plugin_dir_url( PUFFERGO_PLUGIN_FILE );
	$plugin_dir = PUFFERGO_PLUGIN_DIR;

	// 博客归档 / 分类页
	$is_blog_archive = is_category()
		|| is_post_type_archive( 'post' )
		|| ( is_home() && ! is_front_page() );

	if ( $is_blog_archive ) {
		$css_file = $plugin_dir . '/assets/css/blog-archive.css';
		if ( file_exists( $css_file ) ) {
			wp_enqueue_style(
				'puffergo-blog-archive',
				$plugin_url . 'assets/css/blog-archive.css',
				array(),
				filemtime( $css_file )
			);
		}
	}

	// 博客详情页
	if ( is_singular( 'post' ) ) {
		$css_file = $plugin_dir . '/assets/css/blog-detail.css';
		if ( file_exists( $css_file ) ) {
			wp_enqueue_style(
				'puffergo-blog-detail',
				$plugin_url . 'assets/css/blog-detail.css',
				array(),
				filemtime( $css_file )
			);
		}

		$js_file = $plugin_dir . '/assets/js/blog-comments.js';
		if ( file_exists( $js_file ) ) {
			wp_enqueue_script(
				'puffergo-blog-comments',
				$plugin_url . 'assets/js/blog-comments.js',
				array(),
				filemtime( $js_file ),
				true
			);
		}
	}
}
add_action( 'wp_enqueue_scripts', 'puffergo_enqueue_blog_assets' );
