<?php
/**
 * Class: Author_Picture
 *
 * @return l'URL de l'avatar/gravatar de l'auteur de l'article courant
 * @since 1.6.0
 */

namespace EACCustomWidgets\Includes\Elementor\DynamicTags\Tags;

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

use Elementor\Controls_Manager;
use Elementor\Core\DynamicTags\Data_Tag;
use Elementor\Modules\DynamicTags\Module as TagsModule;

class Author_Picture extends Data_Tag {

	public function get_name(): string {
		return 'eac-addon-author-profile-picture';
	}

	public function get_title(): string {
		return esc_html__( 'Author photo', 'eac-components' );
	}

	public function get_group(): array {
		return array( 'eac-author-groupe' );
	}

	public function get_categories(): array {
		return array(
			TagsModule::IMAGE_CATEGORY,
			TagsModule::MEDIA_CATEGORY,
		);
	}

	protected function register_controls(): void {
		$this->add_control(
			'author_picture_size',
			array(
				'label'   => esc_html__( 'Size', 'eac-components' ),
				'type'    => Controls_Manager::SELECT,
				'default' => '96',
				'options' => array(
					'50'  => '50',
					'60'  => '60',
					'80'  => '80',
					'96'  => '96',
					'120' => '120',
					'140' => '140',
				),
			)
		);
	}

	public function get_value( array $options = array() ): array {
		global $authordata;
		$size = $this->get_settings( 'author_picture_size' );

		/**
		 * La variable globale n'est pas définie
		 */
		if ( ! isset( $authordata->ID ) ) {
			$post = get_post();
			if ( $post ) {
				$authordata = get_userdata( $post->post_author ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
			}
		}

		// @since 1.9.1 Global $authordata n'est pas instanciée
		if ( ! isset( $authordata->ID ) ) {
			return array(
				'url' => '',
				'id'  => '',
			);
		}

		return array(
			'url'   => get_avatar_url( (int) get_the_author_meta( 'ID' ), array( 'size' => $size ) ),
			'id'    => '',
			'alt'   => 'Avatar of ' . ucfirst( $authordata->display_name ),
		);
	}
}
