<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use LaraBB\Forum\Models\Permission;
use LaraBB\Group\Models\Group;
use LaraBB\User\Models\User;

class SetUser
{
    public function handle(Request $request, Closure $next)
    {
        app()->setLocale('de');

        /** @var User $currentUser */
        $currentUser = $request->user();
        if(is_null($currentUser)) {
            $currentUser = auth()->loginUsingId('8d306ec3-26ee-4bc3-918b-c8f79a3c3315');
        }

        $currentUser->load(['profile', 'groups.permissions']);
        if(!$currentUser->isInGroup(['Guest'])) {
            $currentUser->lastactive_at = now();
            $currentUser->lastactive_ip = $request->ip();
            $currentUser->save();
        }

        /** @var Collection forumPermissions */
        $currentUser->forumPermissions = collect();
        $currentUser->groups->sortBy('priority')->map(function(Group $group) use($currentUser) {
            $group->permissions->map(function(Permission $permission) use($currentUser) {
                $currentUser->forumPermissions->put($permission->forum_uuid, $permission);
            });
        });

        view()->share('currentUser', $currentUser);

        return $next($request);
    }
}
