<?php
/**
 * WordPress capabilities.
 *
 * @package LocalGuardScanner
 */

namespace LocalGuardScanner\Infrastructure\WordPress;

/**
 * Manages and checks the scanner capability.
 */
final class Capabilities {
	const MANAGE = 'manage_localguard_scanner';

	/**
	 * Install the capability.
	 *
	 * @param bool $network_wide Network activation flag.
	 * @return void
	 */
	public static function install( $network_wide = false ) {
		$role = get_role( 'administrator' );
		if ( $role && ! is_multisite() ) {
			$role->add_cap( self::MANAGE );
		}

		if ( $network_wide && is_multisite() ) {
			update_site_option( 'lgs_network_activated', 1 );
		}
	}

	/**
	 * Keep capability registration idempotent.
	 *
	 * @return void
	 */
	public static function ensure_registered() {
		if ( is_multisite() ) {
			return;
		}

		$role = get_role( 'administrator' );
		if ( $role && ! $role->has_cap( self::MANAGE ) ) {
			$role->add_cap( self::MANAGE );
		}
	}

	/**
	 * Whether the current user may manage scanner data.
	 *
	 * @return bool
	 */
	public static function current_user_can_manage() {
		if ( is_multisite() ) {
			return is_super_admin();
		}

		return current_user_can( self::MANAGE );
	}
}
