<?php
/**
 * REST API Post Comments controller
 *
 * Handles requests to the /posts/comments endpoint.
 *
 * @author   WooThemes
 * @category API
 * @package  WooCommerce/API
 * @since    2.6.0
 */

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

class W2W_REST_Post_Comments_Controller extends WP_REST_Controller {

	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'w2w/v1';

	/**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'posts/comments';
	
	/**
	 * Constructor.
	 *
	 * @since 4.7.0
	 */
	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	/**
	 * Register the routes for post comments.
	 */
	public function register_routes() {
		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_items' ),
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
				'args'                => $this->get_collection_params(),
			),
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'post_comment' ),
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
				'args'                => array(
					'context' => $this->get_context_param( array( 'default' => 'view' ) ),
					'post_id' => array(
						'required' => true
					)
				)
			),
			'schema' => array( $this, 'get_public_item_schema' ),
		) );
	}

	/**
	 * Check whether a given request has permission to read webhook deliveries.
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function get_items_permissions_check( $request ) {
		return true;
	}

	/**
	 * Check if a given request has access to read a webhook develivery.
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function get_item_permissions_check( $request ) {
		return true;
	}

	/**
	 * Get all comments from a post.
	 *
	 * @param WP_REST_Request $request
	 * @return array
	 */
	public function get_items( $request ) {
		$post = get_post( (int) $request['post_id'] );
		$number = isset( $request['number'] ) ? absint( $request['number'] ) : 10;
		$paged = isset( $request['page'] ) ? absint( $request['page'] ) : 1;
		$offset = ( $paged - 1 ) * $number;

		if ( empty( $post->post_type ) || 'post' !== $post->post_type ) {
			return new WP_Error( 'woocommerce_rest_post_invalid_id', __( 'Invalid post id.', 'woocommerce' ), array( 'status' => 404 ) );
		}

		$comments = get_approved_comments( $post->ID, array(
			'parent' => isset( $request['parent'] ) ? absint( $request['parent'] ) : 0,
			'order' => 'DESC',
			'number' => $number,
			'offset' => $offset
		) );
		$data    = array();
		foreach ( $comments as $comment_data ) {
			$comment = $this->prepare_item_for_response( $comment_data, $request );
			$comment = $this->prepare_response_for_collection( $comment );
			$data[] = $comment;
		}

		return rest_ensure_response( $data );
	}
	
	/**
	 * Create a review for a post.
	 *
	 * @param WP_REST_Request $request
	 * @return array
	 */
	public function post_comment( $request ) {
		
		if( ! is_user_logged_in() ) {
			return new WP_Error( 'need_login', '请登录后继续操作', array( 'status' => rest_authorization_required_code() ) );
		}
		
		if( empty( $request['comment'] ) ) {
			return new WP_Error( 'w2w_review_content_empty', '请输入评论内容' );
		}
		
		$post_id = $request['post_id'];
		$request['comment_post_ID'] = $post_id;
		$_POST['comment_post_ID'] = $post_id;
		
		$comment = wp_handle_comment_submission( $request );
		
		if( ! is_wp_error( $comment ) ) {
			
			$delivery = $this->prepare_item_for_response( $comment, $request );
			$comment = rest_ensure_response( $delivery );
		}

		return $comment;
	}

	/**
	 * Prepare a single post review output for response.
	 *
	 * @param WP_Comment $review Post review object.
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response $response Response data.
	 */
	public function prepare_item_for_response( $comment, $request ) {
		
		$avatar_url = get_user_meta( $comment->user_id, 'w2w_avatar', true );
		if( ! $avatar_url ) {
			$avatar_url = get_avatar_url( $comment );
		}

		$data = array(
			'id'           => (int) $comment->comment_ID,
			'date_created' => get_date_from_gmt( $comment->comment_date_gmt, 'Y-m-d' ),
			'comment'       => $comment->comment_content,
			'name'         => $comment->comment_author,
			'avatar'       => $avatar_url
		);

		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
		$data    = $this->add_additional_fields_to_object( $data, $request );
		$data    = $this->filter_response_by_context( $data, $context );

		// Wrap the data in a response object.
		$response = rest_ensure_response( $data );

		/**
		 * Filter post comments object returned from the REST API.
		 *
		 * @param WP_REST_Response $response The response object.
		 * @param WP_Comment       $comment   Post comment object used to create response.
		 * @param WP_REST_Request  $request  Request object.
		 */
		return apply_filters( 'w2w_rest_prepare_post_comment', $response, $comment, $request );
	}

	/**
	 * Get the Post Comment's schema, conforming to JSON Schema.
	 *
	 * @return array
	 */
	public function get_item_schema() {
		$schema = array(
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => 'post_comment',
			'type'       => 'object',
			'properties' => array(
				'id' => array(
					'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
					'type'        => 'integer',
					'context'     => array( 'view' ),
					'readonly'    => true,
				),
				'date_created' => array(
					'description' => __( "The date the comment was created, in the site's timezone.", 'woocommerce' ),
					'type'        => 'date-time',
					'context'     => array( 'view', 'edit' ),
					'readonly'    => true,
				),
				'name' => array(
					'description' => __( 'Author name.', 'woocommerce' ),
					'type'        => 'string',
					'context'     => array( 'view' ),
					'readonly'    => true,
				),
				'email' => array(
					'description' => __( 'Author email.', 'woocommerce' ),
					'type'        => 'string',
					'context'     => array( 'view' ),
					'readonly'    => true,
				)
			),
		);

		return $this->add_additional_fields_schema( $schema );
	}

	/**
	 * Get the query params for collections.
	 *
	 * @return array
	 */
	public function get_collection_params() {
		return array(
			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
		);
	}
}
