<?php

namespace humhub\modules\suggestedfollowing\widgets;

use humhub\components\Widget;
use humhub\modules\suggestedfollowing\Module;
use humhub\modules\suggestedfollowing\services\SuggestedFollowingService;
use Yii;

/**
 * Dashboard sidebar widget displaying top suggested accounts to follow.
 *
 * @package humhub\modules\suggestedfollowing\widgets
 */
class SuggestedFollowingDashboardWidget extends Widget
{
    public function run(): string
    {
        if (Yii::$app->user->isGuest) {
            return '';
        }

        /** @var Module $module */
        $module = Yii::$app->getModule('suggestedfollowing');

        $limit = (int) $module->settings->get(
            'maxWidgetSuggestions',
            $module->maxWidgetSuggestions
        );

        $service = new SuggestedFollowingService(Yii::$app->user->identity);
        $suggestions = $service->getSuggestions($limit);

        $currentUserId = (int) Yii::$app->user->id;

        $suggestions = array_values(array_filter(
            $suggestions,
            static function ($suggestion) use ($currentUserId) {
                return isset($suggestion->user)
                    && (int) $suggestion->user->id !== $currentUserId;
            }
        ));

        if (empty($suggestions)) {
            return '';
        }

        return $this->render('dashboardWidget', [
            'suggestions' => $suggestions,
        ]);
    }
}