<?php
/**
 * Per-role login destinations — packed only in the Pro add-on overlay.
 *
 * Secure design (rafter-secure-design / auth):
 * - Identity: WordPress users after core (or Woo) already authenticated them.
 *   No new auth primitive, session, or credential.
 * - AuthZ: Destinations are keyed by WP_User->roles (RBAC). Lite cannot run
 *   this file; Freemium::unlocked requires the Pro overlay plus a valid license.
 * - Open redirect: URLs still pass Module::sanitizeRedirectDestinationUrl()
 *   (same-site wp_validate_redirect; login-page URLs rejected).
 *
 * @package RedirectAfterLogin
 */

namespace RedirectAfterLogin;

use WP_User;

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

/**
 * Resolve the first matching per-role redirect URL.
 */
final class PremiumRoleRedirects {

	/** @var array<int, string>|null */
	private static ?array $canonical_ordered_roles_once = null;

	/**
	 * @param array<string, mixed> $settings Normalized module settings.
	 */
	public static function pickUrl( WP_User $user, array $settings ): string {
		if ( ! function_exists( 'wp_powersuite_freemium_unlocked' ) || ! wp_powersuite_freemium_unlocked( 'redirect-after-login' ) ) {
			return '';
		}

		if ( empty( $settings['enable_role_redirects'] ) ) {
			return '';
		}

		$role_redirects = $settings['role_redirects'] ?? [];
		if ( ! is_array( $role_redirects ) || $role_redirects === [] || empty( $user->roles ) ) {
			return '';
		}

		foreach ( self::orderedRoleKeys( array_keys( $role_redirects ) ) as $role ) {
			if ( ! isset( $role_redirects[ $role ] ) ) {
				continue;
			}
			if ( ! in_array( $role, (array) $user->roles, true ) ) {
				continue;
			}
			$url = trim( (string) $role_redirects[ $role ] );
			if ( $url !== '' ) {
				return $url;
			}
		}

		return '';
	}

	/**
	 * @param array<int, string> $roles_with_rules Role keys that have a configured URL.
	 * @return array<int, string>
	 */
	private static function orderedRoleKeys( array $roles_with_rules ): array {
		if ( self::$canonical_ordered_roles_once === null ) {
			if ( ! function_exists( 'wp_roles' ) ) {
				require_once ABSPATH . 'wp-admin/includes/user.php';
			}

			$all = array_keys( wp_roles()->roles );
			sort( $all, SORT_STRING );

			$core_priority = [ 'administrator', 'editor', 'author', 'contributor', 'subscriber' ];
			$ordered       = array_values( array_intersect( $core_priority, $all ) );
			$rest          = array_diff( $all, $ordered );
			sort( $rest, SORT_STRING );

			self::$canonical_ordered_roles_once = array_merge( $ordered, $rest );
		}

		$canonical_order = self::$canonical_ordered_roles_once;

		$with_rules = array_intersect( $canonical_order, $roles_with_rules );
		$extras     = array_diff( $roles_with_rules, $with_rules );
		sort( $extras, SORT_STRING );

		return array_merge( array_values( $with_rules ), $extras );
	}
}
