<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template variables are scoped when required inside the block render callback.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

require_once dirname( __DIR__, 3 ) . '/includes/block-css-generator.php';

// ─── Tag & identity ───────────────────────────────────────────────────────────

$tag_name     = isset( $attributes['tagName'] ) ? $attributes['tagName'] : 'a';
$tag_name     = tag_escape( in_array( $tag_name, [ 'a', 'button' ], true ) ? $tag_name : 'a' );

$anchor       = isset( $attributes['anchor'] ) ? sanitize_title( $attributes['anchor'] ) : '';
$unique_class = isset( $attributes['uniqueClass'] ) ? sanitize_html_class( $attributes['uniqueClass'] ) : '';
if ( empty( $unique_class ) ) {
	$unique_class = sanitize_html_class( 'axb-' . wp_unique_id() );
}

// ─── Dynamic / link attributes ────────────────────────────────────────────────

$selected_tag  = $attributes['selectedTag']  ?? 'post_permalink';
$source_entity = $attributes['sourceEntity'] ?? 'post';
$source_type   = $attributes['sourceType']   ?? 'current';
$post_id_attr  = isset( $attributes['postId'] )   ? intval( $attributes['postId'] )   : 0;
$taxonomy      = isset( $attributes['taxonomy'] )  ? sanitize_key( $attributes['taxonomy'] )  : '';
$term_id       = isset( $attributes['termId'] )    ? intval( $attributes['termId'] )    : 0;
$link_option   = $attributes['linkOption']   ?? 'none';
$meta_key      = isset( $attributes['metaKey'] )   ? sanitize_key( $attributes['metaKey'] )   : '';
$acf_field     = isset( $attributes['acfField'] )  ? sanitize_text_field( $attributes['acfField'] ) : '';
$acf_scope     = $attributes['acfScope']     ?? 'entity';
$required      = isset( $attributes['required'] )  ? (bool) $attributes['required']  : true;
$open_in_new   = isset( $attributes['openInNewTab'] ) ? (bool) $attributes['openInNewTab'] : true;
$custom_link   = isset( $attributes['customLink'] ) ? esc_url( $attributes['customLink'] ) : '';
$icon_loc      = $attributes['iconLocation'] ?? 'before';
$link_title    = isset( $attributes['linkTitle'] ) ? sanitize_text_field( $attributes['linkTitle'] ) : '';
$aria_label    = isset( $attributes['ariaLabel'] ) ? sanitize_text_field( $attributes['ariaLabel'] ) : '';
$button_type   = isset( $attributes['buttonType'] ) ? sanitize_key( $attributes['buttonType'] ) : 'button';
$button_type   = in_array( $button_type, [ 'button', 'submit', 'reset' ], true ) ? $button_type : 'button';
$rel_tokens    = [];

if ( $open_in_new ) {
	$rel_tokens[] = 'noopener';
	$rel_tokens[] = 'noreferrer';
}
if ( ! empty( $attributes['relNoFollow'] ) ) {
	$rel_tokens[] = 'nofollow';
}
if ( ! empty( $attributes['relSponsored'] ) ) {
	$rel_tokens[] = 'sponsored';
}
if ( ! empty( $attributes['relUgc'] ) ) {
	$rel_tokens[] = 'ugc';
}
$rel_value = implode( ' ', array_unique( array_filter( $rel_tokens ) ) );

// ─── Resolve effective post ID ────────────────────────────────────────────────

$effective_post_id = 0;
if ( $source_entity === 'post' ) {
	if ( $source_type === 'specific' && $post_id_attr ) {
		$effective_post_id = $post_id_attr;
	} else {
		$effective_post_id = isset( $block->context['postId'] ) ? intval( $block->context['postId'] ) : 0;
		if ( ! $effective_post_id ) {
			$maybe = get_the_ID();
			if ( $maybe ) { $effective_post_id = intval( $maybe ); }
		}
	}
}

// ─── Resolve href ─────────────────────────────────────────────────────────────

$link = '';
if ( $custom_link ) {
	$link = $custom_link;
} else {
	// ACF as URL
	if ( $selected_tag === 'acf_field' && $acf_field && function_exists( 'get_field' ) ) {
		if ( $acf_scope === 'options' ) {
			$val  = get_field( $acf_field, 'option' );
		} elseif ( $source_entity === 'term' && $taxonomy && $term_id ) {
			$val  = get_field( $acf_field, "{$taxonomy}_{$term_id}" );
		} elseif ( $source_entity === 'post' && $effective_post_id ) {
			$val  = get_field( $acf_field, $effective_post_id );
		} else {
			$val = '';
		}
		$link = is_string( $val ) ? $val : '';
	}

	// Post meta as URL
	if ( ! $link && $selected_tag === 'post_meta' && $meta_key && $effective_post_id ) {
		$val  = get_post_meta( $effective_post_id, $meta_key, true );
		$link = is_string( $val ) ? $val : '';
	}

	// Term meta as URL
	if ( ! $link && $selected_tag === 'term_meta' && $meta_key && $taxonomy && $term_id ) {
		$val  = get_term_meta( $term_id, $meta_key, true );
		$link = is_string( $val ) ? $val : '';
	}

	// Term permalink
	if ( ! $link && ( $link_option === 'term' || ( $source_entity === 'term' && $taxonomy && $term_id ) ) ) {
		$maybe = get_term_link( $term_id, $taxonomy );
		$link  = is_wp_error( $maybe ) ? '' : $maybe;
	}

	// Author archive
	if ( ! $link && $selected_tag === 'post_author' && $effective_post_id && $link_option === 'author' ) {
		$post_obj = get_post( $effective_post_id );
		if ( $post_obj ) { $link = get_author_posts_url( $post_obj->post_author ); }
	}

	// Post permalink (explicit or fallback)
	if ( ! $link && $effective_post_id && ( $selected_tag === 'post_permalink' || $link_option === 'post' || $selected_tag === 'post_author' ) ) {
		$link = get_permalink( $effective_post_id );
	}
}

// Bail early if <a> is required but has no href
if ( $tag_name === 'a' && $required && empty( $link ) ) {
	return '';
}

// ─── Wrapper attributes ───────────────────────────────────────────────────────

$extra_attrs = [ 'class' => trim( 'axcelersblocks-button__text ' . $unique_class ) ];
if ( $anchor ) {
	$extra_attrs['id'] = $anchor;
}
if ( $tag_name === 'a' ) {
	$link = is_string( $link ) ? esc_url( $link ) : '';
	if ( $required && empty( $link ) ) { return ''; }
	if ( $link ) {
		$extra_attrs['href']      = $link;
		$extra_attrs['data-href'] = $link;
		if ( $open_in_new ) {
			$extra_attrs['target'] = '_blank';
		}
		if ( $rel_value ) {
			$extra_attrs['rel'] = $rel_value;
		}
		if ( $link_title ) {
			$extra_attrs['title'] = $link_title;
		}
		if ( $aria_label ) {
			$extra_attrs['aria-label'] = $aria_label;
		}
	}
} elseif ( $tag_name === 'button' ) {
	$extra_attrs['type'] = $button_type;
	if ( $link_title ) {
		$extra_attrs['title'] = $link_title;
	}
	if ( $aria_label ) {
		$extra_attrs['aria-label'] = $aria_label;
	}
}
$wrapper_attrs = get_block_wrapper_attributes( $extra_attrs );

// ─── CSS generation & collection ──────────────────────────────────────────────

$devices    = axcelersblocks_get_responsive_devices();
$styles_css = axcelersblocks_generate_block_styles( $unique_class, $devices, $attributes );
$hover_css  = axcelersblocks_generate_block_styles_hover( $unique_class, $devices, $attributes );
$focus_css  = axcelersblocks_generate_block_styles_focus( $unique_class, $devices, $attributes );
$active_css = axcelersblocks_generate_block_styles_active( $unique_class, $devices, $attributes );
axcelersblocks_collect_block_styles( $unique_class, $block, array_merge( $styles_css, $hover_css, $focus_css, $active_css ) );

// ─── Icon ─────────────────────────────────────────────────────────────────────

$icon_html = '';
if ( ! empty( $attributes['iconSvg'] ) && is_string( $attributes['iconSvg'] ) && strpos( $attributes['iconSvg'], '<svg' ) !== false ) {
	$icon_svg  = wp_kses( $attributes['iconSvg'], axcelersblocks_get_allowed_svg_html() );
	$icon_html = $icon_svg ? '<span class="icon">' . $icon_svg . '</span>' : '';
}

// ─── Content assembly ─────────────────────────────────────────────────────────

$content   = ! empty( $attributes['content'] ) ? wp_kses_post( $attributes['content'] ) : '';
$text_html = '<span class="button-text">' . $content . '</span>';

$inner = ( $icon_html && $icon_loc === 'before' )
	? $icon_html . $text_html
	: ( ( $icon_html && $icon_loc === 'after' )
		? $text_html . $icon_html
		: $text_html );

// ─── Output ───────────────────────────────────────────────────────────────────

printf(
	'<%1$s %2$s>%3$s</%1$s>',
	esc_attr( $tag_name ),
	$wrapper_attrs, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- get_block_wrapper_attributes() returns escaped output.
	wp_kses( $inner, axcelersblocks_get_allowed_svg_html() )
);
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
