<?php
/**
 * Session manager capability checks.
 *
 * @package LoginSessionManager
 */

namespace LoginSessionManager\Includes;

use WP_User;

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

class Session_Capabilities {

	/**
	 * @param array<string, mixed> $settings
	 */
	public static function is_manager_active( array $settings ): bool {
		return ! empty( $settings['manager_enabled'] );
	}

	public static function can_view_user_sessions( int $actor_id, int $target_user_id ): bool {
		if ( $actor_id < 1 || $target_user_id < 1 ) {
			return false;
		}

		if ( $actor_id === $target_user_id ) {
			return true;
		}

		if ( ! user_can( $actor_id, 'edit_users' ) ) {
			return false;
		}

		return self::can_manage_target( $actor_id, $target_user_id );
	}

	public static function can_revoke_user_sessions( int $actor_id, int $target_user_id ): bool {
		return self::can_view_user_sessions( $actor_id, $target_user_id );
	}

	public static function can_destroy_all_site_wide( int $actor_id ): bool {
		if ( is_multisite() ) {
			return is_super_admin( $actor_id );
		}

		return user_can( $actor_id, 'manage_options' );
	}

	public static function can_manage_target( int $actor_id, int $target_user_id ): bool {
		$target = get_userdata( $target_user_id );
		if ( ! $target instanceof WP_User ) {
			return false;
		}

		if ( is_super_admin( $target->ID ) && ! is_super_admin( $actor_id ) ) {
			return false;
		}

		if ( user_can( $target, 'manage_options' ) && ! user_can( $actor_id, 'manage_options' ) ) {
			return false;
		}

		if ( user_can( $target, 'edit_users' ) && ! user_can( $actor_id, 'edit_users' ) ) {
			return false;
		}

		$target_level = self::get_user_level( $target );
		$actor_level  = self::get_user_level( get_userdata( $actor_id ) );

		return $actor_level >= $target_level;
	}

	private static function get_user_level( $user ): int {
		if ( ! $user instanceof WP_User ) {
			return 0;
		}

		if ( is_super_admin( $user->ID ) ) {
			return 100;
		}

		if ( user_can( $user, 'manage_options' ) ) {
			return 90;
		}

		if ( user_can( $user, 'edit_users' ) ) {
			return 80;
		}

		if ( user_can( $user, 'publish_posts' ) ) {
			return 50;
		}

		if ( user_can( $user, 'edit_posts' ) ) {
			return 40;
		}

		return 10;
	}
}
