<?php

use Elementor\Core\DynamicTags\Tag;
use Elementor\Modules\DynamicTags\Module;
use Elementor\Controls_Manager;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Plus Addons Dynamic Tag - ACF Field
 *
 * Provides a dynamic tag for Elementor to output an ACF field value.
 *
 * @since 6.4.5
 */
class ThePlus_Dynamic_Tag_ACF_Text extends Tag {

    /**
     * Unique dynamic tag name used internally by Elementor.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_name(): string {
		return 'plus-tag-acf-text';
	}

    /**
     * Label shown in Elementor Dynamic Tags list.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_title(): string {
		return esc_html__( 'ACF Field', 'theplus' );
	}

    /**
     * Registers the group under which this tag will appear.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_group(): array {
		return [ 'plus-opt-acf' ];
	}

    /**
     * Defines the category type (Text) for this dynamic tag.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_categories(): array {
		return [
			Module::TEXT_CATEGORY,
		];
	}

    /**
     * Indicates that settings panel should be shown (even if empty).
     *
     * @since 6.4.5
     * @return bool
     */
	public function is_settings_required(): bool {
		return true;
	}

    /**
     * Register controls for this dynamic tag.
     *
     * @since 6.4.5
     * @return void
     */
	protected function register_controls(): void {

		$this->add_control(
			'acf_source',
			[
				'label'   => esc_html__( 'Source', 'theplus' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'post',
				'options' => [
					'post'   => esc_html__( 'Post', 'theplus' ),
					'author' => esc_html__( 'Post Author', 'theplus' ),
				],
			]
		);

		// Existing Field Selector
		$this->add_control(
			'acf_field_key',
			[
				'label'  => esc_html__( 'Key', 'theplus' ),
				'type'   => Controls_Manager::SELECT,
				'groups' => $this->get_acf_field_groups(),
				'description' => wp_kses_post(
					sprintf(
						'<p class="tp-controller-label-text"><i>%s</i></p>',
						esc_html__( 'Select the ACF field you want to display.', 'theplus' )
					),
				),
			]
		);
	}

    /**
     * Get ACF field groups and their text-safe fields.
     *
     * @since 6.4.5
     * @return void
     */
	protected function get_acf_field_groups(): array {

		if ( ! function_exists( 'acf_get_field_groups' ) ) {
			return [];
		}

		$groups = [];
		$field_groups = acf_get_field_groups();

		$text_supported_types = [
			'text',
			'textarea',
			'number',
			'email',
			'url',
			'password',
			'wysiwyg',
			'select',
			'checkbox',
			'radio',
			'true_false',
			'date_picker',
			'date_time_picker',
			'time_picker',
			'color_picker',
		];

		foreach ( $field_groups as $acf_group ) {

			if ( empty( $acf_group['key'] ) || empty( $acf_group['title'] ) ) {
				continue;
			}

			$fields = acf_get_fields( $acf_group['key'] );

			if ( empty( $fields ) || ! is_array( $fields ) ) {
				continue;
			}

			$options = [];

			foreach ( $fields as $field ) {

				if (
					empty( $field['name'] ) ||
					empty( $field['label'] ) ||
					empty( $field['type'] )
				) {
					continue;
				}

				if ( ! in_array( $field['type'], $text_supported_types, true ) ) {
					continue;
				}

				$options[ $field['name'] ] = $field['label'];
			}

			if ( ! empty( $options ) ) {
				$groups[] = [
					'label'   => esc_html( $acf_group['title'] ),
					'options' => $options,
				];
			}
		}

		return $groups;
	}

    /**
     * Render the dynamic selected ACF field on frontend.
     *
     * Gets the current selected ACF field and prints its value.
     *
     * @since 6.4.5
     * @return void
     */
	public function render(): void {

		$settings   = $this->get_settings_for_display();
		$field_name = $settings['acf_field_key'] ?? '';
		$source     = $settings['acf_source'] ?? 'post';

		if ( empty( $field_name ) || ! function_exists( 'get_field' ) ) {
			return;
		}

		$value = '';

		if ( $source === 'author' ) {

			// Resolve author across author archive, singular post, and fallback to current user.
			$author_id = 0;

			if ( is_author() ) {
				$author_id = (int) get_queried_object_id();
			} elseif ( is_singular() ) {
				$post_id = get_the_ID();
				if ( $post_id ) {
					$author_id = (int) get_post_field( 'post_author', $post_id );
				}
			}

			if ( ! $author_id ) {
				$author_id = get_current_user_id();
			}

			if ( $author_id ) {
				$value = get_field( $field_name, 'user_' . $author_id );
			}
		} else {

			if ( is_tax() || is_category() || is_tag() ) {
				$value = get_field( $field_name, get_queried_object() );
			} else {
				$value = get_field( $field_name, get_the_ID() );
			}
		}

		if ( empty( $value ) ) {
			return;
		}

		// Handle array values (checkbox, select, etc.)
		if ( is_array( $value ) ) {
			$value = implode( ', ', array_map( 'wp_kses_post', $value ) );
		} elseif ( is_object( $value ) ) {
			return; 
		}

		echo wp_kses_post( (string) $value );
	}
}
