<?php

defined( 'ABSPATH' ) || exit;


// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- Block render: core-injected $attributes, $content, and $block in this scope.
/**
 * Renders the player display name for profile routes.
 *
 * @package clanbite
 *
 * @var array    $attributes Block attributes.
 * @var WP_Block $block      Block instance.
 */

$user_id = function_exists( 'clanbite_player_blocks_resolve_subject_user_id' )
	? (int) clanbite_player_blocks_resolve_subject_user_id( $block )
	: 0;

if ( $user_id < 1 ) {
	$wrapper = get_block_wrapper_attributes(
		array(
			'class' => 'clanbite-player-display-name clanbite-player-display-name--placeholder',
		),
		$block
	);
	echo wp_kses( '<div ' . $wrapper . '><p class="clanbite-player-display-name__text">' . esc_html__( 'Player name', 'clanbite' ) . '</p></div>', clanbite_block_fragment_allowed_html());
	return;
}

$title = function_exists( 'clanbite_players_get_display_name' )
	? (string) clanbite_players_get_display_name( $user_id )
	: '';

if ( '' === $title ) {
	$u = get_userdata( $user_id );
	$title = ( $u instanceof WP_User ) ? $u->display_name : __( 'Player', 'clanbite' );
}

$align = '';
if ( isset( $attributes['style']['typography']['textAlign'] ) ) {
	$align = sanitize_key( (string) $attributes['style']['typography']['textAlign'] );
} elseif ( isset( $attributes['textAlign'] ) ) {
	$align = sanitize_key( (string) $attributes['textAlign'] );
}
$class = array( 'clanbite-player-display-name__text' );
if ( $align && in_array( $align, array( 'left', 'center', 'right', 'justify' ), true ) ) {
	$class[] = 'has-text-align-' . $align;
}

$inner = esc_html( $title );

if ( ! empty( $attributes['isLink'] ) && function_exists( 'clanbite_block_player_profile_url' ) ) {
	$href = clanbite_block_entity_link_url(
		clanbite_block_player_profile_url( $user_id ),
		'clanbite/player-display-name',
		$user_id,
		$block
	);
	if ( '' !== $href ) {
		$target = ( isset( $attributes['linkTarget'] ) && '_blank' === $attributes['linkTarget'] ) ? ' target="_blank"' : '';
		$rel    = function_exists( 'clanbite_block_entity_link_rel' ) ? clanbite_block_entity_link_rel( $attributes ) : '';
		$rel_at = '' !== $rel ? ' rel="' . esc_attr( $rel ) . '"' : '';
		$inner  = '<a class="clanbite-player-display-name__link" href="' . esc_url( $href ) . '"' . $target . $rel_at . '>' . $inner . '</a>';
	}
}

$wrapper_attributes = get_block_wrapper_attributes( array(), $block );

echo wp_kses(
	sprintf(
		'<div %1$s><p class="%2$s">%3$s</p></div>',
		$wrapper_attributes,
		esc_attr( implode( ' ', $class ) ),
		$inner
	), clanbite_block_fragment_allowed_html()
);
