<?php
/**
 * Clear-cache REST controller — POST /blocksify/v1/clear-cache.
 *
 * Phase 1 scaffolds the surface; concrete cache flushing lives in the CSS
 * pipeline (Phase 1 of CSS file-mode work). For now: flush WP object cache
 * + fire the `blocksify_dashboard_clear_cache` action so Pro / future
 * cleanup callbacks can hook in without a follow-up release breaking the
 * REST contract.
 *
 * @package Blocksify
 */

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

/**
 * REST controller for the clear-cache endpoint.
 */
class Blocksify_Dashboard_Clear_Cache_Controller extends WP_REST_Controller {

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

	/**
	 * Register POST on /clear-cache.
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'create_item' ),
					'permission_callback' => array( $this, 'permission_check' ),
				),
			)
		);
	}

	/**
	 * Capability gate.
	 *
	 * @return bool
	 */
	public function permission_check() {
		return current_user_can( Blocksify_Dashboard::get_capability() );
	}

	/**
	 * POST /clear-cache handler. Flushes WP object cache as the baseline,
	 * then fires the action so cache-owning subsystems (CSS file-mode pool,
	 * Pro plugins) can clear their own state. `cleared` is filterable so
	 * extensions report a meaningful count back to the client.
	 *
	 * @param WP_REST_Request $request Unused.
	 * @return WP_REST_Response
	 */
	public function create_item( $request ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
		wp_cache_flush();

		/**
		 * Fires when the dashboard's Clear Cache button is pressed. Hook
		 * here to invalidate per-feature caches. SPEC §11.2 (informally —
		 * canonicalized as Pro / pipeline work lands).
		 */
		do_action( 'blocksify_dashboard_clear_cache' );

		/**
		 * Coarse count of cleared entries for the success notice. Pipeline
		 * / Pro extensions sum their cleared counts here.
		 *
		 * @param int $count Default 0 (no Free-side concrete cache yet).
		 */
		$cleared = (int) apply_filters( 'blocksify_dashboard_clear_cache_count', 0 );

		return rest_ensure_response(
			array(
				'cleared' => $cleared,
				'message' => __( 'Cache cleared.', 'blocksify' ),
			)
		);
	}
}
