<?php
/**
 * Pro: role + logged-in state rule gating.
 *
 * @package EasySearchReplace
 */

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

/**
 * Gate rules by logged-in state and / or user role.
 *
 * Interpretation:
 *  - logged_in = 'any'  -> no gate on login state.
 *  - logged_in = 'in'   -> visitor must be logged in.
 *  - logged_in = 'out'  -> visitor must be a guest.
 *  - roles = []         -> no role restriction.
 *  - roles = [...]      -> visitor must have at least one of these roles.
 *
 * Roles implicitly require a logged-in user, so if roles are set and the
 * visitor is a guest the rule is blocked regardless of logged_in setting.
 */
class ESRN_Pro_Roles {

	public static function register() {
		add_filter( 'esrn_should_apply_rule', array( __CLASS__, 'check' ), 10, 3 );
	}

	/**
	 * @param bool  $apply
	 * @param array $rule
	 * @param array $context
	 * @return bool
	 */
	public static function check( $apply, $rule, $context ) {
		if ( ! $apply ) {
			return false;
		}

		$user      = isset( $context['user'] ) ? $context['user'] : null;
		$logged_in = ( $user && ! empty( $user->ID ) );

		$required_state = isset( $rule['logged_in'] ) ? (string) $rule['logged_in'] : 'any';
		if ( 'in' === $required_state && ! $logged_in ) {
			return false;
		}
		if ( 'out' === $required_state && $logged_in ) {
			return false;
		}

		$required_roles = isset( $rule['roles'] ) && is_array( $rule['roles'] ) ? $rule['roles'] : array();
		if ( empty( $required_roles ) ) {
			return true;
		}

		// Roles specified => guest can never match.
		if ( ! $logged_in ) {
			return false;
		}

		$user_roles = isset( $user->roles ) && is_array( $user->roles ) ? $user->roles : array();
		if ( empty( $user_roles ) ) {
			return false;
		}

		foreach ( $required_roles as $role ) {
			if ( in_array( $role, $user_roles, true ) ) {
				return true;
			}
		}

		return false;
	}
}
