<?php

if ( ! function_exists( 'ginevra_core_add_author_info_widget' ) ) {
	/**
	 * Function that add widget into widgets list for registration
	 *
	 * @param array $widgets
	 *
	 * @return array
	 */
	function ginevra_core_add_author_info_widget( $widgets ) {
		$widgets[] = 'GinevraCore_Author_Info_Widget';

		return $widgets;
	}

	add_filter( 'ginevra_core_filter_register_widgets', 'ginevra_core_add_author_info_widget' );
}

if ( class_exists( 'QodeFrameworkWidget' ) ) {
	class GinevraCore_Author_Info_Widget extends QodeFrameworkWidget {

		public function map_widget() {
			$this->set_base( 'ginevra_core_author_info' );
			$this->set_name( esc_html__( 'Ginevra Author Info', 'ginevra-core' ) );
			$this->set_description( esc_html__( 'Add author info element into widget areas', 'ginevra-core' ) );
			$this->set_widget_option(
				array(
					'field_type' => 'text',
					'name'       => 'author_username',
					'title'      => esc_html__( 'Author Username', 'ginevra-core' ),
				)
			);
            $this->set_widget_option(
                array(
                    'field_type' => 'text',
                    'name'       => 'author_position',
                    'title'      => esc_html__( 'Author Position', 'ginevra-core' ),
                )
            );
			$this->set_widget_option(
				array(
					'field_type' => 'color',
					'name'       => 'author_color',
					'title'      => esc_html__( 'Author Name Color', 'ginevra-core' ),
				)
			);
		}

		public function render( $atts ) {
			$author_id = 1;
			if ( ! empty( $atts['author_username'] ) ) {
				$author = get_user_by( 'login', $atts['author_username'] );

				if ( ! empty( $author ) ) {
					$author_id = $author->ID;
				}
			}

            $author_position = ! empty( $atts['author_position']) ? $atts['author_position'] : '';

			$author_color = array();
			if ( ! empty( $atts['author_color'])) {
			    $author_color = 'color: ' . $atts['author_color'];
            }

			$author_link = get_author_posts_url( $author_id );
			?>
			<div class="widget qodef-author-info">
				<a itemprop="url" class="qodef-author-info-image" href="<?php echo esc_url( $author_link ); ?>">
					<?php echo get_avatar( $author_id, 150 ); ?>
				</a>
				<?php if ( ! empty( $author ) ) { ?>
					<h6 class="qodef-author-info-name vcard author">
						<a itemprop="url" href="<?php echo esc_url( $author_link ); ?>" <?php qode_framework_inline_style($author_color); ?>>
							<span class="fn"><?php echo esc_html( get_the_author_meta( 'display_name', $author_id ) ); ?></span>
						</a>
					</h6>
					<p class="qodef-author-info-position"><?php echo esc_html( $author_position ); ?></p>
				<?php } ?>
			</div>
			<?php
		}
	}
}
