<?php

namespace App\Http\Middleware;

use App\Core\Permission\RoutePermissionAuthorize;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class UserRoutePermissionAuthorize
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */

    private $routePermissionAuthorize;
    
    public function __construct ( RoutePermissionAuthorize $routePermissionAuthorize )
    {
        $this->routePermissionAuthorize  =$routePermissionAuthorize;
    }
    
    public function handle($request, Closure $next, $guard = null)
    {

        $params = $request->params;
        $requestParams = [
            'property_id' => fillOnUndefined($params, 'property_id'),
            'user_id' => $request->credentials->user_id,
        ];

        $result = $this->routePermissionAuthorize->isUserAuthorizedForCurrentRoute($requestParams);

        if ( !$result)
        {
            return apiResponse(0, "Your permission not authorised" , null, 400);
        }
        return $next($request);
    }
}
