<?php
namespace QuizPress\API\Controller;

use QuizPress\API\Schema\CategorySchema;
use QuizPress\API\Query\Category as Query;

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


class Category extends \WP_REST_Controller {

	use CategorySchema;

	public static function init() {
		$self            = new self();
		$self->namespace = QUIZPRESS_PLUGIN_SLUG . '/v1';
		$self->rest_base = 'category';
		add_action( 'rest_api_init', array( $self, 'register_routes' ) );
	}

	/**
	 * Register the routes for the objects of the controller.
	 */
	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' => '__return_true',
					'args'                => $this->get_collection_params(),
				),
				array(
					'methods'             => \WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'create_item' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_item_schema(),
				),
				'schema' => [ $this, 'get_public_item_schema' ],
			)
		);

		$get_item_args = array(
			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<id>[\d]+)',
			array(
				'args'   => array(
					'id' => array(
						'description' => esc_html__( 'Unique identifier for the object.', 'quizpress' ),
						'type'        => 'integer',
					),
				),
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_item' ),
					'permission_callback' => '__return_true',
					'args'                => $get_item_args,
				),
				array(
					'methods'             => \WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_item' ),
					'permission_callback' => array( $this, 'update_item_permissions_check' ),
					'args'                => $this->get_item_schema(),
				),
				array(
					'methods'             => \WP_REST_Server::DELETABLE,
					'callback'            => array( $this, 'delete_item' ),
					'permission_callback' => array( $this, 'delete_item_permissions_check' ),
					'args'                => array(
						'force' => array(
							'type'        => 'boolean',
							'default'     => false,
							'description' => esc_html__( 'Whether to bypass Trash and force deletion.', 'quizpress' ),
						),
					),
				),
				'schema' => [ $this, 'get_public_item_schema' ],
			)
		);

	}

	public function create_item_permissions_check( $request ) {
		if ( ! current_user_can( 'edit_posts' ) ) {
			return new \WP_Error(
				'rest_forbidden_context',
				esc_html__( 'Sorry, you are not allowed to create category', 'quizpress' ),
				array( 'status' => rest_authorization_required_code() )
			);
		}
		return true;
	}

	public function update_item_permissions_check( $request ) {
		if ( ! current_user_can( 'edit_posts' ) ) {
			return new \WP_Error(
				'rest_forbidden_context',
				esc_html__( 'Sorry, you are not allowed to update category', 'quizpress' ),
				array( 'status' => rest_authorization_required_code() )
			);
		}
		return true;
	}

	public function delete_item_permissions_check( $request ) {
		if ( ! current_user_can( 'edit_posts' ) ) {
			return new \WP_Error(
				'rest_forbidden_context',
				esc_html__( 'Sorry, you are not allowed to delete category', 'quizpress' ),
				array( 'status' => rest_authorization_required_code() )
			);
		}
		return true;
	}

	/**
	 * Retrieves a collection of posts.
	 *
	 * @since 4.7.0
	 *
	 * @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 ) {
		$page     = max( 1, absint( $request->get_param( 'page' ) ) );
		$per_page = max( 1, absint( $request->get_param( 'per_page' ) ) );
		$keyword  = $request->get_param( 'keyword' );

		$args = array(
			'per_page' => $per_page,
			'offset'   => ( $page - 1 ) * $per_page,
			'status'   => $request->get_param( 'status' ),
			'keyword'  => $keyword,
		);

		$categories = Query::get_category( $args );

		$data = array();
		if ( empty( $categories ) ) {
			$response = rest_ensure_response( $data );
			$response->header( 'x-wp-total', 0 );
			return $response;
		}

		foreach ( $categories as $category ) {
			$response = $this->rest_prepare_item( $category, $request );
			$data[] = $this->rest_prepare_for_collection( $response );
		}

		$response = rest_ensure_response( $data );
		$response->header( 'x-wp-total', Query::get_total_category() );

		return $response;
	}

	public function get_item( $request ) {

		$id = absint( $request->get_param( 'id' ) );

		$category = Query::get_question_category( $id );

		if ( empty( $category ) ) {
			return rest_ensure_response( array() );
		}
		$response = $this->rest_prepare_for_collection(
			$this->rest_prepare_item( $category, $request )
		);

		return rest_ensure_response( $response );
	}


	/**
	 * Creates a single post.
	 *
	 * @since 4.7.0
	 *
	 * @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 create_item( $request ) {
		if ( ! empty( $request['id'] ) ) {
			return new \WP_Error(
				'rest_post_exists',
				esc_html__( 'Cannot create existing category.', 'quizpress' ),
				array( 'status' => 400 )
			);
		}

		$prepared_category = $this->prepare_item_for_database( $request );
		$category_id = Query::category_insert( wp_unslash( (array) $prepared_category ) );
		$category = Query::get_question_category( $category_id );
		$response = $this->rest_prepare_item( $category, $request );
		return rest_ensure_response( $response );
	}

	public function update_item( $request ) {
		$params = $request->get_params();
		if ( empty( $params['id'] ) ) {
			return new \WP_Error(
				'rest_category_id_not_exists',
				esc_html__( 'Cannot update existing category.', 'quizpress' ),
				array( 'status' => 400 )
			);
		}
		$prepared_category = $this->prepare_item_for_database( $request );
		$category_id = Query::category_insert( wp_unslash( (array) $prepared_category ) );
		$category = Query::get_question_category( $category_id );
		$response = $this->rest_prepare_item( $category, $request );
		return rest_ensure_response( $response );
	}

	public function delete_item( $request ) {
		$category_id = $request->get_param( 'id' );
		$is_delete = Query::delete_category( $category_id );
		return new \WP_REST_Response( $is_delete, 200 );
	}


	protected function rest_prepare_item( $category ) {
		$data   = array();
		$schema = $this->get_public_item_schema();

		if ( isset( $schema['properties']['id'] ) ) {
			$data['id'] = (int) ( $category->id ?? 0 );
		}

		if ( isset( $schema['properties']['category_title'] ) ) {
			$data['category_title'] = $category->category_title ?? '';
		}

		if ( isset( $schema['properties']['category_slug'] ) ) {
			$data['category_slug'] = $category->category_slug ?? '';
		}

		if ( isset( $schema['properties']['category_content'] ) ) {
			$data['category_content'] = $category->category_content ?? '';
		}

		return $data;
	}

	protected function prepare_item_for_database( $request ) {
		$prepared_category  = new \stdClass();

		$schema = $this->get_item_schema();

		// Category Id.
		if ( ! empty( $schema['id'] ) && isset( $request['id'] ) ) {
			if ( is_numeric( $request['id'] ) ) {
				$prepared_category->id = $request['id'];
			}
		}

		// Category title.
		if ( ! empty( $schema['category_title'] ) && isset( $request['category_title'] ) ) {
			if ( is_string( $request['category_title'] ) ) {
				$prepared_category->category_title = $request['category_title'];
			}
		}

		// Category slug.
		if ( ! empty( $schema['category_slug'] ) && isset( $request['category_slug'] ) ) {
			if ( is_string( $request['category_slug'] ) ) {
				$prepared_category->category_slug = $request['category_slug'];
			}
		}

		// Category Content.
		if ( ! empty( $schema['category_content'] ) && isset( $request['category_content'] ) ) {
			if ( is_string( $request['category_content'] ) ) {
				$prepared_category->category_content = $request['category_content'];
			}
		}

		return apply_filters( 'quizpress/api/rest_pre_insert_category', $prepared_category, $request );
	}

	protected function rest_prepare_for_collection( $response ) {
		if ( ! ( $response instanceof \WP_REST_Response ) ) {
			return $response;
		}

		$data  = (array) $response->get_data();
		$server = rest_get_server();
		if ( method_exists( $server, 'get_compact_response_links' ) ) {
			$links = call_user_func( array( $server, 'get_compact_response_links' ), $response );
		} else {
			$links = call_user_func( array( $server, 'get_response_links' ), $response );
		}

		if ( ! empty( $links ) ) {
			$data['_links'] = $links;
		}

		return $data;
	}
}
