<?php

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

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

/**
 * Plus Addons Dynamic Tag - User Avatar
 *
 * Provides a dynamic tag for Elementor to output the current user avatar.
 *
 * @since 6.4.5
 */
class ThePlus_Dynamic_Tag_User_Avatar extends Data_Tag {

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

    /**
     * Label shown in Elementor Dynamic Tags list.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_title(): string {
		return esc_html__( 'User Avatar', '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 (Image, Media) for this dynamic tag.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_categories(): array {
		return [
			Module::IMAGE_CATEGORY,
			Module::MEDIA_CATEGORY,
		];
	}

    /**
     * Register controls for this dynamic tag.
     *
     * @since 6.4.5
     * @return void
     */
	protected function register_controls(): void {
		$this->add_control(
			'user_avatar_size',
			[
				'label'   => esc_html__( 'Avatar Size (px)', 'theplus' ),
				'type'    => \Elementor\Controls_Manager::NUMBER,
				'default' => 96,
				'min'     => 20,
				'max'     => 512,
			]
		);
		$this->add_control(
			'tp_fallback',
			[
				'label' => esc_html__( 'Fallback Image', 'theplus' ),
				'type'  => \Elementor\Controls_Manager::MEDIA,
			]
		);
	}

    /**
     * Render the dynamic user avatar on frontend.
     *
     * Gets the current user and show it's avatar.
     *
     * @since 6.4.5
     * @return void
     */
	public function get_value( array $options = [] ) {

		$settings = $this->get_settings();

		$size = ! empty( $settings['user_avatar_size'] ) ? absint( $settings['user_avatar_size'] ) : 96;

		// Resolve which user's avatar to show:
		// 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 $settings['tp_fallback'] ?? [];
		}

		$avatar_url = get_avatar_url( $user_id, [ 'size' => $size ] );

		if ( empty( $avatar_url ) ) {
			return $settings['tp_fallback'] ?? [];
		}

		$attachment_id = attachment_url_to_postid( $avatar_url );

		return [
			'id'  => $attachment_id,
			'url' => $avatar_url,
		];
	}
}
