<?php
/**
 * Dynamic Tag: User Avatar
 *
 * @package captain-widgets-kit
 * @since   1.1.0
 */

use Elementor\Core\DynamicTags\Data_Tag;
use Elementor\Modules\DynamicTags\Module;
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
/**
 * Class Captwiki_Tag_User_Avatar_Image
 * Returns the current user's Gravatar as an Elementor image/media dynamic tag.
 */
class Captwiki_Tag_User_Avatar_Image extends Data_Tag {
	/**
	 * Get tag name.
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-tag-user-avatar-image'; }
	/**
	 * Get tag title.
	 *
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'User Avatar', 'captain-widgets-kit' ); }
	/**
	 * Get tag group.
	 *
	 * @return array
	 */
	public function get_group(): array {
		return array( 'captwiki-user' ); }
	/**
	 * Get tag categories.
	 *
	 * @return array
	 */
	public function get_categories(): array {
		return array( Module::IMAGE_CATEGORY, Module::MEDIA_CATEGORY ); }
	/**
	 * Register tag controls.
	 *
	 * @return void
	 */
	protected function register_controls(): void {
		$this->add_control(
			'captwiki_avatar_size',
			array(
				'label'   => esc_html__( 'Avatar Size (px)', 'captain-widgets-kit' ),
				'type'    => \Elementor\Controls_Manager::NUMBER,
				'default' => 96,
				'min'     => 20,
				'max'     => 512,
			)
		);
		$this->add_control(
			'captwiki_fallback',
			array(
				'label' => esc_html__( 'Fallback Image', 'captain-widgets-kit' ),
				'type'  => \Elementor\Controls_Manager::MEDIA,
			)
		);
	}
	/**
	 * Get tag value.
	 *
	 * @param array $options Function parameter.
	 * @return mixed
	 */
	public function get_value( array $options = array() ) {
		$settings = $this->get_settings();
		$size     = ! empty( $settings['captwiki_avatar_size'] ) ? absint( $settings['captwiki_avatar_size'] ) : 96;
		$user     = wp_get_current_user();
		if ( ! $user || ! $user->ID ) {
			return isset( $settings['captwiki_fallback'] ) ? $settings['captwiki_fallback'] : array(); }
		$avatar_url = get_avatar_url( $user->ID, array( 'size' => $size ) );
		if ( empty( $avatar_url ) ) {
			return isset( $settings['captwiki_fallback'] ) ? $settings['captwiki_fallback'] : array(); }
		return array(
			'id'  => attachment_url_to_postid( $avatar_url ),
			'url' => $avatar_url,
		);
	}
}
