<?php
/**
 * Dynamic content resolver for the Bodycopy block.
 *
 * Returns content markup plus the resolved link hrefs so that render.php
 * can wrap the outer element in <a> from OUTSIDE (same pattern as Heading).
 * No <a> tags are ever inserted into the content markup itself.
 *
 * @package AxcelersBlocks
 */

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

if ( ! function_exists( 'axcelersblocks_bodycopy_resolve_dynamic' ) ) {
	/**
	 * Resolve dynamic content for the Bodycopy block.
	 *
	 * @param array $attributes Full block attributes.
	 * @return array{
	 *   markup:      string,
	 *   link_href:   string,
	 *   author_href: string,
	 *   term_href:   string,
	 * }
	 */
	function axcelersblocks_bodycopy_resolve_dynamic( array $attributes ): array {
		$source_entity = $attributes['sourceEntity']   ?? 'post';
		$source_type   = $attributes['sourceType']     ?? 'current';
		$selected_tag  = $attributes['selectedTag']    ?? 'post_excerpt';
		$taxonomy      = isset( $attributes['taxonomy'] )      ? sanitize_key( $attributes['taxonomy'] )             : 'category';
		$term_id       = isset( $attributes['termId'] )        ? intval( $attributes['termId'] )                     : 0;
		$post_id_attr  = isset( $attributes['postId'] )        ? intval( $attributes['postId'] )                     : 0;
		$date_format   = $attributes['dateFormat']     ?? '';
		$excerpt_len   = isset( $attributes['excerptLength'] ) ? intval( $attributes['excerptLength'] )              : 55;
		$meta_key      = isset( $attributes['metaKey'] )       ? sanitize_key( $attributes['metaKey'] )              : '';
		$term_sep      = isset( $attributes['termSeparator'] ) ? sanitize_text_field( $attributes['termSeparator'] ) : ', ';
		$acf_field     = isset( $attributes['acfField'] )      ? sanitize_text_field( $attributes['acfField'] )      : '';
		$acf_scope     = $attributes['acfScope']       ?? 'entity';
		$required      = array_key_exists( 'required', $attributes ) ? (bool) $attributes['required'] : true;
		$fallback_text = $attributes['fallbackText']   ?? '';

		$empty = [ 'markup' => '', 'link_href' => '', 'author_href' => '', 'term_href' => '' ];

		// Returns plain text with fallback.
		$resolve = function ( $val ) use ( $required, $fallback_text ): string {
			if ( ( '' !== $val && null !== $val ) || 0 === $val || '0' === $val ) {
				return (string) $val;
			}
			return $required ? ( $fallback_text !== '' ? $fallback_text : '—' ) : '';
		};

		// Returns safe HTML with fallback (for content that may contain markup).
		$resolve_markup = function ( $html ) use ( $required, $fallback_text ): string {
			$trim = trim( (string) wp_strip_all_tags( $html ) );
			if ( $trim !== '' ) {
				return wp_kses_post( $html );
			}
			return $required ? esc_html( $fallback_text !== '' ? $fallback_text : '—' ) : '';
		};

		// ─── Term entity ─────────────────────────────────────────────────────

		if ( $source_entity === 'term' ) {
			$term = ( $term_id && $taxonomy ) ? get_term( $term_id, $taxonomy ) : null;

			if ( ! $term || is_wp_error( $term ) ) {
				return array_merge( $empty, [ 'markup' => $required ? esc_html__( '(Term not found)', 'axcelersblocks' ) : '' ] );
			}

			$term_href = get_term_link( $term );
			$markup    = '';

			switch ( $selected_tag ) {
				case 'term_name':
					$markup = esc_html( $resolve( $term->name ) );
					break;

				case 'term_description':
					$markup = $resolve_markup( $term->description );
					break;

				case 'term_meta':
					$val = $meta_key ? get_term_meta( $term->term_id, $meta_key, true ) : '';
					if ( is_array( $val ) || is_object( $val ) ) { $val = wp_json_encode( $val ); }
					$markup = esc_html( $resolve( (string) $val ) );
					break;

				case 'acf_field':
					$val = '';
					if ( function_exists( 'get_field' ) && $acf_field ) {
						$val = $acf_scope === 'options'
							? get_field( $acf_field, 'option' )
							: get_field( $acf_field, 'term_' . $term->term_id );
					}
					if ( is_array( $val ) || is_object( $val ) ) { $val = wp_json_encode( $val ); }
					$markup = is_string( $val ) && preg_match( '/<[^>]+>/', $val )
						? $resolve_markup( $val )
						: esc_html( $resolve( (string) $val ) );
					break;

				default:
					$markup = esc_html( $resolve( '' ) );
			}

			return [
				'markup'      => $markup,
				'link_href'   => '',
				'author_href' => '',
				'term_href'   => is_wp_error( $term_href ) ? '' : (string) $term_href,
			];
		}

		// ─── Post entity ─────────────────────────────────────────────────────

		$post_id  = ( $source_type === 'specific' && $post_id_attr ) ? $post_id_attr : get_the_ID();
		$post_obj = $post_id ? get_post( $post_id ) : null;

		if ( ! $post_obj ) {
			return array_merge( $empty, [ 'markup' => $required ? esc_html__( '(Post not found)', 'axcelersblocks' ) : '' ] );
		}

		$link_href   = (string) get_permalink( $post_id );
		$author_href = '';
		$markup      = '';

		switch ( $selected_tag ) {
			case 'post_title':
				$markup = esc_html( $resolve( get_the_title( $post_id ) ) );
				break;

			case 'post_excerpt':
				$excerpt = get_the_excerpt( $post_id );
				if ( $excerpt !== '' ) {
					$markup = $resolve_markup( $excerpt );
				} else {
					$raw    = get_post_field( 'post_content', $post_id );
					$markup = $resolve_markup( wp_trim_words( wp_strip_all_tags( $raw ), $excerpt_len ?: 55, '…' ) );
				}
				break;

			case 'post_date':
				$format = $date_format !== '' ? $date_format : get_option( 'date_format' );
				$markup = esc_html( $resolve( get_the_date( $format, $post_id ) ) );
				break;

			case 'post_permalink':
				$markup = esc_html( $resolve( $link_href ) );
				break;

			case 'post_meta':
				$val = $meta_key ? get_post_meta( $post_id, $meta_key, true ) : '';
				if ( is_array( $val ) || is_object( $val ) ) { $val = wp_json_encode( $val ); }
				$markup = esc_html( $resolve( (string) $val ) );
				break;

			case 'comments_count':
				$markup = esc_html( $resolve( (string) get_comments_number( $post_id ) ) );
				break;

			case 'comments_url':
				$markup = esc_html( $resolve( trailingslashit( $link_href ) . '#comments' ) );
				break;

			case 'term_list':
				$terms = get_the_terms( $post_id, $taxonomy );
				if ( is_array( $terms ) && ! is_wp_error( $terms ) && $terms ) {
					$markup = esc_html( $resolve( implode( $term_sep, array_column( $terms, 'name' ) ) ) );
				} else {
					$markup = esc_html( $resolve( '' ) );
				}
				break;

			case 'post_author':
				$author = get_userdata( $post_obj->post_author );
				if ( $author ) {
					$markup      = esc_html( $resolve( $author->display_name ) );
					$author_href = (string) get_author_posts_url( $post_obj->post_author );
				} else {
					$markup = $required ? esc_html__( '(Author not found)', 'axcelersblocks' ) : '';
				}
				break;

			case 'acf_field':
				$val = '';
				if ( function_exists( 'get_field' ) && $acf_field ) {
					$val = $acf_scope === 'options'
						? get_field( $acf_field, 'option' )
						: get_field( $acf_field, $post_id );
				}
				if ( is_array( $val ) || is_object( $val ) ) { $val = wp_json_encode( $val ); }
				$markup = is_string( $val ) && preg_match( '/<[^>]+>/', $val )
					? $resolve_markup( $val )
					: esc_html( $resolve( (string) $val ) );
				break;

			default:
				$markup = esc_html( $resolve( '' ) );
		}

		return [
			'markup'      => $markup,
			'link_href'   => $link_href,
			'author_href' => $author_href,
			'term_href'   => '',
		];
	}
}
