<?php

namespace App\Http\Middleware;

use App\Services\VisibilityService;
use Closure;
use Illuminate\Http\Request;

class CheckModuleVisibility
{
    /** @var VisibilityService */
    private $visibility;

    public function __construct(VisibilityService $visibility)
    {
        $this->visibility = $visibility;
    }

    /**
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $moduleKey
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $moduleKeys)
    {
        $user = $request->user();

        if (!$user) {
            abort(403);
        }

        $keys = explode('|', $moduleKeys);
        foreach ($keys as $key) {
            if ($this->visibility->canAccess($user, trim($key))) {
                return $next($request);
            }
        }

        $currentRoute = $request->route() ? $request->route()->getName() : null;
        $landingRoute = $this->visibility->defaultLandingRouteName($user);

        if ($landingRoute && $currentRoute !== $landingRoute && $currentRoute !== 'crm.home') {
            return redirect()
                ->route($landingRoute)
                ->with('warning', 'You do not have access to that page. You were redirected to an area you can use.');
        }

        return redirect()
            ->route('crm.home')
            ->with('warning', 'You do not have access to this module.');
    }
}
