<?php
/**
 * User Custom Field Block Template
 *
 * @since 4.2.0
 *
 * @var WP_User $user User object
 * @var array $attributes Block attributes
 * @var string $content Block content
 * @var WP_Block $block Block instance
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! $user ) {
    return;
}

$meta_field_key = ! empty( $attributes['metaFieldKey'] ) ? $attributes['metaFieldKey'] : '';
$field_label = ! empty( $attributes['fieldLabel'] ) ? $attributes['fieldLabel'] : '';
$field_type = ! empty( $attributes['fieldType'] ) ? $attributes['fieldType'] : 'text';
$show_label = isset( $attributes['showLabel'] ) ? $attributes['showLabel'] : true;
$empty_value = ! empty( $attributes['emptyValue'] ) ? $attributes['emptyValue'] : '';
$prefix_text = ! empty( $attributes['prefixText'] ) ? $attributes['prefixText'] : '';
$suffix_text = ! empty( $attributes['suffixText'] ) ? $attributes['suffixText'] : '';

// Don't show anything if no field key
if ( empty( $meta_field_key ) ) {
    return;
}

// Get the custom field value
$field_value = get_user_meta( $user->ID, $meta_field_key, true );

// Use empty value if no field value
if ( empty( $field_value ) ) {
    $field_value = $empty_value;
}

// Don't show anything if still no value
if ( empty( $field_value ) ) {
    return;
}

// Use field key as label if no label provided
if ( empty( $field_label ) ) {
    $field_label = ucwords( str_replace( [ '_', '-' ], ' ', $meta_field_key ) );
}

// Get block wrapper attributes (includes styling from block editor)
$wrapper_attributes = wpuf_get_block_wrapper_attributes( $attributes, 'user-custom-field', [
    'class' => 'wpuf-custom-field wpuf-field-' . esc_attr( $field_type ),
    'data-user-id' => $user->ID,
    'data-field-key' => $meta_field_key,
] );



?>
<div <?php echo $wrapper_attributes; ?>>
    <?php if ( $show_label && $field_label ) : ?>
    <div class="wpuf-field-label-container">
        <strong class="wpuf-field-label"><?php echo esc_html( $field_label ); ?>:</strong>
    </div>
    <?php endif; ?>

    <div class="wpuf-field-content">
        <?php echo esc_html( $prefix_text ); ?>
        <?php if ( 'email' === $field_type && is_email( $field_value ) ) : ?>
            <a href="mailto:<?php echo esc_attr( $field_value ); ?>"><?php echo esc_html( $field_value ); ?></a>
        <?php elseif ( 'url' === $field_type && filter_var( $field_value, FILTER_VALIDATE_URL ) ) : ?>
            <a href="<?php echo esc_url( $field_value ); ?>" target="_blank" rel="noopener noreferrer">
                <?php echo esc_html( $field_value ); ?>
            </a>
        <?php else : ?>
            <span class="wpuf-field-value"><?php echo esc_html( $field_value ); ?></span>
        <?php endif; ?>
        <?php echo esc_html( $suffix_text ); ?>
    </div>
</div>
