<?php
namespace Jet_Reviews\Endpoints;

use Jet_Reviews\Reviews\Data as Reviews_Data;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}
/**
 * Define Posts class
 */
class Update_Review_Type extends Base {

	/**
	 * [get_method description]
	 * @return [type] [description]
	 */
	public function get_method() {
		return 'POST';
	}

	/**
	 * Returns route name
	 *
	 * @return string
	 */
	public function get_name() {
		return 'update-review-type';
	}

	/**
	 * Returns arguments config
	 *
	 * @return [type] [description]
	 */
	public function get_args() {

		return array(
			'name' => array(
				'default'    => '',
				'required'   => false,
			),
			'slug' => array(
				'default'    => '',
				'required'   => false,
			),
			'settings' => array(
				'default'    => [],
				'required'   => false,
			),
		);
	}

	/**
	 * Check user access to current end-popint
	 *
	 * @return string|bool
	 */
	public function permission_callback( $request ) {
		return current_user_can( 'manage_options' );
	}

	/**
	 * [callback description]
	 * @param  [type]   $request [description]
	 * @return function          [description]
	 */
	public function callback( $request ) {
		$args = $request->get_params();
		$name  = $args['name'];
		$slug  = $args['slug'];
		$settings = $args['settings'];
		$prepared_data = array(
			'name' => $name,
			'slug' => $slug,
			'source' => $settings['source'],
			'source_type' => $settings['source_type'],
			'fields' => maybe_serialize( $settings['fields'] ),
			'settings' => maybe_serialize( $settings ),
		);

		$query = Reviews_Data::get_instance()->update_review_type( $prepared_data );
		do_action( 'jet-reviews/endpoints/reviews/update-review-type', $args );

		if ( ! $query ) {
			return rest_ensure_response( array(
				'success' => false,
				'message' => __( 'Server Error', 'jet-reviews' ),
			) );
		}

		return rest_ensure_response( array(
			'success'  => true,
			'message' => __( 'Review type has been updated', 'jet-reviews' ),
		) );
	}

}
