<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Get dynamic text/title for Sifency widgets
 *
 * @param array $settings Elementor widget settings
 * @param array $args Optional arguments
 * @return string
 */
function sifency_addons_get_dynamic_text( $settings = array(), $args = array() ) {

	$defaults = array(
		'type'           => 'title',
		'excerpt_length' => 20,
		'post_id'        => get_the_ID(),
	);

	$args   = wp_parse_args( $args, $defaults );
	$source = $settings['title_source'] ?? 'post_title';
	$text   = '';

	switch ( $source ) {

		case 'post_title':
			if ( is_front_page() ) {
				$text = esc_html__( 'Home', 'sifency-addons' );
			} elseif ( is_home() ) {
				$text = get_the_title( get_option( 'page_for_posts' ) );
			} else {
				$text = get_the_title( $args['post_id'] );
			}
			break;

		case 'the_excerpt':
			$excerpt = get_post_field( 'post_excerpt', $args['post_id'] );

			if ( empty( $excerpt ) && $args['type'] === 'text' ) {
				$excerpt = get_the_excerpt( $args['post_id'] );
			}

			if ( ! empty( $excerpt ) ) {
				$text = wp_trim_words( $excerpt, (int) $args['excerpt_length'], '...' );
			}
			break;

		case 'the_content':
			$content = get_post_field( 'post_content', $args['post_id'] );
			$content = apply_filters( 'the_content', $content );
			$text    = wp_trim_words( wp_strip_all_tags( $content ), (int) $args['excerpt_length'], '...' );
			break;

		case 'archive':
			$text = get_the_archive_title();
			break;

		case 'site_title':
			$text = get_bloginfo( 'name' );
			break;

		case 'site_tagline':
			$text = get_bloginfo( 'description' );
			break;

		case 'acf_field':
			if ( function_exists( 'get_field' ) && ! empty( $settings['acf_field_name'] ) ) {
				$text = get_field( $settings['acf_field_name'], $args['post_id'] );
			}
			break;

		case 'custom':
		default:
			$text = $settings['heading_text'] ?? '';
			break;
	}

	return $text;
}
