<?php
/**
 * Settings endpoints.
 *
 * @package Nisje
 */

namespace Dekode\Nisje\Components\Rest;

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

/**
 * Settings Rest Class.
 */
class Settings_Controller extends \WP_REST_Controller {

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->namespace = 'nisje/v1';
		$this->rest_base = 'settings';
	}
	/**
	 * Register the routes.
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/',
			[
				[
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => [ $this, 'get_item' ],
					'permission_callback' => '__return_true',
					'args'                => [
						'context' => $this->get_context_param(
							[
								'default' => 'view',
							]
						),
					],
				],
				'schema' => [ $this, 'get_public_item_schema' ],
			]
		);
	}
	/**
	 * Retrieve graph data from a website.
	 *
	 * @param  WP_REST_Request $request Request.
	 * @return WP_REST_Request|WP_Error Plugin object data on success, WP_Error otherwise.
	 */
	public function get_item( $request ) {
		$settings = [];

		$data = $this->prepare_item_for_response( $settings, $request );

		$response = rest_ensure_response( $data );

		return $response;
	}

	/**
	 * Prepares scraper data for return as an object.
	 *
	 * @param stdClass        $item    Item data.
	 * @param WP_REST_Request $request Request.
	 * @param boolean         $is_raw  Optional, not used. Defaults to false.
	 *
	 * @return WP_REST_Response
	 */
	public function prepare_item_for_response( $item, $request, $is_raw = false ) {
		$schema = $this->get_item_schema();

		$data = [];

		if ( ! empty( $schema['properties']['active_components'] ) ) {
			$data['active_components'] = nisje_get_active_components();
		}

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

		$response = rest_ensure_response( $data );

		/**
		 * Filter an scraper value returned from the API.
		 *
		 * @param array           $response
		 * @param WP_REST_Request $request Request used to generate the response.
		 */
		return apply_filters( 'nisje_rest_prepare_settings_value', $response, $item, $request );
	}
	/**
	 * Get the plugin schema, conforming to JSON Schema.
	 *
	 * @return array
	 */
	public function get_item_schema() {
		$schema = [
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => 'settings',
			'type'       => 'object',
			'properties' => [
				'active_components' => [
					'description' => esc_html__( 'Active components', 'nisje' ),
					'type'        => 'array',
					'items'       => [
						'type' => 'string',
					],
					'readonly'    => true,
				],
			],
		];

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