<?php
/**
 * REST controller for exposing PowerWidget data.
 *
 * @package Ilabs\Firevert\Modules\PowerWidget\Api
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\PowerWidget\Api;

use Ilabs\Firevert\Core\Api\Controller\AbstractController;
use WP_REST_Request;
use WP_REST_Response;
use Ilabs\Firevert\Modules\PowerWidget\Services\Repository\PowerWidgetRepository;

/**
 * Class RenderController
 */
final class RenderController extends AbstractController {

	/**
	 * PowerWidgetRepository instance.
	 *
	 * @var PowerWidgetRepository
	 */
	private PowerWidgetRepository $repository;

	/**
	 * Constructor.
	 *
	 * @param PowerWidgetRepository $repository The repository instance.
	 */
	public function __construct( PowerWidgetRepository $repository ) {
		$this->repository = $repository;

		parent::__construct();
	}

	/**
	 * Registers REST API routes.
	 *
	 * @return void
	 */
	public function register_routes(): void {
		add_action( 'rest_api_init', array( $this, 'on_rest_api_init' ) );
	}

	/**
	 * Registers the actual REST API route for the PowerWidget.
	 *
	 * @return void
	 */
	public function on_rest_api_init(): void {
		register_rest_route(
			'firevert/v1',
			'/power-widget/main',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_main_widget_data' ),
				'permission_callback' => $this->get_permission_callback(),
			)
		);

		register_rest_route(
			'firevert/v1',
			'/power-widget/main/products',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_main_widget_products' ),
				'permission_callback' => $this->get_permission_callback(),
			)
		);
	}

	/**
	 * Returns main PowerWidget data as JSON.
	 *
	 * @param WP_REST_Request $request Request.
	 *
	 * @return WP_REST_Response REST response with widget data.
	 */
	public function get_main_widget_data( WP_REST_Request $request ): WP_REST_Response {
		$lang = $request->get_param( 'locale' );
		$lang = is_string( $lang ) ? $lang : null;

		$post = $this->repository->get_or_create_main();
		$data = $this->repository->get_main_widget_payload( $post, $lang );

		return new WP_REST_Response( $data );
	}

	/**
	 * Returns product list for the main PowerWidget.
	 *
	 * @param WP_REST_Request $request Request.
	 *
	 * @return WP_REST_Response REST response with product data.
	 */
	public function get_main_widget_products( WP_REST_Request $request ): WP_REST_Response {
		$page = (int) $request->get_param( 'page' );

		if ( 0 >= $page ) {
			$page = 1;
		}

		$post     = $this->repository->get_or_create_main();
		$products = $this->repository->get_products_widget_payload( $post, $page );

		return new WP_REST_Response( $products );
	}
}
