<?php
/**
 * Setup Avatars Component
 *
 * @package Nisje
 */

namespace Dekode\Nisje\Components;

defined( 'ABSPATH' ) || die( 'Shame on you' );

/**
 * Avatars Component Class
 */
class Avatars extends Component {
	/**
	 * Constructor
	 */
	public function __construct() {
		parent::start(
			'avatars',
			__( 'Avatars', 'nisje' )
		);
	}

	/**
	 * Include files
	 */
	public function includes() {
		nisje_include( 'includes/components/avatars/classes/class-nisje-avatar.php' );
		nisje_include( 'includes/components/avatars/helper-functions.php' );
	}

	/**
	 * Setup actions
	 */
	public function setup_filters() {
		add_filter( 'nisje_custom_profile_layouts', [ $this, 'register_profile_layout' ] );
		add_filter( 'nisje_custom_profile_layout_value_avatar', [ $this, 'register_profile_layout_value' ], 10, 2 );
	}

	/**
	 * Register REST Endpoints
	 */
	public function register_rest_routes() {
		nisje_include( 'includes/components/avatars/rest-handlers/extend-user.php' );

		if ( bp_is_active( 'groups' ) ) {
			nisje_include( 'includes/components/avatars/rest-handlers/extend-groups.php' );
		}
	}

	/**
	 * Register Profile Layout
	 *
	 * @param array $layouts Profile Layouts.
	 * @return array $layouts Populated Profile Layouts
	 */
	public function register_profile_layout( $layouts ) {
		$layouts['avatar'] = esc_html__( 'Avatar', 'nisje' );

		return $layouts;
	}

	/**
	 * Register Profile Layout Value
	 *
	 * @param array $field   Profile field.
	 * @param int   $user_id User id.
	 *
	 * @return array Populated Profile Field.
	 */
	public function register_profile_layout_value( $field, $user_id ) {
		return [
			'name'  => esc_html__( 'Avatar', 'nisje' ),
			'value' => nisje_get_user_avatar( $user_id ),
			'type'  => 'avatar',
		];
	}

	/**
	 * Flush Avatars on delete/insert.
	 *
	 * @param array $avatar_params Avatar values.
	 */
	public function flush_cache_filter_avatar( $avatar_params ) {
		$this->flush_cache( $avatar_params['item_id'], $avatar_params['object'] );
	}

	/**
	 * Flush Avatar on update group.
	 *
	 * @param object $group Group object.
	 */
	public function flush_cache_filter_group( $group ) {
		$this->flush_cache( $group->id, 'group' );
	}

	/**
	 * Flush Avatar Cache
	 *
	 * @param int    $id   Object ID.
	 * @param string $type Avatar type.
	 */
	private function flush_cache( $id, $type ) {
		$cache_key = 'nisje_' . $id . '_' . $type . '_avatar';

		wp_cache_delete( $cache_key, 'avatars' );
	}
}
