<?php

class Wiaas_Order_Projects_API {

	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	private static $namespace = 'wiaas';

	private static $rest_base = 'order-projects';

	public static function register_routes() {

		register_rest_route( self::$namespace, '/' . self::$rest_base, array(
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( __CLASS__, 'get_order_projects' ),
				'permission_callback' => 'is_user_logged_in',
				'args'                => array(),
			),
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( __CLASS__, 'create_order_project' ),
				'permission_callback' => 'is_user_logged_in',
				'args'                => array(
					'name' => array(
						'type'        => 'string',
						'description' => __( 'Order project name.', 'wiaas' ),
						'required'    => true,
						'sanitize_callback' => 'sanitize_text_field',
						'validate_callback' => function($param, $request, $key) {
							if ($param === '') {
								return new WP_Error(
									'rest_invalid_param',
									'Order project name cannot be empty!'
								);
							}
							if (strlen($param) > 100) {
								return new WP_Error(
									'rest_invalid_param',
									'Order project name cannot be longer than 100 characters!'
								);
							}
						},
					),
				),
			)
		) );
	}


	/**
	 * Retrieves available order projects
	 *
	 * @return WP_REST_Response
	 */
	public static function get_order_projects() {
		$projects = Wiaas_Order_Project::get_available_order_projects();

		return rest_ensure_response($projects);
	}

	/**
	 * Creates new available order project
	 *
	 * @param WP_REST_Request $request Request data.
	 *
	 * @return WP_REST_Response
	 */
	public static function create_order_project($request) {
		$name = $request['name'];

		$success = Wiaas_Order_Project::add_order_project($name);
		if ($success) {
			return wiaas_api_notice('PROJECT_ADDED', 'success');
		}

		return wiaas_api_notice('INVALID_DATA', 'error');
	}

}