<?php
/**
 * Dynamic content resolver for the Heading block.
 *
 * @package AxcelersBlocks
 */

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

if ( ! function_exists( 'axcelersblocks_heading_resolve_dynamic' ) ) {
	/**
	 * Resolve dynamic content for the Heading block.
	 *
	 * @param array $attributes Full block attributes.
	 * @return array{ text: string, link_href: string, author_href: string, term_href: string }
	 */
	function axcelersblocks_heading_resolve_dynamic( array $attributes ): array {
		$source_entity = $attributes['sourceEntity']   ?? 'post';
		$source_type   = $attributes['sourceType']     ?? 'current';
		$selected_tag  = $attributes['selectedTag']    ?? 'post_title';
		$link_option   = $attributes['linkOption']     ?? 'none';
		$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']   ?? '';

		$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 : '—' ) : '';
		};

		$text        = '';
		$link_href   = '';
		$author_href = '';
		$term_href   = '';

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

			if ( $term && ! is_wp_error( $term ) ) {
				$term_href = get_term_link( $term );

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

					case 'term_description':
						$text = $resolve( wp_strip_all_tags( $term->description ) );
						break;

					case 'term_meta':
						$val = $meta_key ? get_term_meta( $term->term_id, $meta_key, true ) : '';
						if ( is_array( $val ) )  { $val = implode( ', ', array_map( 'strval', $val ) ); }
						if ( is_object( $val ) ) { $val = wp_json_encode( $val ); }
						$text = $resolve( $val );
						break;

					case 'acf_field':
						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 ); }
							$text = $resolve( $val );
						} else {
							$text = $resolve( '' );
						}
						break;

					default:
						$text = $resolve( '' );
				}

				$text = esc_html( $text );

			} else {
				$text = $required ? esc_html__( '(Term not found)', 'axcelersblocks' ) : '';
			}

		} else {
			// 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 ) {
				$link_href = get_permalink( $post_id );

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

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

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

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

					case 'post_meta':
						$val = $meta_key ? get_post_meta( $post_id, $meta_key, true ) : '';
						if ( is_array( $val ) )  { $val = implode( ', ', array_map( 'strval', $val ) ); }
						if ( is_object( $val ) ) { $val = wp_json_encode( $val ); }
						$text = $resolve( $val );
						break;

					case 'comments_count':
						$text = $resolve( get_comments_number( $post_id ) );
						break;

					case 'comments_url':
						$text = $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 ) {
							$text = $resolve( implode( $term_sep, array_column( $terms, 'name' ) ) );
						} else {
							$text = $resolve( '' );
						}
						break;

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

					case 'acf_field':
						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 ); }
							$text = $resolve( $val );
						} else {
							$text = $resolve( '' );
						}
						break;

					default:
						$text = $resolve( '' );
				}

				if ( $text !== '' ) {
					$text = esc_html( $text );
				}

			} else {
				$text = $required ? esc_html__( '(Post not found)', 'axcelersblocks' ) : '';
			}
		}

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