<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * Class Wiaas_Document_API
 */
class Wiaas_Document_API {
	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	private static $namespace = 'wiaas';

	public static function register_routes() {
		register_rest_route( self::$namespace, 'documents', array(
			'methods' => 'GET',
			'permission_callback' => 'is_user_logged_in',
			'callback' => array(__CLASS__, 'download_package_file'),
			'args' => array(
				'document_id' => array(
					'description' => __( 'Document ID.', 'wiaas' ),
					'type' => 'integer',
					'sanitize_callback' => 'absint',
				)
			)
		) );

		register_rest_route( self::$namespace, 'order/(?P<id>\d+)/item/(?P<item_id>\d+)/document/(?P<key>[\w-]+)', array(
			'args'   => array(
				'id' => array(
					'description' => __( 'Order ID.', 'wiaas' ),
					'type'        => 'integer',
					'sanitize_callback' => 'absint',
				)
			),
			array(
				'methods' => 'GET',
				'permission_callback' => 'is_user_logged_in',
				'callback' => array(__CLASS__, 'download_order_item_document'),
				'args' => array(
					'item_id' => array(
						'description' => __( 'Package Order Item ID.', 'wiaas' ),
						'type' => 'integer',
						'sanitize_callback' => 'absint',
						'required' => true
					),
					'key' => array(
						'description' => __( 'Unique key identifier for order document.', 'wiaas' ),
						'type'        => 'string',
						'sanitize_callback' => 'sanitize_key',
						'required' => true
					),
				)
			)
		) );

		register_rest_route(self::$namespace, 'order/(?P<id>\d+)/document/(?P<key>[\w-]+)', array(
			'args' => array(
				'id' => array(
					'description' => __( 'Order ID.', 'wiaas' ),
					'type'        => 'integer',
					'sanitize_callback' => 'absint',
				)
			),
			array(
				'methods' => 'GET',
				'permission_callback' => 'is_user_logged_in',
				'callback' => array(__CLASS__, 'download_order_other_document'),
				'args' => array(
					'key' => array(
						'description' => __( 'Unique key identifier for order document.', 'wiaas' ),
						'type'        => 'string',
						'sanitize_callback' => 'sanitize_key',
						'required' => true
					),
				)
			)
		));
	}

	/**
	 * Download package document
	 *
	 * @param  WP_REST_Request $request
	 */
	public static function download_package_file($request) {
		$document_id = $request['document_id'];

		Wiaas_Document_Download::download_document($document_id);
	}

	/**
	 * Download order item document
	 *
	 * @param WP_REST_Request $request
	 */
	public static function download_order_item_document($request) {
		Wiaas_Document_Download::download_order_item_document(
			$request['id'],
			$request['item_id'],
			$request['key']);
	}

	/**
	 * Download order document
	 *
	 * @param WP_REST_Request $request
	 */
	public static function download_order_other_document($request) {
		Wiaas_Document_Download::download_order_other_document($request['id'], $request['key']);
	}
}