<?php
/**
 * Products API endpoint handler.
 *
 * @package Awesomemotive\Rewardswp\Api\V1
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Api\V1;

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

use Awesomemotive\Rewardswp\Interfaces\IntegrationInterface;
use function Awesomemotive\Rewardswp\Helpers\is_rewardswp_lite_plan;

/**
 * Class ProductsApi
 *
 * @package RewardsWP
 */
class ProductsApi extends \WP_REST_Controller {
	/**
	 * REST namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'rewardswp/v1';

	/**
	 * Current integration instance.
	 *
	 * @var IntegrationInterface
	 */
	private IntegrationInterface $integration;

	/**
	 * ProductsApi constructor.
	 *
	 * @param IntegrationInterface $integration Active integration instance.
	 */
	public function __construct( IntegrationInterface $integration ) {
		$this->integration = $integration;
	}

	/**
	 * Registers the routes for the objects of the controller.
	 *
	 * @see register_rest_route()
	 */
	public function register_routes() {
		// Example route.
		register_rest_route(
			$this->namespace,
			'/products',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_products' ),
				'permission_callback' => array( $this, 'get_products_permissions_check' ),
				'args'                => [
					'search' => [
						'required'          => true,
						'type'              => 'string',
						'description'       => __( 'The search query for products.', 'rewardswp' ),
						'validate_callback' => function ( $param ) {
							if ( strlen( trim( $param ) ) < 3 ) {
								return new \WP_Error(
									'rest_invalid_search_term',
									__( 'The search term must be at least 3 characters long.', 'rewardswp' ),
									[ 'status' => 400 ]
								);
							}

							return true;
						},
					],
				],
			)
		);
	}

	/**
	 * Handle GET /products.
	 *
	 * @param \WP_REST_Request $request Request object.
	 *
	 * @return \WP_Error|\WP_REST_Response
	 */
	public function get_products( \WP_REST_Request $request ) {
		$search   = $request->get_param( 'search' );
		$products = is_rewardswp_lite_plan() ? [] : $this->integration->search_products( $search );

		return new \WP_REST_Response( $products );
	}

	/**
	 * Permissions for GET /products.
	 *
	 * @param \WP_REST_Request $request Request object.
	 *
	 * @return \WP_Error|bool
	 */
	public function get_products_permissions_check( \WP_REST_Request $request ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new \WP_Error(
				'rest_forbidden',
				esc_html__( 'You do not have permission to access this endpoint.', 'rewardswp' ),
				[ 'status' => 403 ]
			);
		}

		return true;
	}
}
