<?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(
			'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;
		$user   = wp_get_current_user();

		if ( ! $user || ! $user->ID ) {
			return $settings['fallback'] ?? [];
		}

		$avatar_url = get_avatar_url( $user->ID, [ 'size' => $size ] );

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

		$attachment_id = attachment_url_to_postid( $avatar_url );

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