<?php
/**
 * Feed Endpoints
 *
 * @package Nisje
 */

namespace Dekode\Nisje\Components\Rest;

defined( 'ABSPATH' ) || die( 'Shame on you' );

/**
 * Feed Rest Class
 */
class Feed_Controller extends \WP_REST_Controller {
	/**
	 * Constructor
	 */
	public function __construct() {
		$this->namespace = nisje_get_rest_namespace();
		$this->rest_base = 'feed';
		$this->hook_base = strtolower( $this->rest_base );
	}

	/**
	 * Registers routes
	 */
	public function register_routes() {
		register_rest_route( $this->namespace, '/' . $this->rest_base, [
			[
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => [ $this, 'get_items' ],
				'permission_callback' => [ $this, 'get_items_permissions_check' ],
				'args'                => $this->get_collection_params(),
			],
			'schema' => [ $this, 'get_public_item_schema' ],
		] );
	}

	/**
	 * Checks if a given request has access to access a feed
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return true|WP_Error True if the request has read access for the item, otherwise WP_Error object.
	 */
	public function get_items_permissions_check( $request ) {
		$auth = nisje_validate_rest_authentication( $this->hook_base, 'get_items' );
		if ( is_wp_error( $auth ) ) {
			return $auth;
		}

		if ( bp_is_active( 'groups' ) ) {
			$group_id = (int) $request['group_id'];
			if ( 0 !== $group_id ) {
				$group = nisje_get_group( $group_id );
				if ( is_wp_error( $group ) ) {
					return $group;
				}

				if ( 'public' !== $group->status && ! groups_is_user_member( bp_loggedin_user_id(), $group->id ) ) {
					return new \WP_Error( 'nisje_rest_cannot_read', esc_html__( 'Sorry, you are not allowed to see content for this group.', 'nisje' ), [
						'status' => rest_authorization_required_code(),
					] );
				}
			}
		}

		return true;
	}

	/**
	 * Retrieves a feed.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
	 */
	public function get_items( $request ) {
		// Retrieve the list of registered collection query parameters.
		$registered = $this->get_collection_params();
		$args       = [];

		/**
		 * This array defines mappings between public API query parameters whose
		 * values are accepted as-passed, and their internal WP_Query parameter
		 * name equivalents (some are the same). Only values which are also
		 * present in $registered will be set.
		 */
		$parameter_mappings = [
			'author'         => 'author__in',
			'author_exclude' => 'author__not_in',
			'exclude'        => 'post__not_in',
			'offset'         => 'offset',
			'page'           => 'paged',
			'search'         => 's',
		];

		if ( bp_is_active( 'groups' ) ) {
			if ( ! $request['group_id'] ) {
				$user_id   = bp_loggedin_user_id();
				$groups    = [ 0 ];
				$group_ids = groups_get_user_groups( $user_id );
				foreach ( $group_ids['groups'] as $group_id ) {
					$groups[] = $group_id;
				}
			} else {
				$groups = [ $request['group_id'] ];
			}

			$args['post_parent__in'] = $groups;
		}

		/*
		 * For each known parameter which is both registered and present in the request,
		 * set the parameter's value on the query $args.
		 */
		foreach ( $parameter_mappings as $api_param => $wp_param ) {
			if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
				$args[ $wp_param ] = $request[ $api_param ];
			}
		}

		// Check for & assign any parameters which require special handling or setting.
		$args['date_query'] = [];

		// Set before into date query. Date query must be specified as an array of an array.
		if ( isset( $registered['before'], $request['before'] ) ) {
			$args['date_query'][0]['before'] = $request['before'];
		}

		// Set after into date query. Date query must be specified as an array of an array.
		if ( isset( $registered['after'], $request['after'] ) ) {
			$args['date_query'][0]['after'] = $request['after'];
		}

		// Ensure our per_page parameter overrides any provided posts_per_page filter.
		if ( isset( $registered['per_page'] ) ) {
			$args['posts_per_page'] = $request['per_page'];
		}

		/**
		 * Filters allowed post types.
		 *
		 * @param array $post_types Allowd post types.
		 */
		$post_types = apply_filters( 'nisje_feed_post_types', [] );

		$args['post_type'] = $post_types;
		if ( isset( $request['post_types'] ) && ! empty( $request['post_types'] ) ) {
			$args['post_type'] = $request['post_types'];
		}

		$taxonomies = [];
		foreach ( $post_types as $post_type ) {
			$taxonomies = array_merge( wp_list_filter( get_object_taxonomies( $post_type, 'objects' ), [
				'show_in_rest' => true,
			] ), $taxonomies );
		}

		foreach ( $taxonomies as $taxonomy ) {
			$base        = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
			$tax_exclude = $base . '_exclude';

			if ( ! empty( $request[ $base ] ) ) {
				$args['tax_query'][] = [
					'taxonomy'         => $taxonomy->name,
					'field'            => 'term_id',
					'terms'            => $request[ $base ],
					'include_children' => false,
				];
			}

			if ( ! empty( $request[ $tax_exclude ] ) ) {
				$args['tax_query'][] = [
					'taxonomy'         => $taxonomy->name,
					'field'            => 'term_id',
					'terms'            => $request[ $tax_exclude ],
					'include_children' => false,
					'operator'         => 'NOT IN',
				];
			}
		}

		if ( ! empty( $request['type'] ) ) {
			$args['tax_query'][] = [
				'taxonomy'         => nisje_get_setting( 'taxonomy_type_name', 'user-content' ),
				'field'            => 'slug',
				'terms'            => $request['type'],
				'include_children' => false,
			];
		}

		if ( ! empty( $request['type_exclude'] ) ) {
			$args['tax_query'][] = [
				'taxonomy'         => nisje_get_setting( 'taxonomy_type_name', 'user-content' ),
				'field'            => 'slug',
				'terms'            => $request['type'],
				'include_children' => false,
				'operator'         => 'NOT IN',
			];
		}

		/**
		 * Filters the query arguments for a request.
		 *
		 * Enables adding extra arguments or setting defaults for a feed collection request.
		 *
		 * @param array           $args    Key value array of query var to query value.
		 * @param WP_REST_Request $request The request used.
		 */
		$query_args = apply_filters( "nisje_rest_{$this->hook_base}_query", $args, $request );

		$posts_query  = new \WP_Query();
		$query_result = $posts_query->query( $query_args );

		$posts = [];

		foreach ( $query_result as $post ) {
			if ( ! $this->check_read_permission( $post ) ) {
				continue;
			}

			$data    = $this->prepare_item_for_response( $post, $request );
			$posts[] = $this->prepare_response_for_collection( $data );
		}

		$page        = (int) $query_args['paged'];
		$total_posts = $posts_query->found_posts;

		if ( $total_posts < 1 ) {
			// Out-of-bounds, run the query again without LIMIT for total count.
			unset( $query_args['paged'] );

			$count_query = new \WP_Query();
			$count_query->query( $query_args );
			$total_posts = $count_query->found_posts;
		}

		$max_pages = ceil( $total_posts / (int) $posts_query->query_vars['posts_per_page'] );

		if ( $page > $max_pages && $total_posts > 0 ) {
			return new \WP_Error( 'nisje_rest_post_invalid_page_number', esc_html__( 'The page number requested is larger than the number of pages available.', 'nisje' ), [
				'status' => 400,
			] );
		}

		$response = rest_ensure_response( $posts );

		$response->header( 'X-WP-Total', (int) $total_posts );
		$response->header( 'X-WP-TotalPages', (int) $max_pages );

		$request_params = $request->get_query_params();
		$base           = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );

		if ( $page > 1 ) {
			$prev_page = $page - 1;

			if ( $prev_page > $max_pages ) {
				$prev_page = $max_pages;
			}

			$prev_link = add_query_arg( 'page', $prev_page, $base );
			$response->link_header( 'prev', $prev_link );
		}
		if ( $max_pages > $page ) {
			$next_page = $page + 1;
			$next_link = add_query_arg( 'page', $next_page, $base );

			$response->link_header( 'next', $next_link );
		}

		return $response;
	}

	/**
	 * Prepares the response for output
	 *
	 * @param array           $post Post object.
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response  Response object.
	 */
	public function prepare_item_for_response( $post, $request ) {
		$data   = [];
		$schema = $this->get_item_schema();

		if ( ! empty( $schema['properties']['id'] ) ) {
			$data['id'] = $post->ID;
		}

		if ( ! empty( $schema['properties']['link'] ) ) {
			$data['link'] = get_permalink( $post->ID );
		}

		if ( ! empty( $schema['properties']['author'] ) ) {
			$data['author'] = (int) $post->post_author;
		}

		if ( ! empty( $schema['properties']['date'] ) ) {
			$data['date'] = nisje_prepare_date_response( $post->post_date_gmt, $post->post_date );
		}

		if ( ! empty( $schema['properties']['date_gmt'] ) ) {
			// For drafts, `post_date_gmt` may not be set, indicating that the
			// date of the draft should be updated each time it is saved (see
			// #38883).  In this case, shim the value based on the `post_date`
			// field with the site's timezone offset applied.
			if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
				$post_date_gmt = get_gmt_from_date( $post->post_date );
			} else {
				$post_date_gmt = $post->post_date_gmt;
			}
			$data['date_gmt'] = nisje_prepare_date_response( $post_date_gmt );
		}

		if ( ! empty( $schema['properties']['modified'] ) ) {
			$data['modified'] = nisje_prepare_date_response( $post->post_modified_gmt, $post->post_modified );
		}

		if ( ! empty( $schema['properties']['modified_gmt'] ) ) {
			// For drafts, `post_modified_gmt` may not be set (see
			// `post_date_gmt` comments above).  In this case, shim the value
			// based on the `post_modified` field with the site's timezone
			// offset applied.
			if ( '0000-00-00 00:00:00' === $post->post_modified_gmt ) {
				$post_modified_gmt = gmdate( 'Y-m-d H:i:s', strtotime( $post->post_modified ) - ( get_option( 'gmt_offset' ) * 3600 ) );
			} else {
				$post_modified_gmt = $post->post_modified_gmt;
			}
			$data['modified_gmt'] = nisje_prepare_date_response( $post_modified_gmt );
		}

		if ( ! empty( $schema['properties']['post_type'] ) ) {
			$data['post_type'] = $post->post_type;
		}

		if ( ! empty( $schema['properties']['title'] ) ) {
			add_filter( 'protected_title_format', [ $this, 'protected_title_format' ] );

			$data['title'] = [
				'raw'      => $post->post_title,
				'rendered' => get_the_title( $post->ID ),
			];

			remove_filter( 'protected_title_format', [ $this, 'protected_title_format' ] );
		}

		$has_password_filter = false;

		if ( $this->can_access_password_content( $post, $request ) ) {
			// Allow access to the post, permissions already checked before.
			add_filter( 'post_password_required', '__return_false' );

			$has_password_filter = true;
		}

		if ( ! empty( $schema['properties']['content'] ) ) {
			$data['content'] = [
				'raw'       => $post->post_content,
				/** This filter is documented in wp-includes/post-template.php */
				'rendered'  => post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content ),
				'protected' => (bool) $post->post_password,
			];
		}

		if ( ! empty( $schema['properties']['excerpt'] ) ) {
			/** This filter is documented in wp-includes/post-template.php */
			$excerpt         = apply_filters( 'the_excerpt', $post->post_excerpt );
			$data['excerpt'] = [
				'raw'       => $post->post_excerpt,
				'rendered'  => post_password_required( $post ) ? '' : $excerpt,
				'protected' => (bool) $post->post_password,
			];
		}

		if ( $has_password_filter ) {
			// Reset filter.
			remove_filter( 'post_password_required', '__return_false' );
		}

		if ( ! empty( $schema['properties']['comment_status'] ) ) {
			$data['comment_status'] = $post->comment_status;
		}

		$taxonomies = wp_list_filter( get_object_taxonomies( $post->post_type, 'objects' ), [ 'show_in_rest' => true ] );

		foreach ( $taxonomies as $taxonomy ) {
			$base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;

			$terms         = get_the_terms( $post, $taxonomy->name );
			$data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : [];
		}

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

		/**
		 * Filters the post data for a response.
		 *
		 * @param WP_REST_Response $response The response object.
		 * @param WP_Post          $post     Post object.
		 * @param WP_REST_Request  $request  Request object.
		 */
		return apply_filters( "nisje_rest_prepare_{$this->hook_base}", $response, $post, $request );
	}

	/**
	 * Checks if a post can be read.
	 *
	 * Correctly handles posts with the inherit status.
	 *
	 * @param object $post Post object.
	 * @return bool Whether the post can be read.
	 */
	public function check_read_permission( $post ) {
		$post_type = get_post_type_object( $post->post_type );

		// Is the post readable?
		if ( 'publish' === $post->post_status || current_user_can( $post_type->cap->read_post, $post->ID ) ) {
			return true;
		}

		$post_status_obj = get_post_status_object( $post->post_status );
		if ( $post_status_obj && $post_status_obj->public ) {
			return true;
		}

		// Can we read the parent if we're inheriting?
		if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) {
			$parent = get_post( $post->post_parent );
			if ( $parent ) {
				return $this->check_read_permission( $parent );
			}
		}

		/*
		 * If there isn't a parent, but the status is set to inherit, assume
		 * it's published (as per get_post_status()).
		 */
		if ( 'inherit' === $post->post_status ) {
			return true;
		}

		return false;
	}

	/**
	 * Checks if the user can access password-protected content.
	 *
	 * This method determines whether we need to override the regular password
	 * check in core with a filter.
	 *
	 * @param WP_Post         $post    Post to check against.
	 * @param WP_REST_Request $request Request data to check.
	 * @return bool True if the user can access password-protected content, otherwise false.
	 */
	public function can_access_password_content( $post, $request ) {
		if ( empty( $post->post_password ) ) {
			// No filter required.
			return false;
		}

		// Edit context always gets access to password-protected posts.
		if ( 'edit' === $request['context'] ) {
			return true;
		}

		// No password, no auth.
		if ( empty( $request['password'] ) ) {
			return false;
		}

		// Double-check the request password.
		return hash_equals( $post->post_password, $request['password'] );
	}

	/**
	 * Retrieves the schema, conforming to JSON Schema.
	 *
	 * @return array Item schema data.
	 */
	public function get_item_schema() {
		$schema = [
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => $this->hook_base,
			'type'       => 'object',
			// Base properties for every Post.
			'properties' => [
				'date'         => [
					'description' => esc_html__( "The date the object was published, in the site's timezone.", 'nisje' ),
					'type'        => 'string',
					'format'      => 'date-time',
					'context'     => [ 'view' ],
					'readonly'    => true,
				],
				'date_gmt'     => [
					'description' => esc_html__( 'The date the object was published, as GMT.', 'nisje' ),
					'type'        => 'string',
					'format'      => 'date-time',
					'context'     => [ 'view' ],
					'readonly'    => true,
				],
				'id'           => [
					'description' => esc_html__( 'Unique identifier for the object.', 'nisje' ),
					'type'        => 'integer',
					'context'     => [ 'view' ],
					'readonly'    => true,
				],
				'link'         => [
					'description' => esc_html__( 'URL to the object.', 'nisje' ),
					'type'        => 'string',
					'format'      => 'uri',
					'context'     => [ 'view', 'edit', 'embed' ],
					'readonly'    => true,
				],
				'modified'     => [
					'description' => esc_html__( "The date the object was last modified, in the site's timezone.", 'nisje' ),
					'type'        => 'string',
					'format'      => 'date-time',
					'context'     => [ 'view' ],
					'readonly'    => true,
				],
				'modified_gmt' => [
					'description' => esc_html__( 'The date the object was last modified, as GMT.', 'nisje' ),
					'type'        => 'string',
					'format'      => 'date-time',
					'context'     => [ 'view' ],
					'readonly'    => true,
				],
				'post_type'    => [
					'description' => esc_html__( 'Type of Post for the object.', 'nisje' ),
					'type'        => 'string',
					'context'     => [ 'view' ],
					'readonly'    => true,
				],
				'title'        => [
					'description' => esc_html__( 'The title for the object.', 'nisje' ),
					'type'        => 'object',
					'context'     => [ 'view' ],
					'arg_options' => [
						'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
						'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
					],
					'properties'  => [
						'rendered' => [
							'description' => esc_html__( 'HTML title for the object, transformed for display.', 'nisje' ),
							'type'        => 'string',
							'context'     => [ 'view' ],
							'readonly'    => true,
						],
					],
				],
				'content'      => [
					'description' => esc_html__( 'The content for the object.', 'nisje' ),
					'type'        => 'object',
					'context'     => [ 'view' ],
					'arg_options' => [
						'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
						'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
					],
					'properties'  => [
						'rendered' => [
							'description' => esc_html__( 'HTML content for the object, transformed for display.', 'nisje' ),
							'type'        => 'string',
							'context'     => [ 'view' ],
							'readonly'    => true,
						],
					],
				],
				'author'       => [
					'description' => esc_html__( 'The ID for the author of the object.', 'nisje' ),
					'type'        => 'integer',
					'context'     => [ 'view' ],
				],
				'excerpt'      => [
					'description' => esc_html__( 'The excerpt for the object.', 'nisje' ),
					'type'        => 'object',
					'context'     => [ 'view' ],
					'arg_options' => [
						'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
						'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
					],
					'properties'  => [
						'rendered' => [
							'description' => esc_html__( 'HTML excerpt for the object, transformed for display.', 'nisje' ),
							'type'        => 'string',
							'context'     => [ 'view' ],
							'readonly'    => true,
						],
					],
				],
			],
		];

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

	/**
	 * Retrieves the query params for the feed collection.
	 *
	 * @return array Collection parameters.
	 */
	public function get_collection_params() {
		$post_types = apply_filters( 'nisje_feed_post_types', [] );

		$query_params = parent::get_collection_params();

		$query_params['context']['default'] = 'view';

		$query_params['group_id'] = [
			'description' => esc_html__( 'Limit result to a specific group.', 'nisje' ),
			'type'        => 'integer',
		];

		$query_params['after'] = [
			'description' => esc_html__( 'Limit response to posts published after a given ISO8601 compliant date.', 'nisje' ),
			'type'        => 'string',
			'format'      => 'date-time',
		];

		$query_params['author'] = [
			'description' => esc_html__( 'Limit result set to posts assigned to specific authors.', 'nisje' ),
			'type'        => 'array',
			'items'       => [
				'type' => 'integer',
			],
			'default'     => [],
		];

		$query_params['author_exclude'] = [
			'description' => esc_html__( 'Ensure result set excludes posts assigned to specific authors.', 'nisje' ),
			'type'        => 'array',
			'items'       => [
				'type' => 'integer',
			],
			'default'     => [],
		];

		$query_params['before'] = [
			'description' => esc_html__( 'Limit response to posts published before a given ISO8601 compliant date.', 'nisje' ),
			'type'        => 'string',
			'format'      => 'date-time',
		];

		$query_params['exclude'] = [
			'description' => esc_html__( 'Ensure result set excludes specific IDs.', 'nisje' ),
			'type'        => 'array',
			'items'       => [
				'type' => 'integer',
			],
			'default'     => [],
		];

		$query_params['offset'] = [
			'description' => esc_html__( 'Offset the result set by a specific number of items.', 'nisje' ),
			'type'        => 'integer',
		];

		foreach ( $post_types as $post_type ) {
			$taxonomies = wp_list_filter( get_object_taxonomies( $post_type, 'objects' ), [
				'show_in_rest' => true,
			] );

			foreach ( $taxonomies as $taxonomy ) {
				$base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;

				$query_params[ $base ] = [
					/* translators: %s: taxonomy name */
					'description' => sprintf( esc_html__( 'Limit result set to all items that have the specified term assigned in the %s taxonomy.', 'nisje' ), $base ),
					'type'        => 'array',
					'items'       => [
						'type' => 'integer',
					],
					'default'     => [],
				];

				$query_params[ $base . '_exclude' ] = [
					/* translators: %s: taxonomy name */
					'description' => sprintf( esc_html__( 'Limit result set to all items except those that have the specified term assigned in the %s taxonomy.', 'nisje' ), $base ),
					'type'        => 'array',
					'items'       => [
						'type' => 'integer',
					],
					'default'     => [],
				];
			}
		}

		$query_params['type'] = [
			/* translators: %s: taxonomy name */
			'description' => sprintf( esc_html__( 'Limit result set to all items that have the specified term assigned in the %s taxonomy.', 'nisje' ), $base ),
			'type'        => 'array',
			'items'       => [
				'type' => 'string',
			],
			'default'     => [],
		];

		$query_params['type_exclude'] = [
			/* translators: %s: taxonomy name */
			'description' => sprintf( esc_html__( 'Limit result set to all items except those that have the specified term assigned in the %s taxonomy.', 'nisje' ), $base ),
			'type'        => 'array',
			'items'       => [
				'type' => 'string',
			],
			'default'     => [],
		];

		$query_params['post_types'] = [
			'description' => esc_html__( 'Filter by post types.', 'nisje' ),
			'type'        => 'array',
			'items'       => [
				'type' => 'string',
			],
			'default'     => [],
		];

		/**
		 * Filter collection parameters for the posts controller.
		 *
		 * @param array        $query_params JSON Schema-formatted collection parameters.
		 */
		return apply_filters( "nisje_rest_{$this->hook_base}_collection_params", $query_params );
	}
}
