<?php

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

/**
 * TODO: This is temporary implemetation and will probably be changed during work on pending wiaas cart task
 * 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, 'documents/order/(?P<id>\d+)/(?P<type>[\w-]+)', array(
			'args'   => array(
				'id' => array(
					'description' => __( 'Order ID.', 'wiaas' ),
					'type'        => 'integer',
					'sanitize_callback' => 'absint',
				),
				'type' => array(
					'description' => __( 'Order document type.', 'wiaas' ),
					'type'        => 'string',
					'sanitize_callback' => 'sanitize_key',
				),
			),
			array(
				'methods' => 'GET',
				'permission_callback' => 'is_user_logged_in',
				'callback' => array(__CLASS__, 'download_order_document'),
				'args' => array(
					'item_id' => array(
						'description' => __( 'Package Order Item ID.', 'wiaas' ),
						'type' => 'integer',
						'sanitize_callback' => 'absint',
					),
					'document_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 document
	 * @param WP_REST_Request $request
	 */
	public static function download_order_document($request) {
		Wiaas_Document_Download::download_order_item_document(
			$request['id'],
			$request['item_id'],
			$request['type'],
			$request['document_key']);
	}
}