<?php
/**
 * Rollback REST controller — GET /blocksify/v1/version/rollback.
 *
 * Read-only: hands the Version-control panel the data it needs to render the
 * rollback UI — the running version, the list of older wp.org releases that
 * can be rolled back to, and a nonce'd admin-post URL to perform the rollback.
 *
 * The rollback itself is NOT a REST action: it runs as a full-page
 * `admin-post` request (see Blocksify_Rollback) so WordPress core can render
 * its upgrader progress screen and the WP_Filesystem credentials form. The
 * React panel just navigates the browser to `action_url + &version={tag}`.
 *
 * @package Blocksify
 */

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

/**
 * REST controller for the rollback version list.
 */
class Blocksify_Dashboard_Rollback_Controller extends WP_REST_Controller {

	/**
	 * Wire namespace + base for register_routes().
	 */
	public function __construct() {
		$this->namespace = 'blocksify/v1';
		$this->rest_base = 'version/rollback';
	}

	/**
	 * Register GET on /version/rollback.
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_item' ),
					'permission_callback' => array( $this, 'permission_check' ),
				),
			)
		);
	}

	/**
	 * Capability gate. Reuses the dashboard capability for consistency with
	 * the other controllers; the actual rollback admin-post handler enforces
	 * the stricter `update_plugins` capability + a nonce before touching any
	 * files.
	 *
	 * @return bool
	 */
	public function permission_check() {
		return current_user_can( Blocksify_Dashboard::get_capability() );
	}

	/**
	 * GET /version/rollback handler.
	 *
	 * @param WP_REST_Request $request Unused.
	 * @return WP_REST_Response
	 */
	public function get_item( $request ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
		return rest_ensure_response(
			array(
				'current_version' => defined( 'BLOCKSIFY_VERSION' ) ? BLOCKSIFY_VERSION : '',
				'versions'        => Blocksify_Rollback::get_versions(),
				'action_url'      => Blocksify_Rollback::action_url(),
				'can_rollback'    => current_user_can( Blocksify_Rollback::capability() ),
			)
		);
	}
}
