<?php
/**
 * Clear Cache Action
 *
 * Handles the admin-post action that bumps the global transient version,
 * invalidating all AmbassadorHub versioned transients at once.
 *
 * @package AmbassadorHub\Admin\Setup
 */

namespace AmbassadorHub\Admin\Setup;

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

use AmbassadorHub\Cache\GlobalTransient;

use function add_action;
use function check_admin_referer;
use function current_user_can;
use function wp_die;
use function wp_safe_redirect;
use function add_query_arg;
use function admin_url;

/**
 * Registers and handles the "Clear all caches" admin-post action.
 */
final class ClearCacheAction {

	/**
	 * Register the admin-post hook.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'admin_post_ambh_clear_cache', array( self::class, 'handle' ) );
	}

	/**
	 * Handle the form submission.
	 *
	 * @return void
	 */
	public static function handle(): void {
		check_admin_referer( 'ambh_clear_cache', 'ambh_clear_cache_nonce' );

		if ( ! current_user_can( 'ambh_manage_hub' ) ) {
			wp_die( 'Insufficient permissions.' );
		}

		GlobalTransient::bump_version();

		wp_safe_redirect(
			add_query_arg(
				array( 'ambh_cache_cleared' => '1' ),
				admin_url( 'admin.php?page=ambassadorhub-settings&tab=tools' )
			)
		);
		exit;
	}
}
