<?php

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

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

/**
 * Plus Addons Dynamic Tag - User Meta
 *
 * Provides a dynamic tag for Elementor to output the current user meta.
 *
 * @since 6.4.5
 */
class ThePlus_Dynamic_Tag_User_Meta extends Tag {

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

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

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

    /**
     * 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() {
		return true;
	}

    /**
     * Register controls for this dynamic tag.
     *
     * @since 6.4.5
     * @return void
     */
	protected function register_controls(): void {
		$this->add_control(
			'meta_key',
			[
				'label'       => esc_html__( 'Meta Key', 'theplus' ),
				'type'        => \Elementor\Controls_Manager::TEXT,
				'placeholder' => esc_html__( 'Enter user meta key', 'theplus' ),
				'default'     => 'nickname',
			]
		);
	}

    /**
     * Render the dynamic user meta on frontend.
     *
     * Gets the current user and prints its meta details.
     *
     * @since 6.4.5
     * @return void
     */
	public function render(): void {

		$meta_key = $this->get_settings( 'meta_key' );
		if ( empty( $meta_key ) ) {
			return;
		}

		// Resolve which user's meta to read:
		// 1. On an author archive, the queried author.
		// 2. On a singular post, the post's author.
		// 3. Otherwise, the currently logged-in user.
		$user_id = 0;

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

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

		if ( ! $user_id ) {
			return;
		}

		$value = get_user_meta( $user_id, $meta_key, true );

		if ( is_array( $value ) ) {
			$value = implode( ', ', $value );
		}

		echo esc_html( $value );
	}
}
